1 October 2021

Implementing a trailing stop in MQL5 involves continuously monitoring the market during each tick by iterating through all open positions. This allows the program to check if the market price has moved in a favorable direction, which may warrant adjusting the position's trailing stop. The trailing stop can be adjusted higher or lower based on the market movements, aiming to lock in profits and minimize potential losses. By implementing a trailing stop, traders can benefit from an automated system that helps protect their positions while allowing them to capture gains as the market moves in their favor.

Source code viewer
  1. #include <Trade\PositionInfo.mqh>
  2. #include <Trade\Trade.mqh>
  3. CPositionInfo position;
  4. CTrade trade;
  5.  
  6. input bool trailingStopLoss = true; // Enable trailing stop loss
  7. int stopLossPoints = 1000; // Stop loss in points
  8.  
  9. // Move trailing stop towards profit.
  10. double stopLoss = stopLossPoints * Point();
  11. uint PositionsCount = PositionsTotal();
  12. if(trailingStopLoss && PositionsCount > 0)
  13. {
  14. for(int i = PositionsCount-1; i >= 0; i--)
  15. {
  16. if(position.SelectByIndex(i) && position.Symbol() == Symbol())
  17. {
  18. ENUM_POSITION_TYPE type = position.PositionType();
  19. double CurrentSL = position.StopLoss();
  20. double CurrentTP = position.TakeProfit();
  21. double CurrentPrice = position.PriceCurrent();
  22.  
  23. if(type == POSITION_TYPE_BUY)
  24. {
  25. if(CurrentPrice - stopLoss > CurrentSL || CurrentSL == 0.0)
  26. {
  27. trade.PositionModify(position.Ticket(), NormalizeDouble((CurrentPrice - stopLoss), Digits()), 0);
  28. }
  29. }
  30. if(type == POSITION_TYPE_SELL)
  31. {
  32. if(CurrentPrice + stopLoss < CurrentSL || CurrentSL == 0.0)
  33. {
  34. trade.PositionModify(position.Ticket(), NormalizeDouble((CurrentPrice + stopLoss), Digits()), 0);
  35. }
  36. }
  37. }
  38. }
  39. }
Programming Language: MQL5