1 October 2021

How to implement trailing stop to MQL5. Basically during every tick you iterate through all positions, when trailing stop can be moved higher/lower it will do just that.

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(m_position.SelectByIndex(i) && m_position.Symbol() == m_symbol.Name())
  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(m_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(m_position.Ticket(), NormalizeDouble((CurrentPrice + stopLoss), Digits()), 0);
  35. }
  36. }
  37. }
  38. }
  39. }
Programming Language: MQL5