preview
Building Your Own Expert Advisor (Part 8): ATR and R-Multiple Trailing Stops

Building Your Own Expert Advisor (Part 8): ATR and R-Multiple Trailing Stops

MetaTrader 5 — Examples |
88 0
Solomon Anietie Sunday
Solomon Anietie Sunday

Contents

  1. Introduction
  2. Section 1: Building TrailingStop.mqh
  3. Section 2: Trailing in the Series EA
  4. Verification
  5. What This Part Does Not Do
  6. Conclusion


Introduction

The previous part moved every risk control in the series into a framework of three classes, one for each scope of risk, and closed by suggesting that a trailing stop could become another class alongside them, with its own configuration structure and an additional call in the tick handler. This part builds that class and connects it to the Series EA. The broker's freeze level was set aside in the preceding parts because it governs changes to an order or position that already exists, and nothing in the EA moved a stop. A trailing stop changes the stop of an open position on every move, so the freeze level is checked here as well, against the stop and target the position already carries.

By the end of this part, you will have:

  • TrailingStop.mqh in the Risk Management folder, holding one engine and two trailing methods.
  • An ATR trail and an R-multiple ladder, with break-even as a floor under either.
  • The Series EA trailing its own positions on every tick while its signal is still read once per bar.

Problem: A Stop Set at Entry and Never Revisited

Every control built so far runs before a trade exists. Sizing, the margin checks, the basket limits, and account limits all decide whether a trade may open and how large it may be. After the order is sent, the EA never looks at the stop again. The basket tier can close a losing group of positions, but nothing moves an individual stop. A position that has traveled a long way in its favor, therefore, still carries the stop it was opened with. If the price turns and comes back, and nothing else closes the position first, the trade gives up all of its open profit and then loses the full amount it risked at entry. The take-profit sits at a fixed multiple of the stop distance, and until price reaches it, nothing protects what the trade has gained.

A trailing stop moves the stop behind the price as the trade progresses. Doing that safely is a different problem from the ones solved so far. A pre-trade check that gets something wrong costs a trade, or lets one through at the wrong size. A stop modification that gets something wrong can widen the risk on a live position, be refused by the trade server, or keep resending a refused request on every tick.

Two Questions in Every Trailing Stop

On every evaluation, a trailing stop answers two separate questions. The first is where the stop should move. This is the part that differs between methods. An ATR trail answers it with a distance scaled to recent volatility. An R-multiple ladder answers it with a fixed set of profit milestones. Either calculation is only a few lines of arithmetic. The second is whether the stop may move to that level right now. The engine checks the same four rules for every method before it sends anything:

Rule Why it applies
The stop only moves in the protective direction. A trailing stop that loosens increases the risk on the position.
The new level respects the broker's stop level. The server rejects a stop placed too close to the current price.
The price is outside the freeze distance of the current stop and target.
The server refuses any change to a stop or target that price is about to reach.
The move is at least a minimum step. Each modification is a request to the trade server, and moving a stop by a fraction of a point costs a request while protecting almost nothing.

The framework keeps these two questions separate. Each method answers the first one and returns a price, or zero when it has no proposal. The engine answers the second one for every method, and it is the only code that sends a modification. A method is given no trade object and is never asked to send anything, so every level it proposes goes through the same checks. The checks cover the stop's direction, the stop level, the freeze distance to the current stop and target, and the minimum move size. The checks do not cover the symbol's trade mode, terminal/account trading permissions, tick-size alignment, or the freeze distance to the proposed level. Therefore, a request can still be refused even if it passes all four checks. The engine therefore also reads the server's answer, as the section on sending the modification shows.

Image of why the separation matters

Splitting trailing into interchangeable methods that only calculate a level is a well-established design. The engine in this part also checks the proposed stop against the stop level, and the position's current stop and target against the freeze level, before sending, and reads R from the trade history for the features that need it.

Scope of This Article

One header file is added to the Risk Management folder, and the Series EA includes it. The signal, the sizing, the plan-validate-execute pipeline, and the three risk tiers are unchanged. The header adds:

  • A configuration structure and a context structure describing one position.
  • A base class for trailing methods, with an ATR method and an R-multiple ladder.
  • Break-even as a floor under the active method or on its own.
  • One engine that owns the four checks, reads R from history, and sends every modification.

The EA adds two input groups, a configuration block in OnInit(), one call at the top of OnTick(), and an OnTradeTransaction() handler. The first section below covers the header on its own. The second covers the EA.


Section 1: Building TrailingStop.mqh

The Configuration

The trailing class follows the same pattern as the trade and basket tiers: one configuration structure, filled once by the EA, with a default value for every field.

//+------------------------------------------------------------------+
//| Trailing configuration, filled once by the EA                    |
//+------------------------------------------------------------------+
struct STrailConfig
  {
   long              magic;
   ENUM_TRAIL_METHOD method;
   double            activateAtR;            // 0 = act as soon as a stop can improve

   //--- Break-even
   bool              useBreakEven;
   double            breakEvenAtR;           // Profit in R that moves the stop to entry
   int               breakEvenOffsetPoints;  // Fixed points beyond entry, not the actual costs

   //--- ATR method
   double            atrMultiplier;

   //--- R-ladder method
   double            ladderStepR;            // Rung spacing, in R
   double            ladderLagR;             // How far behind the reached rung to lock, in R

   //--- Guards and logging
   int               minStepPoints;          // Ignore improvements smaller than this
   bool              verbose;                // Log every modification

   void              SetDefaults(void);
  };

method selects which built-in method the engine creates. activateAtR holds everything back until the position is that many R in profit, and zero lets the engine act as soon as a stop can improve. minStepPoints is the smallest move the engine will send. The other fields are covered with the code that reads them.

//+------------------------------------------------------------------+
//| Trailing defaults                                                |
//+------------------------------------------------------------------+
void STrailConfig::SetDefaults(void)
  {
   magic                 = 0;
   method                = TRAIL_OFF;
   activateAtR           = 0.0;
   useBreakEven          = false;
   breakEvenAtR          = 1.0;
   breakEvenOffsetPoints = 20;
   atrMultiplier         = 2.0;
   ladderStepR           = 1.0;
   ladderLagR            = 1.0;
   minStepPoints         = 50;
   verbose               = true;
  }

The defaults switch both the method and break-even off, so an engine that is included and never configured moves nothing.

What a Method Is Given

For each position it evaluates, the engine fills one context structure and passes it to the method as read-only input.

//+------------------------------------------------------------------+
//| Everything a method may read about one position                  |
//+------------------------------------------------------------------+
struct STrailContext
  {
   string            symbol;
   ulong             ticket;
   ENUM_POSITION_TYPE positionType;
   double            entryPrice;
   double            currentSL;
   double            currentTP;
   double            bid;
   double            ask;
   double            closePrice;       // Bid for a buy, Ask for a sell
   double            profitDistance;   // How far closePrice is beyond entry
   double            originalRisk;     // R in price units, 0 when unknown
   double            atrValue;
   double            point;
   int               digits;
  };

closePrice is Bid for a buy and Ask for a sell, because that is the price the position's stop is tested against. profitDistance is how far that price has moved beyond entry, and it is negative while the position is losing. originalRisk is R, the distance between entry and the stop the position was opened with, and it is zero when the engine does not know it. symbol and ticket identify the position, and the point and digits carry the symbol's precision. The convention is that a method reads only from this structure. If a later method needs information that is not here, the change is a new field, and the engine stays the only code that reads positions and market prices.

The Method Interface

//+------------------------------------------------------------------+
//| Base class: a method proposes a stop price, or 0 for no proposal |
//+------------------------------------------------------------------+
class CTrailMethod
  {
public:
   virtual          ~CTrailMethod(void) {}

   virtual double    ComputeStopLevel(const STrailContext &ctx) { return 0.0; }
   virtual bool      NeedsOriginalRisk(void) const { return false; }
   virtual string    Name(void) const { return "none"; }
  };

A method implements three functions. ComputeStopLevel() returns a proposed stop price, or zero for no proposal. NeedsOriginalRisk() tells the engine whether this method uses R, because finding R costs a history query, as the section on recovering it explains. Name() labels the log lines.

ATR Trailing

//+------------------------------------------------------------------+
//| ATR trailing                                                     |
//+------------------------------------------------------------------+
class CTrailATR : public CTrailMethod
  {
private:
   double            m_multiplier;

public:
                     CTrailATR(const double multiplier) { m_multiplier = multiplier; }

   virtual double    ComputeStopLevel(const STrailContext &ctx);
   virtual bool      NeedsOriginalRisk(void) const { return false; }
   virtual string    Name(void) const { return "ATR"; }
  };

//+------------------------------------------------------------------+
//| Trail at a volatility-scaled distance behind the closing side    |
//+------------------------------------------------------------------+
double CTrailATR::ComputeStopLevel(const STrailContext &ctx)
  {
   if(ctx.atrValue <= 0 || m_multiplier <= 0)
      return 0.0;

   double distance = ctx.atrValue * m_multiplier;

   if(ctx.positionType == POSITION_TYPE_BUY)
      return ctx.closePrice - distance;

   return ctx.closePrice + distance;
  }

The ATR method places the stop a multiple of ATR behind the closing price. The value it uses is whatever the EA passes to Manage(). The Series EA refreshes it once per bar, as Section 2 shows, so the distance changes at most once per bar while the closing price it is measured from moves on every tick. It proposes a new level on every evaluation, and the minimum-step check decides which of those proposals are large enough to send. When the next bar brings a larger ATR, the proposal falls further behind price and the stop stays where it is, since the engine never moves a stop backwards. When ATR falls, the proposal moves closer, and the stop can advance faster than the price does.

The initial stop and the trail use different multipliers. With the EA's defaults, the initial stop is 1.5 ATR from entry, and the trail follows 2.0 ATR behind price. If ATR has not changed since entry, the first move comes only after price has gone about half an ATR in the trade's favor, plus the minimum step. Setting the trailing multiplier at or below the initial stop multiplier makes the trail start sooner.

R and R-Multiple Ladder

R is the distance between a position's entry price and the stop-loss it was opened with. The engine measures it once, from the order that opened the position, so it assumes the entry price does not change, which holds unless a netting position is added to. A trade that is one R in profit has moved as far in its favor as its stop was placed against it. The Series EA sets its take-profit at TPRatio times the stop distance, which makes the default target 2R. The ladder moves the stop in fixed milestones measured in R.

//+------------------------------------------------------------------+
//| R-multiple ladder trailing                                       |
//+------------------------------------------------------------------+
class CTrailRRLadder : public CTrailMethod
  {
private:
   double            m_stepR;
   double            m_lagR;

public:
                     CTrailRRLadder(const double stepR, const double lagR)
     {
      m_stepR = stepR;
      m_lagR  = lagR;
     }

   virtual double    ComputeStopLevel(const STrailContext &ctx);
   virtual bool      NeedsOriginalRisk(void) const { return true; }
   virtual string    Name(void) const { return "R-ladder"; }
  };

//+------------------------------------------------------------------+
//| Lock whole R multiples as they are cleared                       |
//+------------------------------------------------------------------+
double CTrailRRLadder::ComputeStopLevel(const STrailContext &ctx)
  {
//--- Without the original risk there is no R to count in
   if(ctx.originalRisk <= 0 || m_stepR <= 0 || ctx.profitDistance <= 0)
      return 0.0;

   double profitR = ctx.profitDistance / ctx.originalRisk;

//--- The highest rung fully cleared
   double rung = MathFloor(profitR / m_stepR);
   if(rung < 1)
      return 0.0;

//--- Lock this far behind the rung that was reached
   double lockR = (rung * m_stepR) - m_lagR;
   if(lockR <= 0)
      return 0.0;

   double lockDistance = lockR * ctx.originalRisk;

   if(ctx.positionType == POSITION_TYPE_BUY)
      return ctx.entryPrice + lockDistance;

   return ctx.entryPrice - lockDistance;
  }

Nothing happens until profit reaches a whole rung. Then the stop jumps to lock a whole number of R and stays there until the next rung. The step sets the spacing between rungs, and the lag sets how far behind the reached rung the stop is locked. With a step of 1R, a lag of 1R, and break-even at 1R, the arithmetic works out as follows:

Profit reached Break-even proposes Ladder proposes Stop moves to
Below 1R Nothing Nothing Stays at the original stop, 1R below entry
1R Entry plus offset nothing, since the lock would be 0R
Entry plus offset
2R Entry plus offset +1R +1R
2.9R Entry plus offset +1R Unchanged
3R Entry plus offset +2R +2R

The table illustrates the calculation using those settings. It is not a result from a test run.

If TPRatio is set at its default of 2.0, the position closes at 2R, the same level at which the ladder would make its first move, so with the default settings, the ladder adds nothing beyond break-even. A smaller ladder step, such as 0.5R, would create additional rungs between whole R multiples. For the ladder to lock profit, the take-profit has to sit beyond the rungs it should reach. A TPRatio of 4.0, as an example, leaves room for rungs at 2R and 3R.

The minimum step applies to the ladder as well. When one rung is worth fewer points than minStepPoints, the move to the next rung is too small to send, and the stop stays where it is until the move to a later rung clears the minimum, skipping the rungs in between. With a 1R step and a stop several hundred points wide, a rung is far larger than the default minimum of 50 points, so this arises only with a small step or a very tight stop.

ATR vs Ladder

The figure uses an illustrative price path, with the ATR trail running alone and break-even at 1R combined with the ladder. The ATR stop follows price in small steps and gives part of each advance back to volatility. The ladder ignores everything between rungs and moves in whole R.

The Engine

//+------------------------------------------------------------------+
//| CTrailingStop                                                    |
//+------------------------------------------------------------------+
class CTrailingStop
  {
private:
   STrailConfig      m_cfg;
   string            m_symbol;
   CTrade            m_trade;
   CTrailMethod      *m_method;
   bool              m_ownsMethod;
   datetime          m_pausedBar;       // Bar in which the server refused a modification
   datetime          m_verboseBar;      // Bar the throttled messages belong to
   ulong             m_verboseTickets[]; // Positions already logged on that bar

   //--- Original risk per position, read from history once
   ulong             m_riskIds[];
   double            m_riskValues[];

   double            LookupOriginalRisk(const ulong positionId, const double entryPrice);
   void              PruneRiskCache(const ulong &liveIds[], const int liveCount);

   double            StopsLevelPrice(void) const;
   double            FreezeLevelPrice(void) const;

   bool              IsImprovement(const STrailContext &ctx, const double proposed) const;
   bool              ClearsMinimumStep(const STrailContext &ctx, const double proposed) const;
   bool              RespectsStopsLevel(const STrailContext &ctx, const double proposed) const;
   bool              IsFrozen(const STrailContext &ctx) const;
   bool              VerboseThisBar(const ulong ticket);

   double            BreakEvenLevel(const STrailContext &ctx) const;
   bool              ApplyStop(const STrailContext &ctx, const double newStop);

public:
                     CTrailingStop(void);
                    ~CTrailingStop(void);

   //--- Setup
   bool              Init(const STrailConfig &config, const string symbol = NULL);
   bool              Validate(string &error) const;
   bool              RegisterMethod(CTrailMethod *method);

   //--- Evaluate every position this EA holds
   void              Manage(const double atrValue);

   string            MethodName(void) const;
  };

The engine is the only class in the file that owns a CTrade object. Its private functions cover finding R, the four checks, and sending the modification. The public side is setup, the evaluation call, and the method name for logging. m_method is a pointer to a CTrailMethod. MQL5 reaches a member through a pointer with the same dot it uses for an object, so a call such as m_method.ComputeStopLevel(ctx) runs whichever method the engine holds.

Recovering R From History

The ladder, break-even, and activation threshold all need R, but the obvious source does not provide it. POSITION_SL holds the current stop. Once trailing moves it, the position no longer records where the stop started, and MQL5 has no position property that preserves the original level. The order that opened the position does preserve it. A history order stores the stop it was submitted with, and the documentation states that a position's identifier corresponds to the ticket of the order that opened it.

HistorySelectByPosition() loads that position's orders, and the function reads the stop from the opening order. If no order in that list has the identifier as its ticket, no other order is used in its place, since the documentation names the identifier as the way to find the order that opened a position. The identifier is the key rather than the ticket because the documentation allows a position's ticket to change during some server operations, while the identifier stays fixed for the life of the position.

//+------------------------------------------------------------------+
//| The risk a position was opened with, in price units              |
//+------------------------------------------------------------------+
double CTrailingStop::LookupOriginalRisk(const ulong positionId, const double entryPrice)
  {
   int cached = ArraySize(m_riskIds);
   for(int i = 0; i < cached; i++)
      if(m_riskIds[i] == positionId)
         return m_riskValues[i];

   if(!HistorySelectByPosition(positionId))
      return 0.0;

//--- Nothing in history for this position yet: ask again next time, cache nothing
   int orders = HistoryOrdersTotal();
   if(orders <= 0)
      return 0.0;

//--- The opening order is the one whose ticket is the position's identifier.
//--- No other order is taken in its place.
   bool found = false;
   for(int i = 0; i < orders; i++)
      if(HistoryOrderGetTicket(i) == positionId)
        {
         found = true;
         break;
        }

//--- A stop that cannot be read is not a missing stop: ask again next time
   double orderSL = 0.0;
   if(found && !HistoryOrderGetDouble(positionId, ORDER_SL, orderSL))
      return 0.0;

   double originalRisk = (orderSL > 0) ? MathAbs(entryPrice - orderSL) : 0.0;

   ArrayResize(m_riskIds,    cached + 1);
   ArrayResize(m_riskValues, cached + 1);
   m_riskIds[cached]    = positionId;
   m_riskValues[cached] = originalRisk;

   if(!found)
      PrintFormat("Position #%I64u: the order that opened it is not in the history, so R is unknown. R-based features will not act on it.",
                  positionId);
   else
      if(originalRisk <= 0)
         PrintFormat("Position #%I64u was opened without a stop, so R is undefined. R-based features will not act on it.",
                     positionId);

   return originalRisk;
  }

The stop recorded on the opening order cannot change, so R is cached, and the history is read once per position. Entries for closed positions are removed at the end of each full pass, so the cache holds at most one entry for every position this EA has open. A call made during a refusal pause returns before it reads any position, so it neither adds nor removes anything. A pass cut short by a refusal can add entries but removes none, because it has not seen every open position.

If the history holds no orders for the position yet, which can happen just after a position opens, or its stop cannot be read, nothing is cached, and the lookup runs again on the next evaluation. If the order was sent without a stop, R is zero, a log line reports it, and every R-based feature leaves that position alone. A position whose opening order is missing from a history that holds its other orders is treated the same way, with its own log line. Both results are cached, so the R-based features stay off for that position until it closes, even if the missing order reaches the history later.

The two log lines tell the cases apart, and caching avoids a history query on every tick for as long as the position stays open. The Series EA always sends its stop with the order, so a missing stop only affects a position with the EA's magic number that was opened some other way. After a terminal restart the cache is empty, and the first evaluation reads the same value from the history again, as long as the terminal still holds that position's order history.

Break-Even as a Floor

//+------------------------------------------------------------------+
//| Break-even level for this position, or 0 if not reached yet      |
//+------------------------------------------------------------------+
double CTrailingStop::BreakEvenLevel(const STrailContext &ctx) const
  {
   if(!m_cfg.useBreakEven || ctx.originalRisk <= 0)
      return 0.0;

   if(ctx.profitDistance < m_cfg.breakEvenAtR * ctx.originalRisk)
      return 0.0;

   double offset = m_cfg.breakEvenOffsetPoints * ctx.point;

   if(ctx.positionType == POSITION_TYPE_BUY)
      return ctx.entryPrice + offset;

   return ctx.entryPrice - offset;
  }

Once profit reaches breakEvenAtR times R, break-even proposes a stop at entry plus an offset. In this article, break-even means that level, entry plus a fixed number of points, and not a guarantee of closing without a loss. A stop exactly at entry closes at the entry price, so what a position still loses there is commission, swap, and any slippage. The offset leaves room for those, but it does not read them, so on an account with high commission, or on a position that has paid swap for several days, the default may not cover them.

Furthermore, the engine combines break-even with the active method by taking the better of the two levels: the higher one for a buy and the lower one for a sell. Break-even, therefore, acts as a floor. With the EA's defaults, an unchanged ATR, and a buy, the ATR trail starts lifting the stop before 1R, break-even raises it to entry plus the offset at 1R, and the ATR level takes over again once it exceeds that level by at least the minimum step, which occurs a little past 1.3R. Break-even also works with the method set to off.

The Four Checks

Order Check Rejects when
1 Improvement The level does not move the stop in the protective direction.
2 Minimum step The move is smaller than minStepPoints.
3 Stops level The level is closer to the closing price than the broker allows.
4 Freeze level The price is within the freeze distance of the current stop or target.

The level is rounded to the symbol's precision before any of them run, so each check measures the price the server will receive rather than one that rounding can still move. Prices on the symbol's grid differ by whole points, so floating-point error can only matter for a level exactly on a boundary. Such a level is either skipped until the price moves on, or sent at a distance the documented rules accept.

//+------------------------------------------------------------------+
//| A stop may only move in the protective direction                 |
//+------------------------------------------------------------------+
bool CTrailingStop::IsImprovement(const STrailContext &ctx, const double proposed) const
  {
   if(ctx.currentSL <= 0)
      return true;

   if(ctx.positionType == POSITION_TYPE_BUY)
      return (proposed > ctx.currentSL);

   return (proposed < ctx.currentSL);
  }

//+------------------------------------------------------------------+
//| Is the improvement large enough to send?                         |
//+------------------------------------------------------------------+
bool CTrailingStop::ClearsMinimumStep(const STrailContext &ctx, const double proposed) const
  {
   if(ctx.currentSL <= 0)
      return true;

   if(m_cfg.minStepPoints <= 0)
      return true;

   double improvement = MathAbs(proposed - ctx.currentSL);
   return (improvement >= m_cfg.minStepPoints * ctx.point);
  }

//+------------------------------------------------------------------+
//| The server rejects a stop too close to, or beyond, the price     |
//+------------------------------------------------------------------+
bool CTrailingStop::RespectsStopsLevel(const STrailContext &ctx, const double proposed) const
  {
//--- Even with no broker minimum, the stop must sit at least a point on the protective side
   double minDistance = MathMax(StopsLevelPrice(), ctx.point);

//--- A buy's stop is tested against Bid, a sell's against Ask
   double distance = (ctx.positionType == POSITION_TYPE_BUY)
                     ? ctx.bid - proposed
                     : proposed - ctx.ask;

   return (distance >= minDistance);
  }

The improvement check accepts any proposed level when the position has no stop. Otherwise, it requires a strict improvement, so a method that calculates a bad level can fail to help but can never move an existing stop against the position. A position without a stop skips the improvement and minimum-step checks and takes the first level that clears the stop level and freeze checks. Those set a minimum distance from price and no maximum, so no check judges whether that first stop is a sensible risk for the position. The minimum step is in points, and zero switches it off, following the convention used throughout the framework.

The stop level is measured from Bid for a buy and from Ask for a sell. At entry, the Series EA required the stop distance to cover the stop level plus the spread because a buy enters at Ask while its stop is tested at Bid. Here the distance is measured from the closing price directly, so the spread is already included. A reported stop level of zero means the broker sets no minimum distance, but a stop at or beyond the current price is still invalid, so the check never accepts a distance smaller than one point.

The Freeze Level

SYMBOL_TRADE_FREEZE_LEVEL is the distance, in points, within which the server treats a position's stop or target as about to trigger and refuses to change either of them. For a buy position, Bid must be at least that distance from both the stop and the target before a modification is accepted. For a sell, the same applies to Ask.

//+------------------------------------------------------------------+
//| Modification is refused while price is inside the freeze level   |
//+------------------------------------------------------------------+
bool CTrailingStop::IsFrozen(const STrailContext &ctx) const
  {
   double freezeLevel = FreezeLevelPrice();
   if(freezeLevel <= 0)
      return false;

   if(ctx.currentSL > 0 && MathAbs(ctx.closePrice - ctx.currentSL) < freezeLevel)
      return true;

   if(ctx.currentTP > 0 && MathAbs(ctx.closePrice - ctx.currentTP) < freezeLevel)
      return true;

   return false;
  }

The check measures the stop and the target the position already carries, which is what the server refuses to change. It does not measure the level being proposed. When it triggers, the engine sends nothing and, with verbose on, logs that the position is inside the freeze level, once per bar for each position. VerboseThisBar() keeps that count: it remembers the bar and the positions already logged on it, and starts a new list when the bar changes. The next tick is evaluated normally, so the stop moves as soon as the price leaves the freeze zone. When a symbol reports a freeze level of zero, the check does nothing. The value can be found in the symbol specification in MetaTrader. These conditions are also described in the MQL5 article "The checks a trading robot must pass before publication in the market" by MetaQuotes, for those looking to publish their work on the MQL5 Marketplace.

Sending the Modification

//+------------------------------------------------------------------+
//| Send the modification, keeping the existing take-profit          |
//+------------------------------------------------------------------+
bool CTrailingStop::ApplyStop(const STrailContext &ctx, const double newStop)
  {
   double normalized = NormalizeDouble(newStop, ctx.digits);

   if(ctx.currentSL > 0 && MathAbs(normalized - ctx.currentSL) < ctx.point / 2.0)
      return false;

   bool sent    = m_trade.PositionModify(ctx.ticket, normalized, ctx.currentTP);
   uint retcode = m_trade.ResultRetcode();

//--- A true return means the request passed CTrade's own checks
   if(!sent || (retcode != TRADE_RETCODE_DONE && retcode != TRADE_RETCODE_PLACED))
     {
      m_pausedBar = iTime(m_symbol, PERIOD_CURRENT, 0);
      PrintFormat("Trailing: modifying #%I64u to %.*f was refused. Retcode: %u (%s). Paused until the next bar.",
                  ctx.ticket, ctx.digits, normalized,
                  retcode, m_trade.ResultRetcodeDescription());
      return false;
     }

   if(m_cfg.verbose)
     {
      double movedPoints = (ctx.currentSL > 0)
                           ? MathAbs(normalized - ctx.currentSL) / ctx.point
                           : 0.0;
      PrintFormat("Trailing [%s]: #%I64u stop %.*f -> %.*f (+%.1f pts)",
                  MethodName(), ctx.ticket,
                  ctx.digits, ctx.currentSL, ctx.digits, normalized, movedPoints);
     }

   return true;
  }

The level is rounded to the symbol's digits, and a request identical to the current stop is not sent. The take-profit is passed back unchanged, because PositionModify() sets both levels at once and a zero would remove the target. A true return from PositionModify() means the request passed CTrade's own checks and was sent, not that the server applied it. The return code carries that answer, so both are read, and anything other than TRADE_RETCODE_DONE or TRADE_RETCODE_PLACED is treated as a refusal. Without the second test, a line reporting a moved stop could be printed for a request the server declined. Some refusals clear on the next tick, such as one caused by price sitting too close to the level. Others do not change until something outside the EA does, such as trading being switched off in the terminal.

The engine treats both the same way. It records the current bar and leaves the loop, so no further position is modified in that pass, and every later call returns at its first check until a new bar opens. Without that, a request that keeps being refused would be sent again on every tick, identical or with a level that has moved slightly. The cost falls on the temporary case, where the stop stays at its last accepted level until the next bar, which on a higher timeframe can be a while. With verbose on, each accepted modification prints one line.

The Evaluation Loop

The evaluation loop returns at once when there is neither a method nor break-even or while a refusal pause is in effect. It reads the tick once and decides whether R is needed at all, so an ATR trail with both break-even and the activation threshold disabled never accesses the history. For each of the EA's positions on the symbol, it fills the context, applies the activation threshold, combines the proposal with the break-even floor, and runs the four checks. When the activation threshold is set and R is unknown, the position is left alone.

//+------------------------------------------------------------------+
//| Evaluate every position this EA holds on its symbol              |
//+------------------------------------------------------------------+
void CTrailingStop::Manage(const double atrValue)
  {
   bool hasMethod = (CheckPointer(m_method) != POINTER_INVALID);
   if(!hasMethod && !m_cfg.useBreakEven)
      return;

//--- After a refusal, nothing is sent again until a new bar opens
   if(m_pausedBar != 0)
     {
      if(m_pausedBar == iTime(m_symbol, PERIOD_CURRENT, 0))
         return;
      m_pausedBar = 0;
     }

   MqlTick tick;
   if(!SymbolInfoTick(m_symbol, tick))
      return;

   double point  = SymbolInfoDouble(m_symbol, SYMBOL_POINT);
   int    digits = (int)SymbolInfoInteger(m_symbol, SYMBOL_DIGITS);

   bool needsRisk = m_cfg.useBreakEven || m_cfg.activateAtR > 0 ||
                    (hasMethod && m_method.NeedsOriginalRisk());

   ulong liveIds[];
   int   liveCount = 0;
   ArrayResize(liveIds, PositionsTotal());

   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(!PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL) != m_symbol ||
         PositionGetInteger(POSITION_MAGIC) != m_cfg.magic)
         continue;

      ulong positionId = (ulong)PositionGetInteger(POSITION_IDENTIFIER);
      liveIds[liveCount] = positionId;
      liveCount++;

      STrailContext ctx;
      ctx.symbol       = m_symbol;
      ctx.ticket       = ticket;
      ctx.positionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
      ctx.entryPrice   = PositionGetDouble(POSITION_PRICE_OPEN);
      ctx.currentSL    = PositionGetDouble(POSITION_SL);
      ctx.currentTP    = PositionGetDouble(POSITION_TP);
      ctx.bid          = tick.bid;
      ctx.ask          = tick.ask;
      ctx.atrValue     = atrValue;
      ctx.point        = point;
      ctx.digits       = digits;

      //--- A long closes on Bid, a short on Ask
      ctx.closePrice     = (ctx.positionType == POSITION_TYPE_BUY) ? tick.bid : tick.ask;
      ctx.profitDistance = (ctx.positionType == POSITION_TYPE_BUY)
                           ? ctx.closePrice - ctx.entryPrice
                           : ctx.entryPrice - ctx.closePrice;

      ctx.originalRisk = needsRisk ? LookupOriginalRisk(positionId, ctx.entryPrice) : 0.0;

      //--- Nothing acts until the position has reached the activation level
      if(m_cfg.activateAtR > 0)
        {
         if(ctx.originalRisk <= 0 || ctx.profitDistance < m_cfg.activateAtR * ctx.originalRisk)
            continue;
        }

      //--- Break-even is a floor; the method's proposal is used only when it is better
      double candidate = hasMethod ? m_method.ComputeStopLevel(ctx) : 0.0;
      double breakEven = BreakEvenLevel(ctx);

      if(breakEven > 0)
        {
         if(candidate <= 0)
            candidate = breakEven;
         else
            candidate = (ctx.positionType == POSITION_TYPE_BUY)
                        ? MathMax(candidate, breakEven)
                        : MathMin(candidate, breakEven);
        }

      if(candidate <= 0)
         continue;

      //--- Round to the symbol's precision before the checks
      candidate = NormalizeDouble(candidate, digits);

      //--- Four guards, cheapest rejection first
      if(!IsImprovement(ctx, candidate))
         continue;

      if(!ClearsMinimumStep(ctx, candidate))
         continue;

      if(!RespectsStopsLevel(ctx, candidate))
         continue;

      if(IsFrozen(ctx))
        {
         if(VerboseThisBar(ticket))
            PrintFormat("Trailing: #%I64u is inside the freeze level, modification not permitted right now.",
                        ticket);
         continue;
        }

      //--- A refusal pauses the engine, including the rest of this pass
      if(!ApplyStop(ctx, candidate) && m_pausedBar != 0)
         break;
     }

//--- A pass cut short by a refusal has not seen every open position, so it prunes nothing
   if(m_pausedBar == 0)
      PruneRiskCache(liveIds, liveCount);
  }

A level that fails a check is skipped without a log line, apart from the freeze-level message, and so is every earlier exit: a refusal pause, a missing tick, the activation level not reached, R unknown after the one line that reports it, or nothing to propose. Silence from the engine, therefore, means only that no modification was sent.

Setup and Validation

//+------------------------------------------------------------------+
//| Adopt a configuration and build the selected method              |
//+------------------------------------------------------------------+
bool CTrailingStop::Init(const STrailConfig &config, const string symbol = NULL)
  {
//--- A configuration that fails validation is not adopted
   STrailConfig previous = m_cfg;
   m_cfg = config;

   string error = "";
   if(!Validate(error))
     {
      m_cfg = previous;
      Print("CTrailingStop: ", error);
      return false;
     }

   m_symbol    = (symbol == NULL || symbol == "") ? _Symbol : symbol;
   m_pausedBar = 0;

   m_trade.SetExpertMagicNumber(m_cfg.magic);

   if(m_ownsMethod && CheckPointer(m_method) == POINTER_DYNAMIC)
      delete m_method;
   m_method     = NULL;
   m_ownsMethod = false;

   switch(m_cfg.method)
     {
      case TRAIL_ATR:
         m_method     = new CTrailATR(m_cfg.atrMultiplier);
         m_ownsMethod = true;
         break;
      case TRAIL_RR_LADDER:
         m_method     = new CTrailRRLadder(m_cfg.ladderStepR, m_cfg.ladderLagR);
         m_ownsMethod = true;
         break;
      default:
         break;
     }

   return true;
  }
Initialization validates the new configuration before adopting it and then builds the selected method. A configuration that fails validation is not adopted, so an engine that is already running keeps the settings and method it had. Validation follows the same approach as the basket tier. It returns immediately when neither a method nor break-even is enabled and otherwise checks only the settings the selected features read, so a setting that will never be used cannot stop the EA from starting. It rejects a zero or negative ATR multiplier, ladder step or break-even trigger, and a negative ladder lag, minimum step, activation threshold or break-even offset, so the break-even level never sits on the losing side of entry.

//+------------------------------------------------------------------+
//| Use a method the library does not ship. Call after Init().       |
//+------------------------------------------------------------------+
bool CTrailingStop::RegisterMethod(CTrailMethod *method)
  {
   if(CheckPointer(method) == POINTER_INVALID)
      return false;

   if(m_ownsMethod && CheckPointer(m_method) == POINTER_DYNAMIC)
      delete m_method;

   m_method = method;

//--- Only a method created with new is ours to delete
   m_ownsMethod = (CheckPointer(method) == POINTER_DYNAMIC);
   return true;
  }

An EA can also supply its own CTrailMethod subclass. It creates the method with new, hands it over after Init(), and the engine deletes it when the engine is destroyed. A method the EA declared as an ordinary object instead is used the same way and is never deleted by the engine. The call has to come after Init(), because initialization replaces whatever method the engine holds. The engine applies the same four checks to a supplied method as to the built-in ones.


Section 2: Trailing in the Series EA

Including the File

#include <Risk Management/TradeRisk.mqh>
#include <Risk Management/BasketRisk.mqh>
#include <Risk Management/PortfolioRisk.mqh>
#include <Risk Management/TrailingStop.mqh>

The fourth line is the new one. TrailingStop.mqh does not depend on RiskTypes, so it includes only the standard trade library and can be used in an EA that does not use any of the risk tiers.

Two globals join the existing ones: the engine instance and a cached ATR value that the tick clock reads.

//--- Position management, for trades that already exist
CTrailingStop   trailing;

//--- Strategy state
int fastHandle = INVALID_HANDLE;
int slowHandle = INVALID_HANDLE;
int atrHandle  = INVALID_HANDLE;

//--- Read once per bar by the strategy, reused by trailing on every tick
double g_atrValue = 0.0;

The Inputs

input group "Trailing Stop"
input ENUM_TRAIL_METHOD    TrailMethod = TRAIL_ATR;          // Trailing method [OFF = no trailing method]
input double               TrailActivateAtR = 0.0;           // Do nothing until profit reaches this many R [0 = off]
input double               TrailATRMultiplier = 2.0;         // ATR mode: stop distance behind price
input double               TrailLadderStepR = 1.0;           // R-ladder mode: rung spacing in R
input double               TrailLadderLagR = 1.0;            // R-ladder mode: how far behind the rung to lock
input int                  TrailMinStepPoints = 50;          // Ignore improvements smaller than this
input bool                 TrailVerbose = true;              // Log every stop modification

input group "Break-Even"
input bool                 UseBreakEven = true;              // Move the stop beyond entry once in profit
input double               BreakEvenAtR = 1.0;               // Profit in R that triggers it
input int                  BreakEvenOffsetPoints = 20;       // Fixed points beyond entry, not the actual costs

The defaults trail with ATR, and move the stop to break-even at 1R. Setting TrailMethod to TRAIL_OFF and UseBreakEven to false returns the EA to the behavior of the previous version, since the engine then returns before reading any position. Break-even has its own group because it runs with any method or with none.

Configuring the Engine

The block goes at the end of OnInit(), after the account-risk tier.

//--- Position management: what happens to a trade after it exists
   STrailConfig trailCfg;
   trailCfg.SetDefaults();
   trailCfg.magic                 = MagicNumber;
   trailCfg.method                = TrailMethod;
   trailCfg.activateAtR           = TrailActivateAtR;
   trailCfg.useBreakEven          = UseBreakEven;
   trailCfg.breakEvenAtR          = BreakEvenAtR;
   trailCfg.breakEvenOffsetPoints = BreakEvenOffsetPoints;
   trailCfg.atrMultiplier         = TrailATRMultiplier;
   trailCfg.ladderStepR           = TrailLadderStepR;
   trailCfg.ladderLagR            = TrailLadderLagR;
   trailCfg.minStepPoints         = TrailMinStepPoints;
   trailCfg.verbose               = TrailVerbose;

   if(!trailing.Init(trailCfg))
      return INIT_PARAMETERS_INCORRECT;

//--- R-based features need the stop a position was opened with
   if(TrailMethod == TRAIL_RR_LADDER || UseBreakEven || TrailActivateAtR > 0)
      Print("R-based trailing is active. It only acts on positions that were opened with a stop-loss.");

This is not a fourth risk tier. The three tiers from the previous part decide whether a trade may exist, and this class manages a trade after it exists. The closing note reports that the R-based features are active and that they only act on positions opened with a stop.

Two Clocks in One Tick Handler

The signal is still read once per bar. The new-bar check at the top of OnTick() exists to stop one crossover from opening several trades, and that has not changed. A trailing stop manages an existing stop while price continues moving inside the bar. A stop that moves only when a new bar opens can give back the profit from a fast move within the bar, and on a higher timeframe, one bar can cover a large part of the trade.

The trailing call, therefore, goes first in the tick handler, above the new-bar check:

//--- Tick clock: trailing is evaluated on every tick
   trailing.Manage(g_atrValue);

//--- Bar clock: everything below decides at most once per bar
   datetime currentBarTime = iTime(_Symbol, _Period, 0);
   if(currentBarTime == 0)
      return;

The basket checks stay below the new-bar check, where the series originally placed them as a deliberate trade-off, because each pass re-reads every position and prices its margin with OrderCalcMargin(). The trailing evaluation also reads this EA's positions on every tick, but for each one it performs a few comparisons and, on most ticks, stops at the first check without contacting the server.

The ATR method needs an ATR value, and the strategy already copies one when each bar opens. That reading is cached, and every later tick in the bar uses it:

//--- The strategy: the only part of this file that is about trading
   double atrValue = 0.0;
   int direction = ReadSignal(atrValue);

//--- Cached for the tick clock, whether or not a signal was triggered
   if(atrValue > 0)
      g_atrValue = atrValue;

   if(direction == 0)
      return;

The buffer is read at index 0 on the first tick of each bar, so the value belongs to a bar that has only just opened. That bar has almost no range yet, so the value is usually a little lower than the ATR at the previous bar's close, and it is not the value this bar will end with. Copying it again on every tick would follow the forming bar as its range grows, at the cost of a buffer read per tick. Caching it instead gives a trailing distance that changes once per bar under a stop that moves with price on every tick.

Trailing runs above the bar clock, so the first tick of each bar still uses the previous bar's value, and the new one applies from the second tick. If the spread check ends a bar early, the previous value stays in use for that whole bar. Before the first bar has been processed, the cached value is zero, the ATR method proposes nothing, and break-even and the ladder still work.

The two clocks: every tick and new bar

Reacting to a New Position

//+------------------------------------------------------------------+
//| Trade transaction function                                       |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
//--- A new deal means a position opened, closed or changed size
   if(trans.type != TRADE_TRANSACTION_DEAL_ADD)
      return;

   trailing.Manage(g_atrValue);
  }

A new deal can mean that a position opened, a pending order was filled, or an existing position changed or closed. The handler evaluates straight away instead of waiting for the next tick, which on a quiet symbol can take a while. For the crossover EA, whose positions open with a stop, this rarely moves the stop immediately. It is relevant for a pending entry that is filled beyond its price or a position without a stop, for which the ATR method can give a first stop immediately. A deal from another EA or another symbol still triggers a pass. It is the same work the engine does on every tick, and it can only act on this EA's own positions since the engine filters by symbol and magic number.


Verification

Three runs show individual paths of the engine working. All three use the "every tick based on real ticks" model on XAUUSD, M10, from August 21st to September 21st, on a hedging account. They show those paths in those conditions only, and they do not prove the engine correct in general. The paths they do not reach are listed after the last run. Reading the code shows what the engine does with the server's answer: any return code other than TRADE_RETCODE_DONE or TRADE_RETCODE_PLACED is treated as a refusal. Only a run on the target server can show which return codes it uses and which limits actually apply.

Run Settings What the run shows
1. Trailing switched off TrailMethod = TRAIL_OFF, UseBreakEven = false, everything else identical to a run of the previous version on the same symbol, period, and dates.
Every figure in the Backtest results tab matches the previous version.
2. ATR Trail TrailMethod = TRAIL_ATR, UseBreakEven = false, TrailVerbose = true A run of Trailing [ATR] lines on one trade, each new stop beyond the previous one, none moving back.
3. Ladder with break-even TrailMethod = TRAIL_RR_LADDER, step 1.0, lag 1.0, UseBreakEven = true, BreakEvenAtR = 1.0, TPRatio raised to 4.0 One move to entry plus the offset at 1R, then one move at the 2R rung, and no trailing lines between them.

Run 1: Trailing Switched Off

First, we switch off the new features by setting both trailing and break-even to false so we can compare the results directly with the previous version.

Run 1 settings

Here are the results from both versions, run under the same conditions:

Current version resultPrevious version result

Every figure in the two Backtest results tabs is the same, not only the trade count and the net profit: gross profit and gross loss, the largest and average trades, the longest runs of wins and losses, and the balance and equity drawdowns. Different trades would be very unlikely to reproduce all of them at once, although the tab reports totals and does not list the deals themselves. The code gives the reason they match: with the method off and break-even off, the engine returns before it reads a position, so it cannot alter a trade.

Run 2: ATR Trail

The video below shows a Strategy Tester run with Trailing [ATR] where each new stop is beyond the previous one and none moves back.

The log lines behind that run, with the ticket shortened:

CS      0       18:13:51.737    Trade   2026.08.21 02:40:00   order performed sell 1.09 at 4523.40 [#2 sell 1.09 XAUUSD at 4523.40]
CS      0       18:13:51.739    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 02:40:00   CTrade::OrderSend: market sell 1.09 XAUUSD sl: 4532.51 tp: 4486.96 [done at 4523.40]
CS      0       18:13:51.739    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 02:40:00   ORDER_TYPE_SELL placed | Lot: 1.09 | Entry: 4523.40 | SL: 4532.51 | TP: 4486.96 | Stop: 911.0 pts | Intended risk: 100.00
CS      0       18:14:39.833    Trade   2026.08.21 03:06:38   position modified [#2 sell 1.09 XAUUSD 4523.40 sl: 4531.88 tp: 4486.96]
CS      0       18:14:39.834    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 03:06:38   CTrade::OrderSend: modify position #2 XAUUSD (sl: 4531.88, tp: 4486.96) [done]
CS      0       18:14:39.834    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 03:06:38   Trailing [ATR]: #2 stop 4532.51 -> 4531.88 (+63.0 pts)
CS      0       18:14:40.284    Trade   2026.08.21 03:09:29   position modified [#2 sell 1.09 XAUUSD 4523.40 sl: 4531.38 tp: 4486.96]
CS      0       18:14:40.287    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 03:09:29   CTrade::OrderSend: modify position #2 XAUUSD (sl: 4531.38, tp: 4486.96) [done]
CS      0       18:14:40.287    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 03:09:29   Trailing [ATR]: #2 stop 4531.88 -> 4531.38 (+50.0 pts)
CS      0       18:14:40.830    Trade   2026.08.21 03:13:02   position modified [#2 sell 1.09 XAUUSD 4523.40 sl: 4530.67 tp: 4486.96]
CS      0       18:14:40.832    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 03:13:02   CTrade::OrderSend: modify position #2 XAUUSD (sl: 4530.67, tp: 4486.96) [done]
CS      0       18:14:40.832    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 03:13:02   Trailing [ATR]: #2 stop 4531.38 -> 4530.67 (+71.0 pts)
CS      0       18:14:40.834    Trade   2026.08.21 03:13:02   position modified [#2 sell 1.09 XAUUSD 4523.40 sl: 4530.16 tp: 4486.96]
CS      0       18:14:40.836    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 03:13:02   CTrade::OrderSend: modify position #2 XAUUSD (sl: 4530.16, tp: 4486.96) [done]
CS      0       18:14:40.836    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 03:13:02   Trailing [ATR]: #2 stop 4530.67 -> 4530.16 (+51.0 pts)

Run 3: Ladder With Break-Even

We perform the third run with the R-ladder and monitor how the stop moves at each R threshold. The video below shows the move to entry plus the offset at 1R, then the first rung at 2R, with nothing between them. A later rung would need the price to reach 3R before the take-profit at 4R, which this trade did not.

The same run is in the log:

CS      0       18:28:00.605    Trade   2026.08.21 17:50:00   order performed buy 0.6 at 4591.73 [#8 buy 0.6 XAUUSD at 4591.73]
CS      0       18:28:00.607    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 17:50:00   CTrade::OrderSend: market buy 0.60 XAUUSD sl: 4575.36 tp: 4657.21 [done at 4591.73]
CS      0       18:28:00.607    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 17:50:00   ORDER_TYPE_BUY placed | Lot: 0.60 | Entry: 4591.73 | SL: 4575.36 | TP: 4657.21 | Stop: 1637.0 pts | Intended risk: 99.01
CS      0       18:28:01.752    Trade   2026.08.21 18:36:25   position modified [#8 buy 0.6 XAUUSD 4591.73 sl: 4591.93 tp: 4657.21]
CS      0       18:28:01.754    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 18:36:25   CTrade::OrderSend: modify position #8 XAUUSD (sl: 4591.93, tp: 4657.21) [done]
CS      0       18:28:01.754    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 18:36:25   Trailing [R-ladder]: #8 stop 4575.36 -> 4591.93 (+1657.0 pts)
CS      0       18:28:03.442    Trade   2026.08.21 19:48:31   position modified [#8 buy 0.6 XAUUSD 4591.73 sl: 4608.10 tp: 4657.21]
CS      0       18:28:03.444    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 19:48:31   CTrade::OrderSend: modify position #8 XAUUSD (sl: 4608.10, tp: 4657.21) [done]
CS      0       18:28:03.444    FixedMACrossover_Part8 (XAUUSD,M10)     2026.08.21 19:48:31   Trailing [R-ladder]: #8 stop 4591.93 -> 4608.10 (+1617.0 pts)
Each verbose line shows the current trailing stop and the previous level from which it moved. Several paths are not covered by these runs. The freeze-level check only triggers on a symbol whose freeze level is above zero, so it should be read from the symbol specification before expecting its log line. The pause after a refusal, and the retcode check that sets it, are inspection-only. Nor do they reach an instrument whose tick size is larger than a point, a position opened without a stop, R read back after a restart, more than one position open at once, or a netting account. Each of those is described in the section below rather than shown.


What This Part Does Not Do

Trailing manages only this EA's positions on its own symbol, identified by magic number, and one engine serves one symbol. The R-based features depend on the position having been opened with a stop. Without one, R is undefined and the ladder, break-even, and the activation threshold leave that position alone. On a netting account, the position's entry price becomes an average when later deals add to it, while R still comes from the opening order. The crossover EA never adds to a position, so this does not arise here. An EA that adds to positions on a netting account should leave the R-based features off, since they would measure profit from the average entry against the risk of the first order.

Stop levels are rounded to the symbol's digits rather than aligned to its tick size, as are the prices sent by the rest of the framework. On an instrument whose tick size is larger than a point, a level that falls between two ticks can be refused. The refusal pauses trailing until the next bar instead of repeating. The freeze check tests the stop and target a position already carries, which are what the freeze rule for positions covers, and it does not test the level being proposed. On a symbol whose freeze level is larger than its stop level, a new stop can therefore land inside the freeze distance. The next change then waits until the price moves far enough from that stop, and with verbose on, the freeze message is logged meanwhile. If a server refuses such a stop outright, the refusal is logged, and the engine waits for the next bar instead of repeating the request.

After a refusal, the engine pauses until the next bar. If one position keeps being refused, trailing for the EA's other positions on the same symbol is also delayed. The break-even offset is a fixed number of points and does not read actual commission or swap. A proposal that fails a check is skipped silently, apart from the freeze-level message, so a method that never seems to act is usually proposing levels that one of the checks rejects. Partial closes at R milestones are not included. They change the size of a position, which is outside what this class does.

The trailing distance under the ATR method changes once per bar, because the value comes from the strategy's own reading at the bar's open. Within a bar, the stop follows price at a fixed distance, and a volatility change is picked up from the second tick of the next bar.


Conclusion

This part added the first class in the framework that manages a position after it opens: a trailing stop. Each trailing method determines where the stop should move, while a single engine decides whether it may move there and sends the request. The four checks, including the freeze level set aside since the margin article, are written once and apply to every method, including one an EA supplies itself. R is read from the order that opened the position, so the ladder, break-even and the activation threshold keep working after the stop has moved, and after a restart while that order history is still available. The Series EA gained one include, two input groups, one configuration block, a call at the top of the tick handler, and a trade transaction handler. Its signal is still read once per bar, while its stops are now evaluated on every tick.

The source files are attached below.

Filename Description
FixedMACrossover_Part8.mq5 The series EA with trailing stops and break-even. It keeps the crossover, the three risk tiers, and their call sequence and adds the trailing configuration and the per-tick evaluation.
TrailingStop.mqh Implements CTrailingStop, the trailing engine with its four checks, together with the CTrailMethod base class and the ATR and R-ladder methods.

Attached files |
TrailingStop.mqh (26.41 KB)
Reading Parquet Natively in MQL5: Thrift, Snappy and Dictionary Decoding into matrix Without CSV Reading Parquet Natively in MQL5: Thrift, Snappy and Dictionary Decoding into matrix Without CSV
This article shows how to read Apache Parquet files directly in MQL5 without DLLs: a native Thrift Compact Protocol decoder for footer metadata, a native Snappy block decompressor, and a hybrid RLE/bit‑packing decoder for definition levels and dictionary indices. We assemble numeric columns into a matrix with an optional null mask. Scope: flat schemas, INT32/INT64/FLOAT/DOUBLE, UNCOMPRESSED/SNAPPY, DataPageV1, first row group. The result avoids CSV conversions and preserves nulls and types.
Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (CDC Module) Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (CDC Module)
The article presents an interim stage in the implementation of the EEMFlow framework using MQL5. The focus is on the design and integration of a CDC module that includes a Self-Corrector, a Self-Attention mechanism for the corrected flow, and weighted signal aggregation via a confidence mask. The article examines architectural principles, the sequence of forward and backward passes, and the specifics of working with local and global motion features.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Building a Modular Pre-Trade Execution Filter Engine in MQL5 Building a Modular Pre-Trade Execution Filter Engine in MQL5
The article presents a modular pre-trade execution filter for MQL5 as an object-oriented include class. It validates quote freshness, aligns order filling with broker capabilities, applies a rollover freeze window, and detects spread outliers using rolling statistics with a hard cap. An on-chart diagnostic indicator and an EA template with reproducible telemetry show integration and help reduce execution frictions in live trading.