Code Library / Trailing Stop

MQL5 ATR Trailing Stop

ATR-based dynamic trailing stop for MQL5. Adjusts trailing distance based on market volatility.

Language: MQL5 · Category: Trailing Stop · Tags: ATR, trailing stop, MQL5, volatility, dynamic stop

Source code

void ATRTrailingStop(ulong ticket, int atrPeriod, double mult) {
   double atr[];
   int h = iATR(_Symbol, PERIOD_CURRENT, atrPeriod);
   CopyBuffer(h, 0, 0, 1, atr);
   double trailDist = atr[0] * mult;
   if(PositionSelectByTicket(ticket)) {
      double sl = PositionGetDouble(POSITION_SL);
      if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
         double newSL = SymbolInfoDouble(_Symbol, SYMBOL_BID) - trailDist;
         if(newSL > sl) {
            MqlTradeRequest req={}; MqlTradeResult res={};
            req.action=TRADE_ACTION_SLTP; req.position=ticket;
            req.symbol=_Symbol; req.sl=NormalizeDouble(newSL,_Digits);
            req.tp=PositionGetDouble(POSITION_TP); 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