DEV Community

Omais Ali
Omais Ali

Posted on

A trailing stop in MQL5 that does not flood the trade server

Trailing stops are one of the most requested EA features, and one of the most common reasons a broker complains about an EA. The naive version calls PositionModify on every tick the price moves in your favour. On a fast market that can be dozens of modify requests a second.

Here is a version that only modifies when it matters.

Three rules

  1. Move the stop only when the new level improves on the current one by at least a step, for example 10 points.
  2. Respect SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_TRADE_FREEZE_LEVEL, or the request will be rejected anyway.
  3. Never send more than one modify per position per second.

The code

#include <Trade\Trade.mqh>
CTrade trade;
datetime lastModify = 0;

void TrailBuy(ulong ticket, double trailPoints, double stepPoints)
{
   if(!PositionSelectByTicket(ticket)) return;
   if(TimeCurrent() == lastModify) return;           // one request per second

   double pt      = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   double bid     = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double tick    = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   long   stopsLv = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   long   freezeLv= SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL);

   double trail   = trailPoints;
   double minDist = (double)MathMax(stopsLv, freezeLv);
   if(trail < minDist) trail = minDist;

   double newSL = bid - trail / (1.0 / pt);
   newSL = MathFloor(newSL / tick) / (1.0 / tick);   // round down to tick size

   double curSL = PositionGetDouble(POSITION_SL);
   double step  = stepPoints / (1.0 / pt);
   if(curSL != 0.0 && newSL < curSL + step) return;  // not enough improvement

   if(trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP)))
      lastModify = TimeCurrent();
}
Enter fullscreen mode Exit fullscreen mode

The divisions by the reciprocal are just a style choice to keep the arithmetic readable here; use whatever form you prefer in your own code.

Why the step matters

Without a minimum step, a trailing stop that is 30 points behind price will send a request for every single point of movement. With a 10 point step it sends one request for every 10 points, which is gentler on the server and makes your journal readable when you debug.

Testing it

Run it in the Strategy Tester on Every tick based on real ticks and count the modify lines in the journal. If you see several modifies within the same second, the throttle is not working. Then run it on a demo account during a news release, which is where flooding problems usually show up first.

Top comments (0)