MQL5

Trailing stop with a minimum step (anti-spam)

Moves the SL only when the improvement exceeds a minimum step — avoids flooding the server with one-point modifications on every tick, a classic cause of request banning.

Prerequisites

MetaTrader 5, CTrade

MQL5
void TrailWithStep(ulong ticket, double distPoints, double stepPoints)
{
   if(!PositionSelectByTicket(ticket)) return;

   long   type = PositionGetInteger(POSITION_TYPE);
   double sl   = PositionGetDouble(POSITION_SL);
   double tp   = PositionGetDouble(POSITION_TP);

   if(type == POSITION_TYPE_BUY)
   {
      double bid   = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      double newSL = NormalizeDouble(bid - distPoints * _Point, _Digits);
      // On ne bouge que si le gain de SL vaut au moins stepPoints
      if(newSL - sl >= stepPoints * _Point)
         trade.PositionModify(ticket, newSL, tp);
   }
   else
   {
      double ask   = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      double newSL = NormalizeDouble(ask + distPoints * _Point, _Digits);
      if(sl == 0.0 || sl - newSL >= stepPoints * _Point)
         trade.PositionModify(ticket, newSL, tp);
   }
}

Result

2026.06.10 11:15:02.330  TrailStep (XAUUSD,M5)  #812446102 SELL : newSL 2381.45, gain 8 pts < step 50 -> ignoré
2026.06.10 11:16:33.518  TrailStep (XAUUSD,M5)  #812446102 SELL : gain 22 pts < step 50 -> ignoré
2026.06.10 11:18:47.812  TrailStep (XAUUSD,M5)  #812446102 SELL : SL 2382.10 -> 2381.20 (avancée 90 pts)
2026.06.10 11:18:47.860  TrailStep (XAUUSD,M5)  PositionModify OK — 1 requête serveur en 4 minutes au lieu de 240
Trailing StopStepCTradePerformance

Related snippets

Back to the Data Lab