Building Your Own Expert Advisor (Part 9): Point-Based and Indicator Trailing Stops
Contents
- Introduction
- Section 1: Building TrailIndicator.mqh
- Section 2: The New Methods in the Series EA
- What This Part Does Not Do
- Conclusion
Introduction
The previous part added TrailingStop.mqh to the framework. It holds one engine, which checks every proposed stop against four rules before sending it, and two methods: an ATR trail and an R-multiple ladder. It also lets an EA create a method of its own and hand it to the engine after Init(), and the engine applies the same four checks to that method as to the two it ships.
This part uses that route for two common ways of trailing. The first keeps the stop a fixed number of points behind price. The second keeps it behind an indicator line, with a moving average as the working example. Both are written in a separate file that includes the engine.
By the end of this part, you will have:
- TrailIndicator.mqh in the Risk Management folder, holding a fixed-point method and an indicator method.
- A base class that converts a level drawn on the chart into a stop price for both buys and sells.
- The series EA offering five trailing choices from one input, with the two new methods registered at startup.
Problem: Stop Levels Taken From the Chart
A fixed-point trail is plain arithmetic: take the price the position would close at and step back a set number of points. An indicator trail reads a line such as a moving average, places the stop on it, and moves the stop each time the line moves. The symbol property SYMBOL_CHART_MODE indicates whether bars are built from Bid or from the last deal price. On a Bid-based chart, placing the stop on the line works for a buy. A moving average calculated on those bars is a line in Bid, a buy closes at Bid, and its stop is triggered when Bid reaches it, so the line and the stop are at the same price.
A sell closes at Ask, and its stop is triggered when Ask reaches it. With the stop placed exactly on the line, Ask touches the stop while Bid—and the Bid-based chart—remains one spread lower. The trader sees a sell closed at a moving average that the chart never reached. On a symbol with a narrow spread the stop fires slightly early. On a wide-spread symbol, or when the spread widens at a session open or around news, it fires correspondingly earlier.
Part 4 met the same fact when it corrected the minimum stop distance to the stops level plus the spread, because a buy's stop is triggered on Bid and a sell's on Ask. A stop that follows a chart line must apply that fact to the line itself, since the line is quoted in Bid.
Distance Methods and Level Methods
Every trailing method answers the same question: where the stop should be. The methods start from two kinds of price. Distance methods start from the closing price, which the engine sets to Bid for a buy and Ask for a sell; the ATR trail is one, and the fixed-point trail in this part is another. They step back a distance from the price that triggers the stop, so the distance is exact in both directions. On a chart built from Bid, that also means a sell's stop sits the distance plus the spread above the price the chart shows.
Level methods start from a price drawn on the chart: an indicator line, a swing high or low, a Parabolic SAR dot. On a chart built from Bid that price is in Bid, so it can be used as it is for a buy, and for a sell the spread has to be added before the level becomes a stop. The spread added is the one at the moment of the evaluation, not the one at which the stop will later fire.
| Method | Family | Starts from | Spread handling |
|---|---|---|---|
| ATR | Distance | Closing price | Already included |
| R-multiple ladder | Distance | Entry price | Not needed: the lock is a distance from the fill price |
| Fixed points | Distance | Closing price | Already included |
| Indicator line | Level | A line built from Bid | Added for sells by ToStopLevel() |
The framework applies the correction in one place. Every level method inherits from CTrailChartLevel, which converts a chart level into a stop price and adds the spread for sells. A level method reads its level and passes it to that conversion, so it has no way to place a sell stop on a Bid line by mistake. It is the same arrangement the engine uses one layer up, where a method proposes a level and only the engine decides whether it is sent.

The chart shows a sell position trailing a moving average that reads the last closed bar. The red dashed stop sits on the line and fires when Ask reaches it, while Bid stays below both the stop and the line. The blue dotted stop is the same level plus the spread, and the same move does not reach it. The spread is drawn wider than on a typical major pair so the gap can be seen.
Scope of This Article
One header file is added to the Risk Management folder: TrailIndicator.mqh. It includes TrailingStop.mqh and adds:
- CTrailPoints, a fixed-distance method.
- CTrailChartLevel, a base class that converts a chart level into a stop price.
- CTrailIndicator, which trails behind one buffer of an indicator handle, where that buffer holds a price level that suits buys and sells.
TrailingStop.mqh is unchanged, and an EA that only uses the ATR trail and the ladder does not need the new file. The series EA replaces its trailing-method input with an enumeration of its own, gives each method's settings their own input group, and registers the new methods after the engine starts. The signal, the sizing, the three risk tiers and the two clocks in the tick handler are unchanged. The first section covers the header on its own, and the second covers the EA.
Section 1: Building TrailIndicator.mqh
Installing the Engine
The new file includes the engine by a relative path, so it always uses the TrailingStop.mqh in the same folder:
#include "TrailingStop.mqh"
Its include guard follows the framework's naming, RISKMANAGEMENT_TRAILINDICATOR_MQH. An EA can include both files, in either order, and each class is declared once.
Fixed-Point Trailing
//+------------------------------------------------------------------+ //| Fixed-distance trailing | //+------------------------------------------------------------------+ class CTrailPoints : public CTrailMethod { private: int m_distancePoints; public: CTrailPoints(const int distancePoints) { m_distancePoints = distancePoints; } bool IsValid(string &error) const; virtual double ComputeStopLevel(const STrailContext &ctx); virtual bool NeedsOriginalRisk(void) const { return false; } virtual string Name(void) const { return "Points"; } }; //+------------------------------------------------------------------+ //| Settings check, called before the method is registered | //+------------------------------------------------------------------+ bool CTrailPoints::IsValid(string &error) const { error = ""; if(m_distancePoints <= 0) { error = "fixed trailing distance must be greater than zero points."; return false; } return true; } //+------------------------------------------------------------------+ //| Trail a fixed distance behind the closing side | //+------------------------------------------------------------------+ double CTrailPoints::ComputeStopLevel(const STrailContext &ctx) { double distance = m_distancePoints * ctx.point; if(ctx.positionType == POSITION_TYPE_BUY) return ctx.closePrice - distance; return ctx.closePrice + distance; }
The fixed-point method is a distance method, so it needs nothing beyond the context the engine already fills. For a buy it proposes the closing price minus the distance, and for a sell the closing price plus the distance. Because the closing price is Bid for a buy and Ask for a sell, the stop sits exactly the configured number of points from the price the position would close at.
The method does not use R-multiples, so NeedsOriginalRisk() returns false, and the engine only looks up R for it when break-even or the activation threshold is switched on. IsValid() rejects a distance of zero or less. The engine cannot check this setting itself, for a reason covered in the second section.
The first move follows the same logic as the ATR trail. The engine only accepts a proposal that is tighter than the stop the position already has. If the configured distance is smaller than the distance to the initial stop by at least the minimum step, the first evaluation after entry moves the stop in. If it is larger, the stop stays where it is until price has moved the difference in the trade's favor, plus the minimum step.
A Base Class for Chart Levels
//+------------------------------------------------------------------+ //| Base class for methods that trail behind a chart level | //+------------------------------------------------------------------+ class CTrailChartLevel : public CTrailMethod { protected: int m_bufferPoints; // Extra room beyond the level bool m_chartChecked; // The symbol's chart mode has been read bool m_bidChart; // Its bars are built from Bid CTrailChartLevel(void) { m_bufferPoints = 0; m_chartChecked = false; m_bidChart = false; } double ToStopLevel(const STrailContext &ctx, const double chartLevel); }; //+------------------------------------------------------------------+ //| Turn a Bid-built chart level into a stop, or 0 if on wrong side | //+------------------------------------------------------------------+ double CTrailChartLevel::ToStopLevel(const STrailContext &ctx, const double chartLevel) { //--- The conversion assumes bars built from Bid; on any other chart nothing is proposed if(!m_chartChecked) { long mode = 0; if(!SymbolInfoInteger(ctx.symbol, SYMBOL_CHART_MODE, mode)) return 0.0; // Read again on the next evaluation m_bidChart = (mode == SYMBOL_CHART_MODE_BID); m_chartChecked = true; if(!m_bidChart) PrintFormat("Trailing [%s]: %s bars are not built from Bid, so this method proposes no stop", Name(), ctx.symbol); } if(!m_bidChart) return 0.0; if(chartLevel <= 0 || chartLevel == EMPTY_VALUE) return 0.0; double buffer = m_bufferPoints * ctx.point; double stop = 0.0; if(ctx.positionType == POSITION_TYPE_BUY) { stop = chartLevel - buffer; if(stop >= ctx.closePrice) return 0.0; } else { //--- A sell closes on Ask, so a Bid-built level needs the spread added double spread = ctx.ask - ctx.bid; stop = chartLevel + buffer + (spread > 0 ? spread : 0.0); if(stop <= ctx.closePrice) return 0.0; } return stop; }
The constructor is protected, so the class cannot be created on its own; it exists to be inherited. m_bufferPoints is extra room beyond the level, which the derived class sets. ToStopLevel() takes a level read from the chart and returns a stop price, or zero when the level gives no usable stop.
The conversion assumes a Bid-based chart, so ToStopLevel() reads the symbol's SYMBOL_CHART_MODE on its first call and keeps the answer. On a symbol whose bars are built from the last deal price, it prints one line and proposes nothing from then on. That is a choice. On such a chart the line is in neither Bid nor Ask, and a stop placed from it could fire early for a buy, and early or late for a sell, by an amount the method cannot know. The cost is that a level method does not trail on those symbols at all; only break-even, when it is switched on, still moves the stop.
For a buy, the stop is the level minus the buffer. For a sell, it is the level plus the buffer plus the current spread, taken from the context as Ask minus Bid. The spread is added here, once, for every level method that inherits from the class. It is the spread at the moment of the evaluation, so a sell stop placed while the spread is narrow can still fire early if the spread widens later.
The function also returns zero when the level gives no usable stop. A level of zero or EMPTY_VALUE means the indicator has no value for that bar. A buy stop at or above the closing price, or a sell stop at or below it, means the line is on the wrong side of price, such as a moving average above a long position after a sharp drop. In both situations the method proposes nothing and the stop stays where it is, which is also what happens to any proposal that fails one of the engine's four checks.
Indicator Trailing
The indicator method needs one value per evaluation. That is one call to CopyBuffer(), for one element, from a chosen buffer and bar:
double value[1]; ResetLastError(); if(CopyBuffer(m_handle, m_buffer, m_shift, 1, value) != 1)
If the call does not return exactly one value, the method proposes nothing and logs why, as the full function below shows. The class around that call stores the handle, the buffer index, the bar to read, whether the method owns the handle, and whether the last read failed:
//+------------------------------------------------------------------+ //| Indicator trailing: the stop follows one price-level buffer | //+------------------------------------------------------------------+ class CTrailIndicator : public CTrailChartLevel { private: int m_handle; int m_buffer; int m_shift; // 1 = last closed bar, 0 = the forming bar bool m_ownsHandle; string m_label; bool m_readFailing; // The last read failed and was logged public: CTrailIndicator(const int handle, const int buffer, const int shift, const int bufferPoints, const bool ownsHandle, const string label = "Indicator"); ~CTrailIndicator(void); bool IsValid(string &error) const; virtual double ComputeStopLevel(const STrailContext &ctx); virtual bool NeedsOriginalRisk(void) const { return false; } virtual string Name(void) const { return m_label; } }; //+------------------------------------------------------------------+ //| Constructor | //+------------------------------------------------------------------+ CTrailIndicator::CTrailIndicator(const int handle, const int buffer, const int shift, const int bufferPoints, const bool ownsHandle, const string label = "Indicator") { m_handle = handle; m_buffer = buffer; m_shift = shift; m_bufferPoints = bufferPoints; m_ownsHandle = ownsHandle; m_label = label; m_readFailing = false; } //+------------------------------------------------------------------+ //| Release the handle only if this method was given ownership | //+------------------------------------------------------------------+ CTrailIndicator::~CTrailIndicator(void) { if(m_ownsHandle && m_handle != INVALID_HANDLE) IndicatorRelease(m_handle); }
A shift of 1 reads the last closed bar, whose value stays fixed while the next bar forms. A shift of 0 reads the forming bar, whose value changes on every tick. Because the engine never moves a stop backwards, a stop tightened on a value the forming bar later gives back stays where it was put, so a shift of 0 can close a trade on a line the finished bar never drew. A shift of 1 avoids that at the cost of following the line one bar late, and it is the default. With a shift of 1 the line changes once per bar, and most ticks inside a bar produce a proposal the engine has already sent or already rejected.
bufferPoints is the room beyond the line, stored in the base class. label names the method in the engine's log lines, so the EA's moving-average trail prints as Trailing [MA].
ownsHandle tells the method whether to release the handle when it is destroyed, and the destructor does the release. The engine deletes a method it was given with new, so a method that owns its handle frees the indicator when the engine itself is destroyed. The EA does not need an IndicatorRelease() line for it.
//+------------------------------------------------------------------+ //| Settings check, called before the method is registered | //+------------------------------------------------------------------+ bool CTrailIndicator::IsValid(string &error) const { error = ""; if(m_handle == INVALID_HANDLE) { error = "indicator trailing was given an invalid indicator handle."; return false; } if(m_buffer < 0 || m_shift < 0) { error = "indicator buffer and shift cannot be negative."; return false; } if(m_bufferPoints < 0) { error = "indicator trailing buffer cannot be negative."; return false; } return true; } //+------------------------------------------------------------------+ //| Read one indicator value and trail behind it | //+------------------------------------------------------------------+ double CTrailIndicator::ComputeStopLevel(const STrailContext &ctx) { double value[1]; ResetLastError(); if(CopyBuffer(m_handle, m_buffer, m_shift, 1, value) != 1) { //--- Logged when reading starts to fail, not on every tick if(!m_readFailing) PrintFormat("Trailing [%s]: no value from buffer %d at bar %d (error %d, %d bars calculated), no stop proposed", m_label, m_buffer, m_shift, GetLastError(), BarsCalculated(m_handle)); m_readFailing = true; return 0.0; } if(m_readFailing) PrintFormat("Trailing [%s]: buffer %d readable again", m_label, m_buffer); m_readFailing = false; return ToStopLevel(ctx, value[0]); }
IsValid() rejects an invalid handle, a negative buffer index or shift, and a negative buffer distance. ComputeStopLevel() copies one value and passes it to the conversion in the base class. When the copy fails, it prints one line with the error code and the number of bars the indicator has calculated, which BarsCalculated() returns as −1 while the data is not calculated yet. It then stays quiet until a read succeeds, which it reports in one more line, so a failure leaves evidence without a line on every tick.
The class does not know which indicator it reads, and that does not make every indicator fit. A handle fits when its buffer holds a price level and the same buffer can serve both directions, because one method instance trails buys and sells alike. A moving average and Parabolic SAR both qualify: their line sits below price in a rise and above it in a fall, and while the line is on the other side of price, ToStopLevel() returns zero and the stop waits. A single Bollinger band, a channel, or separate support and resistance levels do not, since each gives a different level for each direction. Supporting them would need a second buffer index for sells, a change to the constructor that this part does not make.
Two Ways Data Reaches a Method
The ATR method reads no indicator. The EA copies ATR once per bar for its signal, caches the value, and passes it through Manage(atrValue), which places it in the context. The indicator method reads its own handle when it is evaluated.
Data reaches methods by two routes. Manage() keeps its ATR parameter to preserve the ATR trail's behavior; removing it would require changing the engine, which this part does not do. Closing the gap would mean giving the ATR method its own handle, which would also remove the ATR field from the context and the EA's cached g_atrValue.
The indicator route has a cost the cached ATR avoids. The method copies one buffer value for each of the EA's positions on every tick. With the default shift of 1, the value only changes once per bar, so most of those reads return the number the previous tick already read.
Section 2: The New Methods 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> #include <Risk Management/TrailIndicator.mqh>
The fifth line is new. TrailIndicator.mqh includes TrailingStop.mqh itself, so the fourth line is not strictly needed; it stays so that the EA's dependencies can be read in one place.
Five Choices in One Input
The engine's enumeration, ENUM_TRAIL_METHOD, lists the methods the engine builds itself: none, ATR and the ladder. Listing methods from another file there would mean editing the engine, so the EA declares its own enumeration:
//+------------------------------------------------------------------+ //| Every trailing method this EA can run | //+------------------------------------------------------------------+ enum ENUM_EA_TRAIL { EA_TRAIL_OFF, // No trailing method EA_TRAIL_ATR, // ATR distance EA_TRAIL_RR_LADDER, // R-multiple ladder EA_TRAIL_POINTS, // Fixed points EA_TRAIL_INDICATOR // Indicator line (moving average) };
The trailing inputs now use it, and each method's settings have their own group:
input group "Trailing Stop" input ENUM_EA_TRAIL TrailMethod = EA_TRAIL_ATR; // Trailing method [OFF = no trailing method] input double TrailActivateAtR = 0.0; // Do nothing until profit reaches this many R [0 = off] input int TrailMinStepPoints = 50; // Ignore improvements smaller than this input bool TrailVerbose = true; // Log every stop modification input group "Trailing: ATR and R-Ladder" input double TrailATRMultiplier = 2.0; // ATR: stop distance behind price input double TrailLadderStepR = 1.0; // R-ladder: rung spacing in R input double TrailLadderLagR = 1.0; // R-ladder: how far behind the rung to lock input group "Trailing: Fixed Points" input int TrailPointsDistance = 300; // Stop distance behind price, in points input group "Trailing: Indicator (moving average)" input int TrailMAPeriod = 50; // Moving average period input ENUM_MA_METHOD TrailMAMethod = MODE_EMA; // Moving average type input int TrailIndicatorShift = 1; // Bar to read [1 = last closed, 0 = forming] input int TrailIndicatorBufferPoints = 20; // Extra room beyond the line
The settings every method uses stay in the "Trailing Stop" group. The ATR and ladder settings keep their names and defaults and move into a group of their own, which makes it clear in the properties dialog which settings belong to which method. The "Break-Even" group is unchanged.
The new defaults are a fixed distance of 300 points, and a 50-period exponential moving average read at the last closed bar with 20 points of room beyond it. They are demonstration values, not the result of an optimization, as is the minimum step of 50 points kept from the previous part, and each one is to be set for the symbol, the timeframe and the broker's stops level. A fixed number of points does not carry from one symbol to another: 300 points is 30 pips on a five-digit currency pair and 3.00 on a symbol quoted to two decimals. The trailing average is deliberately not one of the strategy's two simple averages of 10 and 20 periods, because a trail on those lines would tie the exit to the same lines the entry is read from.
While the symbol's stops level is larger than the fixed distance, every proposal of the fixed-point method fails the engine's stops-level check. The buffer is how far price can pass the line before it reaches the stop. The minimum step is the smallest improvement the engine sends, so a smaller step follows price more closely at the cost of more modification requests: with 50 points, the fixed-point run below sent 1,100 of them for 150 positions.
Choosing the Indicator
With EA_TRAIL_INDICATOR selected, the EA creates the moving-average handle the method will read:
//--- Another indicator fits if buffer 0 holds a price level that suits buys and sells int maHandle = iMA(_Symbol, _Period, TrailMAPeriod, 0, TrailMAMethod, PRICE_CLOSE);The EA chooses the indicator, and TrailIndicator.mqh stays the same whichever it is. The EA does change. iSAR() takes a step and a maximum where iMA() takes a period and a method, so switching to it means a new call, inputs for its own settings, and checks on those values in place of the period check. An iCustom() call to an indicator of your own works the same way, as long as buffer 0 holds the level and the level suits both directions; for a level in another buffer, the second argument passed to the method changes with it.
Built-In and Registered Methods
Five choices reach the engine by two routes. ATR and the ladder are built by the engine from STrailConfig, as before, and the EA converts its own choice into the engine's enumeration:
//+------------------------------------------------------------------+ //| The engine builds and validates the two methods it ships | //+------------------------------------------------------------------+ ENUM_TRAIL_METHOD BuiltInTrailMethod() { switch(TrailMethod) { case EA_TRAIL_ATR: return TRAIL_ATR; case EA_TRAIL_RR_LADDER: return TRAIL_RR_LADDER; default: return TRAIL_OFF; } }
For the fixed-point and indicator choices this returns TRAIL_OFF, so Init() builds no method, and the EA creates one and registers it:
//+------------------------------------------------------------------+ //| Build a method the engine does not ship, and register it | //+------------------------------------------------------------------+ bool RegisterTrailMethod() { string error = ""; switch(TrailMethod) { case EA_TRAIL_POINTS: { CTrailPoints *points = new CTrailPoints(TrailPointsDistance); if(points == NULL) { Print("Trailing: the fixed-point method could not be created."); return false; } if(!points.IsValid(error)) { Print("Trailing: ", error); delete points; return false; } return trailing.RegisterMethod(points); } case EA_TRAIL_INDICATOR: { if(TrailMAPeriod < 1) { Print("Trailing: moving average period must be at least 1."); return false; } //--- Another indicator fits if buffer 0 holds a price level that suits buys and sells int maHandle = iMA(_Symbol, _Period, TrailMAPeriod, 0, TrailMAMethod, PRICE_CLOSE); CTrailIndicator *indicator = new CTrailIndicator(maHandle, 0, TrailIndicatorShift, TrailIndicatorBufferPoints, true, "MA"); if(indicator == NULL) { Print("Trailing: the indicator method could not be created."); if(maHandle != INVALID_HANDLE) IndicatorRelease(maHandle); return false; } if(!indicator.IsValid(error)) { Print("Trailing: ", error); delete indicator; // Releases the handle it was given return false; } return trailing.RegisterMethod(indicator); } default: return true; // Built-in method, or no method at all } }
Both functions are called from the trailing block at the end of OnInit():
//--- Position management: what happens to a trade after it exists STrailConfig trailCfg; trailCfg.SetDefaults(); trailCfg.magic = MagicNumber; trailCfg.method = BuiltInTrailMethod(); 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; //--- Methods the engine does not ship are registered after Init() if(!RegisterTrailMethod()) return INIT_PARAMETERS_INCORRECT; //--- R-based features need the stop a position was opened with if(TrailMethod == EA_TRAIL_RR_LADDER || UseBreakEven || TrailActivateAtR > 0) Print("R-based trailing is active. It only acts on positions that were opened with a stop-loss.");
Registration comes after Init(), because Init() replaces whatever method the engine holds. With TrailMethod set to ATR or the ladder, the engine receives the same configuration the previous version gave it, and the registration function returns true without doing anything.
The two routes differ in who checks the settings. For its own methods, the engine checks the settings in Validate() during Init(), so an ATR multiplier of zero stops the EA with a CTrailingStop: message. A registered method's settings never pass through the engine, so the engine cannot check them. Each new class therefore carries its own IsValid(), and RegisterTrailMethod() calls it before handing the method over. A failed check prints the reason with a Trailing: prefix, deletes the object, and makes OnInit() return INIT_PARAMETERS_INCORRECT, the same result a bad built-in setting produces. Before it creates the moving-average handle, the function refuses a period below 1 with its own message, so a bad period is not reported as an invalid handle.
RegisterMethod(), from the previous part, takes ownership of any valid method pointer and returns false only for one that is not valid. The engine deletes the method when it is destroyed, or when Init() or another registration replaces it. A method that fails its own check never reaches the engine, so the function deletes it, and for the indicator method the destructor releases the moving-average handle as well. If new itself fails, it returns NULL, and the function prints a line, releases the handle it had just created, and returns false before anything is called through the pointer. So once a method exists, the engine owns it or this function deletes it, and OnDeinit() is unchanged.
Once a position is open, each move the new methods make is logged by the engine in the format it already uses, with the method's name in brackets. The lines below come from two Strategy Tester runs of the series EA on XAUUSD M10, from 2026.08.21 to 2026.09.21, on a hedging demo account with 100,000 USD at 1:100. Both used every tick based on real ticks from the MetaQuotes-Demo server, so the spread can change within a minute bar as it did in the server's history, and zero latency as the execution delay. No commission was charged, and swap was charged on the positions held past the daily rollover. The lines and counts show how the two methods behave on this history with these settings; another server's ticks, another spread or another delay setting will give other lines and other counts.
Both runs set RiskPercent to 0.1, MaxSpreadPips to 10 and UseBreakEven to false, and left every other input at its default. Break-even was off so that each line is a move the method itself proposed, since the engine logs a break-even move under the method's name too. The first run used the fixed-point method, and these are its first four modifications, with the tester's own lines between them left out:
2026.08.21 02:40:00 Trailing [Points]: #2 stop 4532.51 -> 4526.94 (+557.0 pts) 2026.08.21 03:00:00 Trailing [Points]: #4 stop 4518.14 -> 4523.19 (+505.0 pts) 2026.08.21 03:00:02 Trailing [Points]: #4 stop 4523.19 -> 4523.72 (+53.0 pts) 2026.08.21 03:00:09 Trailing [Points]: #4 stop 4523.72 -> 4524.22 (+50.0 pts)
Position #2 is a sell filled at 4523.40. In the same second as the fill, its stop moved from the initial 4532.51 to 4526.94, which is 354 points above the fill: 300 points of configured distance, measured from Ask as the method computes it, and 54 points between the fill price and the Ask of the tick that evaluated it. Position #4 is a buy, and its two later moves are 53 and 50 points, each clearing the minimum step of 50. Over the month the fixed-point method made 1,100 modifications on 150 positions.
The second run used the moving average, and these are its first six modifications:
2026.08.21 03:16:53 Trailing [MA]: #2 stop 4532.51 -> 4516.27 (+1624.0 pts) 2026.08.21 03:40:00 Trailing [MA]: #4 stop 4520.85 -> 4516.02 (+483.0 pts) 2026.08.21 05:30:00 Trailing [MA]: #6 stop 4515.97 -> 4518.12 (+215.0 pts) 2026.08.21 05:40:00 Trailing [MA]: #6 stop 4518.12 -> 4518.62 (+50.0 pts) 2026.08.21 05:50:00 Trailing [MA]: #6 stop 4518.62 -> 4519.41 (+79.0 pts) 2026.08.21 06:00:00 Trailing [MA]: #6 stop 4519.41 -> 4519.96 (+55.0 pts)
Sell #2 shows the jump the next paragraph describes. Its stop stayed at the initial level for 36 minutes after entry, then moved 1,624 points in one modification to just above the line, and the trade closed on that stop 29 seconds later. Buy #6 shows the shift of 1: each of its moves lands on the open of a ten-minute bar, when the value read from the last closed bar changes, and a bar whose new value did not move the stop far enough produced no line. Over the month this method made 241 modifications on 80 of its 129 positions, and the other 49 closed without one.
A moving-average trail that prints nothing for a while is usually waiting for price to move far enough past the line for the stop behind it to clear the stops level, or proposing levels that are not yet tighter than the current stop by the minimum step. When price first moves far enough past the line, the stop can jump a long way in one modification, from the initial stop to just behind the line.
What This Part Does Not Do
The spread ToStopLevel() adds is the spread at the moment of the evaluation, not the spread when the stop eventually triggers. A sell stop placed in quiet conditions can still trigger early when the spread widens later. This is the same approximation, in the same direction, as the spread allowance for the initial stop. Because the spread is read on every evaluation, a sell's proposed level also moves with the spread inside a bar, and it can tighten when the spread narrows even though the line has not moved; the minimum step keeps small changes from being sent.
The level methods work only on symbols whose bars are built from Bid. On a symbol charted from the last deal price, ToStopLevel() prints one line and proposes nothing, so a level method does not move the stop there; break-even, when it is switched on, still does. The distance methods are not affected.
A failed read of the indicator is logged once, with the error code and the number of bars calculated. A level of zero or EMPTY_VALUE, a line on the wrong side of price, and a proposal that does not improve on the current stop by the minimum step are not logged. A level of zero or below is read as no value, so a level method proposes nothing while its level is there, which matters on a symbol whose price can reach zero or go below it.
One indicator method instance uses one buffer for both directions, so it suits lines that sit below price in a rise and above it in a fall. An indicator with separate levels for buys and sells would need a second buffer index for sells, which this part does not build. A shift of 0 follows the forming bar, and a stop tightened on a value that bar later gives back is not moved back.
Data reaches methods by two routes, the ATR value passed through Manage() and the indicator method's own handle, and the indicator method reads its buffer for each position on every tick.
Carried forward from the previous part: (1) R depends on the opening order being in history. (2) After a refused modification, the engine pauses until the next bar for all managed positions. (3) Stops are rounded to symbol digits, not tick size; if tick size exceeds point size, a modification can be refused and the engine pauses until the next bar. (4) With verbose enabled, the freeze-level message prints once per bar per position while price remains inside the zone.
A trail at a percentage of price, the natural companion to a fixed-point trail on instruments whose price level makes a fixed distance meaningless, is not included.
Conclusion
This part added two trailing methods without modifying the trailing engine. The fixed-point method is a distance method: it steps back a set number of points from the closing price and needs nothing else. The indicator method follows one price-level buffer of an indicator the EA chooses, through a base class that converts a chart level into a stop price on charts built from Bid and adds the spread of the moment for sells, so that a sell stop fires about where the chart shows the line rather than one spread early. The engine applies its four checks to both, as it does to its own methods.
The series EA gained one include, an enumeration of five trailing choices, a settings group for each method, and two short functions that pass the choice to the engine, either as a method the engine builds and validates or as one the EA builds, validates and registers.
The source files are attached below.
| Filename | Description |
|---|---|
| FixedMACrossover_Part9.mq5 | The series EA with five trailing choices. It keeps the crossover, the three risk tiers and the trailing engine, and registers the fixed-point and indicator methods at startup. |
| TrailIndicator.mqh | Implements CTrailPoints, the CTrailChartLevel base class and CTrailIndicator. Requires TrailingStop.mqh in the same folder. |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.