Code Library / Trailing Stop

MQL5 Parabolic SAR Trailing Stop

Use Parabolic SAR as a dynamic trailing stop in MQL5.

Language: MQL5 · Category: Trailing Stop · Tags: Parabolic SAR, trailing stop, MQL5, indicator, dynamic

Source code

void SARTrailingStop(ulong ticket) {
   double sar[];
   int h=iSAR(_Symbol,PERIOD_CURRENT,0.02,0.2);
   CopyBuffer(h,0,0,2,sar);
   if(PositionSelectByTicket(ticket)) {
      double sl=PositionGetDouble(POSITION_SL);
      MqlTradeRequest req={}; MqlTradeResult res={};
      req.action=TRADE_ACTION_SLTP; req.position=ticket;
      req.symbol=_Symbol; req.tp=PositionGetDouble(POSITION_TP);
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
         if(sar[0]>sl && sar[0]<SymbolInfoDouble(_Symbol,SYMBOL_BID))
            {req.sl=NormalizeDouble(sar[0],_Digits); OrderSend(req,res);}
   }
   IndicatorRelease(h);
}

How to use this snippet

This is a building block, not a finished trading system. Paste it into your own MQL5 project, compile it, and test it on a demo account with your broker's real spreads before relying on it. If MetaEditor reports errors, the compilation error fixer can help.

Related snippets