Your Take Profit Is a Guess Until You Log MFE: Building an Excursion Recorder in MQL5
Introduction
Most of us set a take profit the same way. We pick a risk:reward ratio that sounds respectable — 1:2, 1:3 — we backtest it, the curve looks acceptable, and we ship it. The number survives because nothing we habitually look at asks the question that matters: do the trades actually get there?
A profit factor cannot answer that per position or per class, and nor can win rate, equity curve or drawdown. Those describe what happened after your exits fired.
MetaTrader's own extended tester report does go further. It includes MFE-Profits and MAE-Profits Distribution charts, together with the MFE- and MAE-versus-profit correlation charts, and hovering a bar gives you the numbers behind it. That is genuinely useful, and if a single pooled histogram over the whole book is what you need, stop here and use it.
What it cannot do is answer the question per position and per class. Its excursion is pooled across every symbol and expressed in profit, not in R frozen at entry — so a $50 MFE on EURUSD and a $50 MFE on BTCUSD land in the same bucket. It gives you no row per ticket, so you cannot join excursion to the ladder rung that was live, the entry filter that fired, or the asset class the trade belonged to. And it cannot tell you what share of your FX trades ever reached 1.5R, because that is a reach rate by class, not a distribution over the book.
This article builds the missing piece: a small, self-contained MFE/MAE recorder. It writes one CSV row per closed position in R, tagged by symbol and open time. The open time is the first CSV column, so you can join rows to external trade logs by entry timestamp. A companion script then reads that file and prints the reach-rate table per asset class.
One position: what the terminal already gives you, and what the recorder adds

Figure 1. Drawn from a synthetic path to show the mechanism. The trade list records entry and exit; the extended Strategy Tester report adds MFE and MAE pooled across the book. This recorder adds R_peak and R_trough per position. Both are sampled on a timer, so they are bounds on the true excursion rather than the true extremes — the hollow markers are the real peak and trough, which fell between two samples. The gap is drawn larger here than it usually is.
Why the profit factor hides this
Consider two Expert Advisors with identical reports: 60% win rate, profit factor 1.6, and the same net result.
EA A takes trades that typically run to 2.5R before stalling, and exits at 1.5R. It leaves a third of each move on the table, but its target is comfortably inside where the market actually goes.
EA B takes trades that typically stall at 0.9R and exits at 1.5R — which means it almost never exits at its target. Its wins come from the trailing stop catching what it can on the way back down. Its take profit is decoration.
Those are entirely different systems with entirely different fixes. A should widen or trail further. B should lower its target or admit its edge is smaller than it thought.
No summary statistic distinguishes them — win rate, profit factor and net result are identical. The tester's MFE and MAE distributions would separate A from B in aggregate, but would not tell you which rung to move or which class was misfitted, because they pool every symbol into one histogram in profit rather than R. MFE per position distinguishes them immediately.
Measuring excursion in R, not in points
Record excursion in R — multiples of a fixed risk unit — not in points or account currency. Points are not comparable across symbols; a 50-point move is enormous on EURUSD and invisible on BTCUSD. R is dimensionless, so a basket EA trading FX, metals, crypto and indices can be analysed in one table.
R here is a volatility-normalised risk unit, not a figure read back from the order: one R is rMultiple × ATR, measured at the moment of entry, where rMultiple is the value you pass to MFEInit. Set that multiple to the one your own initial stop uses and R becomes your initial stop distance exactly, with the stop sitting at −1R. Set it to something else and R is still a valid, comparable unit — it is simply an ATR unit rather than a stop distance, and anyone reading the output needs to know which convention produced it.
R is computed and frozen at the exact moment of entry, captured through OnTradeTransaction the instant the entry deal appears. If the host EA does not forward OnTradeTransaction, the tracker computes R on the first timer pass after the position appears. This can happen, for example, if the recorder is attached while positions are already open. Such rows carry an approximate R; they are still usable for shape analysis, but they should not be used to compare R_peak exactly across trades whose ATR changed materially in the intervening seconds. Do not recompute R as ATR changes, or your R values will drift and stop being comparable between trades.
R_peak = (best price reached in your favour - entry) / R R_trough = (worst price reached against you - entry) / R R_at_close = (price of the last closing deal - entry) / R R_realized = sum over closing deals of (exit_i - entry) x volume_i / (sum of volume_i) / R
Signs are flipped for sells. R_peak is always zero or positive, R_trough is always zero or negative, and R_at_close and R_realized can be either.
The last two answer different questions. R_at_close is the final exit only. R_realized is the position's actual price result: every closing deal, each weighted by the volume it closed. On a position closed in one deal the two are equal. On a position that scaled out, R_at_close describes only the last leg and understates what the position earned, so results and giveback are judged on R_realized. Neither includes commission or swap.
The recorder
The design constraint is that MFE/MAE must be sampled while the position is open, but written when it is closed. The recorder creates its tracking slot in OnTradeTransaction when the entry deal arrives. This ensures that even positions opened and closed between timer passes still produce a row. Such a row carries its realised outcome, because every exit price is folded into both extremes when the row is written, but it carries nothing beyond that: whatever the position did between the last sample and the exit is not recorded. The alternative, creating the slot only on the first timer pass after the position appears, silently omits such positions entirely, which is a worse failure mode. The trade-off is that peak and trough on a short-lived position are lower bounds rather than true extremes; filter by minutes_open before trusting the reach-rate table on a fast system.
By the time HistoryDealGetTicket() can see the closing deal, the excursion information is gone — the terminal keeps no record of how far an open position travelled. So we track live and flush on disappearance.
The state we keep
Freezing rPoints at entry is the single most important line in this structure. It is what makes two trades taken a week apart on different symbols comparable. Freezing only works if the code actually captures R at the entry moment, not at the first opportunity afterwards. That is why the recorder hooks OnTradeTransaction and computes R from the ATR read at the entry deal — see MFETradeTransaction below. A timer-only tracker would freeze R too, but at whatever ATR the first pass happened to see, which is not necessarily the one the entry logic used.
//+------------------------------------------------------------------+ //| One tracked position | //+------------------------------------------------------------------+ struct MFERecord { ulong ticket; // display identifier only ulong positionId; // stable ID for HistorySelectByPosition string symbol; long type; // POSITION_TYPE_BUY / POSITION_TYPE_SELL double openPrice; // volume-weighted average of the entry fills double volume; // entry volume accumulated so far double rPoints; // one R in POINTS: rMult x ATR, frozen double peakPts; // best excursion in our favour (>= 0) double troughPts; // worst excursion against us (<= 0) datetime openTime; bool alive; // seen during this scan }; MFERecord g_mfe[];
Scope: hedging accounts only. MFEInit() reads ACCOUNT_MARGIN_MODE and, on anything other than a retail hedging account, returns false and leaves the recorder disabled with a message in the log. Netting is not partly supported; it is not supported. A netting position can absorb additions, partial closes and reversals (DEAL_ENTRY_INOUT), and no single R frozen at its first entry describes it.
//+------------------------------------------------------------------+ //| Configure the recorder. Call once from OnInit(). | //| | //| rMultiple defines the risk unit: one R = rMultiple x ATR at the | //| moment of entry. Set it to the multiple your own initial stop | //| uses and R becomes your initial stop distance, with the stop at | //| -1R. Set it to anything else and R is an ATR unit instead. | //| | //| Returns false, and leaves the recorder disabled, on any account | //| that is not a retail hedging account. | //+------------------------------------------------------------------+ bool MFEInit(long magic, double rMultiple = 1.5, int atrPeriod = 14, string fileName = "MFERecorder\\MFE.csv") { g_mfeMagic = magic; g_mfeRMult = (rMultiple > 0 ? rMultiple : 1.5); g_mfeATRPeriod = (atrPeriod > 0 ? atrPeriod : 14); g_mfeFileName = (fileName != "" ? fileName : "MFERecorder\\MFE.csv"); g_mfeHeaderChecked = false; ArrayResize(g_mfe, 0); ENUM_ACCOUNT_MARGIN_MODE mode = (ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE); if(mode != ACCOUNT_MARGIN_MODE_RETAIL_HEDGING) { g_mfeEnabled = false; Print("MFE: recorder disabled - this is not a hedging account. ", "Netting and exchange accounts are not supported."); return false; } g_mfeEnabled = true; return true; }
Finding or creating a slot
Two lookups are needed, and the distinction between them matters. MFEPositionIdSlot finds a slot by the stable position identifier and is what OnTradeTransaction uses, because at that moment the position object may not be selectable at all. MFESlot finds a slot from a live position’s ticket and is what the sampling loop uses, resolving the ticket to its identifier first so that both paths key on the same value.
That distinction also constrains how a slot is built. Because the position may not exist as a selectable object yet, MFEApplyEntryDeal reads nothing from it: the entry deal already carries the position identifier, the symbol, the fill price and volume, the direction and the time, and those are enough. Reaching for PositionSelectByTicket here would fail in exactly the case the function exists to handle.
A position is not always filled in one deal: on a hedging account a market order can still be filled in several deals. The first DEAL_ENTRY_IN creates the slot and the rest are folded into a volume-weighted average, which is what POSITION_PRICE_OPEN would have reported had the position been selectable. Keeping only the first fill would shift the entry anchor, and every excursion on that position with it. R is the exception: it stays frozen at the value computed from the first entry deal, because a risk unit that moves as the position is filled is no longer a unit. Any excursion already sampled was measured from the previous average, so it is rebased by the same shift when the anchor moves — otherwise the peak would be quoted from a price the position no longer opened at.
//+------------------------------------------------------------------+ //| Find a slot by stable position ID, or -1. | //| | //| This is the lookup OnTradeTransaction uses, because at that | //| moment the position object may not yet be selectable by ticket. | //+------------------------------------------------------------------+ int MFEPositionIdSlot(ulong positionId) { for(int i = 0; i < ArraySize(g_mfe); i++) if(g_mfe[i].positionId == positionId) return i; return -1; } //+------------------------------------------------------------------+ //| Find a slot from a live position's ticket, or -1. | //| | //| Resolves the ticket to its position identifier first, so that | //| both lookups use the same key the slot was created with. | //+------------------------------------------------------------------+ int MFESlot(ulong ticket) { if(!PositionSelectByTicket(ticket)) return -1; ulong posId = (ulong)PositionGetInteger(POSITION_IDENTIFIER); return MFEPositionIdSlot(posId); } //+------------------------------------------------------------------+ //| Apply one entry DEAL to the tracking slot for its position. | //| | //| The first DEAL_ENTRY_IN creates the slot. A later one for the | //| same position - a market order filled in several deals - is | //| folded into the volume-weighted average open price, which is | //| what POSITION_PRICE_OPEN would report. Keeping only the first | //| fill would bias every excursion on that position. | //| | //| Nothing here selects a position. At the moment the entry deal | //| arrives the position object may not be selectable yet, and the | //| deal already carries everything the slot needs: the position | //| identifier, the symbol, the fill price and volume, the direction | //| and the time. | //| | //| R stays frozen at the value computed from the FIRST entry deal; | //| later fills move the average price but not the risk unit. | //| | //| The caller has already checked the deal's magic. | //+------------------------------------------------------------------+ int MFEApplyEntryDeal(const ulong positionId, const string symbol, const double rPoints, const long dealType, const double dealPrice, const double dealVolume, const datetime dealTime) { if(rPoints <= 0 || symbol == "" || dealPrice <= 0 || dealVolume <= 0) return -1; if(dealType != DEAL_TYPE_BUY && dealType != DEAL_TYPE_SELL) return -1; //--- a later fill of a position already being tracked int i = MFEPositionIdSlot(positionId); if(i >= 0) { double total = g_mfe[i].volume + dealVolume; if(total <= 0) return i; double newOpen = (g_mfe[i].openPrice * g_mfe[i].volume + dealPrice * dealVolume) / total; // Excursion already sampled was measured from the OLD average. Moving // the anchor without moving those samples would leave a peak and a // trough quoted from a price the position no longer opened at, so // rebase them by the same shift. A buy's excursion falls when the // average rises; a sell's rises. double point = SymbolInfoDouble(g_mfe[i].symbol, SYMBOL_POINT); if(point > 0) { double shiftPts = (newOpen - g_mfe[i].openPrice) / point; double sign = (g_mfe[i].type == POSITION_TYPE_BUY ? -1.0 : 1.0); g_mfe[i].peakPts += sign * shiftPts; g_mfe[i].troughPts += sign * shiftPts; if(g_mfe[i].peakPts < 0.0) // the invariants still hold g_mfe[i].peakPts = 0.0; if(g_mfe[i].troughPts > 0.0) g_mfe[i].troughPts = 0.0; } g_mfe[i].openPrice = newOpen; g_mfe[i].volume = total; return i; } //--- first fill: create the slot int n = ArraySize(g_mfe); ArrayResize(g_mfe, n + 1); g_mfe[n].ticket = positionId; // on hedging, ticket == position id g_mfe[n].positionId = positionId; g_mfe[n].symbol = symbol; g_mfe[n].type = (dealType == DEAL_TYPE_BUY ? POSITION_TYPE_BUY : POSITION_TYPE_SELL); g_mfe[n].openPrice = dealPrice; g_mfe[n].volume = dealVolume; g_mfe[n].rPoints = rPoints; g_mfe[n].peakPts = 0; g_mfe[n].troughPts = 0; g_mfe[n].openTime = dealTime; g_mfe[n].alive = true; return n; } //+------------------------------------------------------------------+ //| Fallback: create a slot from live position data. | //| Used only when OnTradeTransaction was missed (e.g. EA restarted | //| with positions already open). ATR is taken at the next timer | //| pass, not at true entry - such rows use an approximate R. | //+------------------------------------------------------------------+ int MFECreate(ulong ticket) { if(!PositionSelectByTicket(ticket)) return -1; // MFETrack() is callable on its own, so the magic test is repeated here // rather than relying on the caller having filtered. if(PositionGetInteger(POSITION_MAGIC) != g_mfeMagic) return -1; string symbol = PositionGetString(POSITION_SYMBOL); double point = SymbolInfoDouble(symbol, SYMBOL_POINT); if(point <= 0) return -1; double atr = MFEGetATR(symbol); if(atr <= 0) return -1; double rPoints = (atr * g_mfeRMult) / point; if(rPoints <= 0) return -1; ulong posId = (ulong)PositionGetInteger(POSITION_IDENTIFIER); int n = ArraySize(g_mfe); ArrayResize(g_mfe, n + 1); g_mfe[n].ticket = ticket; g_mfe[n].positionId = posId; g_mfe[n].symbol = symbol; g_mfe[n].type = PositionGetInteger(POSITION_TYPE); g_mfe[n].openPrice = PositionGetDouble(POSITION_PRICE_OPEN); // already averaged g_mfe[n].volume = PositionGetDouble(POSITION_VOLUME); g_mfe[n].rPoints = rPoints; g_mfe[n].peakPts = 0; g_mfe[n].troughPts = 0; g_mfe[n].openTime = (datetime)PositionGetInteger(POSITION_TIME); g_mfe[n].alive = true; return n; }
The reason for splitting creation from sampling is that a timer-based tracker can only ever see R after the position exists. OnTradeTransaction fires before the position can disappear from the position pool, so R is captured against the same ATR the entry logic used — not against an ATR that moved in the meantime.
One filter is essential. OnTradeTransaction delivers every deal on the account, not only those produced by this EA. If you create a slot for another trade, the timer scan — which filters by magic — will never update it. The slot is eventually written out with zero excursion, and it looks like a valid position that went nowhere.
//+------------------------------------------------------------------+ //| Capture R at the exact moment of entry, via trade transactions. | //| | //| The host EA must forward OnTradeTransaction to this function: | //| void OnTradeTransaction(...) { MFETradeTransaction(...); } | //| | //| OnTradeTransaction delivers every deal on the ACCOUNT, not only | //| the ones this EA produced, so the magic number is tested here | //| before a slot is created. Without that test a deal from another | //| expert, or a manual trade, creates a slot that the timer scan | //| never updates - because that scan does filter by magic - and the | //| orphan is eventually written out with a zero excursion. | //+------------------------------------------------------------------+ void MFETradeTransaction(const MqlTradeTransaction &trans) { if(!g_mfeEnabled) return; if(trans.type != TRADE_TRANSACTION_DEAL_ADD) return; if(!HistoryDealSelect(trans.deal)) return; if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) != DEAL_ENTRY_IN) return; if(HistoryDealGetInteger(trans.deal, DEAL_MAGIC) != g_mfeMagic) return; // someone else's trade long dealType = HistoryDealGetInteger(trans.deal, DEAL_TYPE); if(dealType != DEAL_TYPE_BUY && dealType != DEAL_TYPE_SELL) return; // balance, credit, commission and the like ulong posId = (ulong)HistoryDealGetInteger(trans.deal, DEAL_POSITION_ID); string sym = HistoryDealGetString(trans.deal, DEAL_SYMBOL); double dealPrice = HistoryDealGetDouble(trans.deal, DEAL_PRICE); double dealVolume = HistoryDealGetDouble(trans.deal, DEAL_VOLUME); datetime dealTime = (datetime)HistoryDealGetInteger(trans.deal, DEAL_TIME); double atr = MFEGetATR(sym); if(atr <= 0) return; double point = SymbolInfoDouble(sym, SYMBOL_POINT); if(point <= 0) return; double rPoints = (atr * g_mfeRMult) / point; MFEApplyEntryDeal(posId, sym, rPoints, dealType, dealPrice, dealVolume, dealTime); }
Sampling
Called for each open position on every management cycle. A five-second timer is plenty — MFE is not a tick-precision measurement, and sampling every tick on a forty-symbol basket is wasted work.
//+------------------------------------------------------------------+ //| Sample one open position's excursion. | //| | //| Measured at the price the position would actually be CLOSED at - | //| bid for a buy, ask for a sell. Using the mid price inflates | //| every MFE by half a spread. | //+------------------------------------------------------------------+ void MFETrack(ulong ticket) { if(!g_mfeEnabled) return; if(!PositionSelectByTicket(ticket)) return; int i = MFESlot(ticket); if(i < 0) i = MFECreate(ticket); if(i < 0) return; string symbol = g_mfe[i].symbol; double point = SymbolInfoDouble(symbol, SYMBOL_POINT); if(point <= 0) return; double excursionPts; if(g_mfe[i].type == POSITION_TYPE_BUY) excursionPts = (SymbolInfoDouble(symbol, SYMBOL_BID) - g_mfe[i].openPrice) / point; else excursionPts = (g_mfe[i].openPrice - SymbolInfoDouble(symbol, SYMBOL_ASK)) / point; if(excursionPts > g_mfe[i].peakPts) g_mfe[i].peakPts = excursionPts; if(excursionPts < g_mfe[i].troughPts) g_mfe[i].troughPts = excursionPts; g_mfe[i].alive = true; }
Note the bid/ask choice. A buy is closed at the bid, so its excursion is measured against the bid. Using the mid price inflates every MFE by half a spread — small on a major, material on a symbol whose spread is a meaningful fraction of its range.
Flushing closed positions
Each cycle, mark everything dead, let MFETrack() revive what still exists, then write out whatever stayed dead.
//+------------------------------------------------------------------+ //| The one call to make from OnTimer(). | //| | //| Marks every tracked position dead, lets MFETrack() revive the | //| ones still open, then writes out whatever stayed dead. | //| A row that fails to write is retained for retry next cycle. | //+------------------------------------------------------------------+ void MFEFlushClosed() { if(!g_mfeEnabled) return; for(int i = 0; i < ArraySize(g_mfe); i++) g_mfe[i].alive = false; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong t = PositionGetTicket(i); if(t == 0) continue; if(!PositionSelectByTicket(t)) continue; if(PositionGetInteger(POSITION_MAGIC) != g_mfeMagic) continue; MFETrack(t); } for(int i = ArraySize(g_mfe) - 1; i >= 0; i--) { if(g_mfe[i].alive) continue; if(MFEWriteRow(i)) ArrayRemove(g_mfe, i, 1); // else: keep the slot, retry next cycle } }
Because the flush iterates PositionsTotal() on a timer rather than reacting to OnTick, every open position is sampled on every pass regardless of which chart the host EA is attached to. That matters for a basket. An OnTick-driven recorder would sample non-chart symbols on the chart symbol’s tick schedule. The error is systematic: when the chart symbol is quiet and a traded symbol is active, peaks are recorded too low on the symbols that moved most.
Recovering the exit: final leg and realised result
The position is gone, so the exits come from history. Select the position's deal history by its identifier and walk every DEAL_ENTRY_OUT and DEAL_ENTRY_OUT_BY deal. The last one gives R_at_close. All of them together, each weighted by its volume, give R_realized, which is the position's actual result when it was closed in stages.
The tracker stores a separate positionId field, taken from the entry deal's DEAL_POSITION_ID (or from POSITION_IDENTIFIER on the fallback path), and uses it for history selection, because that is the key HistorySelectByPosition takes. The ticket is kept only for display; on a hedging account the two are numerically equal.
//+------------------------------------------------------------------+ //| Summarise every closing deal of a position, in points. | //| | //| lastPts the LAST closing deal -> R_at_close | //| realizedPts volume-weighted over ALL closes -> R_realized | //| bestPts most favourable single exit | //| worstPts least favourable single exit | //| | //| On a position closed in one deal lastPts == realizedPts. On a | //| staged exit they differ, and only realizedPts is the position's | //| actual result: it weights each leg by the volume it closed, so | //| it is expressed per unit of the position's full volume. | //| Commission and swap are not included - this is a price result. | //+------------------------------------------------------------------+ bool MFEExitSummary(const int i, double &lastPts, double &realizedPts, double &bestPts, double &worstPts, datetime &closeTime) { lastPts = 0; realizedPts = 0; bestPts = 0; worstPts = 0; closeTime = 0; double point = SymbolInfoDouble(g_mfe[i].symbol, SYMBOL_POINT); if(point <= 0) return false; if(!HistorySelectByPosition(g_mfe[i].positionId)) return false; double sumVol = 0; double sumPtsVol = 0; long lastMsc = -1; bool any = false; for(int d = 0; d < HistoryDealsTotal(); d++) { ulong deal = HistoryDealGetTicket(d); if(deal == 0) continue; long entry = HistoryDealGetInteger(deal, DEAL_ENTRY); if(entry != DEAL_ENTRY_OUT && entry != DEAL_ENTRY_OUT_BY) continue; double price = HistoryDealGetDouble(deal, DEAL_PRICE); double volume = HistoryDealGetDouble(deal, DEAL_VOLUME); if(price <= 0 || volume <= 0) continue; double pts = (g_mfe[i].type == POSITION_TYPE_BUY) ? (price - g_mfe[i].openPrice) / point : (g_mfe[i].openPrice - price) / point; sumVol += volume; sumPtsVol += pts * volume; if(!any) { bestPts = pts; worstPts = pts; } else { bestPts = MathMax(bestPts, pts); worstPts = MathMin(worstPts, pts); } long msc = HistoryDealGetInteger(deal, DEAL_TIME_MSC); if(msc >= lastMsc) // later deal wins, ties to the later index { lastMsc = msc; lastPts = pts; closeTime = (datetime)HistoryDealGetInteger(deal, DEAL_TIME); } any = true; } if(!any || sumVol <= 0) return false; realizedPts = sumPtsVol / sumVol; return true; }
MFEWriteRow returns a boolean. A slot is removed from memory only after a successful write. If the file is locked, the disk is full, or history is temporarily unavailable, the slot survives and is retried on the next cycle — a transient failure no longer loses the row permanently. A permanent failure would retain the slot indefinitely, so if you expect to run for months unattended, add an attempt counter and discard after a few dozen tries rather than carrying a dead slot forever.
If your EA closes positions in stages, the row carries both views. R_at_close is the last exit. R_realized is the volume-weighted result of all of them, expressed per unit of the position's full volume. Use R_realized whenever the question is what the position earned or gave back.Writing the row
Open with FILE_READ|FILE_WRITE, check FileSize() for the header, then FileSeek(SEEK_END). Opening write-only truncates the file, and you lose the history you were trying to build.
The writer also does one piece of arithmetic that the sampler cannot. Every exit price is part of the position's path, but the timer may never see it: a position can close between two passes, and a scale-out can fill beyond the last sample. Folding the best and worst exit into both extremes before the row is written is what guarantees R_at_close and R_realized land inside R_trough and R_peak. That is the definition of MFE and MAE, not a convenience.
R_realized is appended as the tenth column rather than inserted, so anything that reads the first nine columns of an older file keeps working. If the file was started by an earlier version, the recorder says so once in the log.
//+------------------------------------------------------------------+ //| Write one CSV row for a closed position. | //| Returns true on success, false on any failure. | //| | //| Opened READ|WRITE, never WRITE alone: FILE_WRITE on its own | //| truncates the file and destroys the history being collected. | //+------------------------------------------------------------------+ bool MFEWriteRow(int i) { if(g_mfe[i].rPoints <= 0) return false; double lastPts, realizedPts, bestExitPts, worstExitPts; datetime closeTime; if(!MFEExitSummary(i, lastPts, realizedPts, bestExitPts, worstExitPts, closeTime)) return false; // Every exit price is part of the position's path, and the timer may // never have sampled it: a position can close between two passes, or a // scale-out can fill beyond the last sample. Folding the best and worst // exit into the extremes keeps both R_at_close and R_realized inside // [R_trough, R_peak] on every row. double peakPts = MathMax(g_mfe[i].peakPts, bestExitPts); double troughPts = MathMin(g_mfe[i].troughPts, worstExitPts); double rAtClose = lastPts / g_mfe[i].rPoints; double rRealized = realizedPts / g_mfe[i].rPoints; double rPeak = peakPts / g_mfe[i].rPoints; double rTrough = troughPts / g_mfe[i].rPoints; int minutes = (int)((closeTime - g_mfe[i].openTime) / 60); int h = FileOpen(g_mfeFileName, FILE_READ | FILE_WRITE | FILE_CSV | FILE_ANSI, ','); if(h == INVALID_HANDLE) { Print("MFE: cannot open ", g_mfeFileName, ", error ", GetLastError()); return false; } if(FileSize(h) == 0) FileWrite(h, "open_time", "closed_time", "symbol", "ticket", "direction", "R_at_close", "R_peak", "R_trough", "minutes_open", "R_realized"); else MFECheckHeader(h); FileSeek(h, 0, SEEK_END); FileWrite(h, TimeToString(g_mfe[i].openTime, TIME_DATE | TIME_SECONDS), TimeToString(closeTime, TIME_DATE | TIME_SECONDS), g_mfe[i].symbol, (string)g_mfe[i].ticket, (g_mfe[i].type == POSITION_TYPE_BUY ? "BUY" : "SELL"), DoubleToString(rAtClose, 2), DoubleToString(rPeak, 2), DoubleToString(rTrough, 2), (string)minutes, DoubleToString(rRealized, 2)); FileClose(h); return true; }
Wiring it in
//+------------------------------------------------------------------+ //| Expert initialisation function | //+------------------------------------------------------------------+ int OnInit() { MFEInit(InpMagicNumber, 3.0, 14); // magic, R multiple, ATR period EventSetTimer(5); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Timer function | //+------------------------------------------------------------------+ void OnTimer() { // ... your own management ... MFEFlushClosed(); // tracks the living, writes the dead } //+------------------------------------------------------------------+ //| Trade transaction handler | //+------------------------------------------------------------------+ void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result) { MFETradeTransaction(trans); // freezes R at the entry deal } //+------------------------------------------------------------------+
Two calls, plus the forwarded event. The file appears in MQL5/Files/MFERecorder/, or in the tester's own Files directory when running a backtest.
The 3.0 passed to MFEInit() above is the recommended setting for an EA whose initial stop is 3.0 × ATR: R then equals the stop distance, and the stop sits at −1R. It is not the configuration that produced the sample later in this article, which was recorded with a multiple of 1.5 (see the MAE section). To reproduce that scale, call MFEInit(InpMagicNumber, 1.5, 14). MFEInit() returns false on a non-hedging account; test it if you want OnInit() to fail rather than run without the recorder.
Validating the recorder before you trust it
A measurement tool that is quietly wrong is worse than none, because it replaces honest uncertainty with false confidence. Before you tune anything on this data, prove the recorder works.
The Strategy Tester is the right place, and it takes about ten minutes. Run your EA over a short period on one symbol with the recorder attached. The tester writes its own MQL5/Files directory, so the output lands in the tester's sandbox rather than your live folder.
Then check four things against the tester's own trade list.
- The row count matches the number of closed positions the tester reports. If it is short, positions are closing without being flushed.
- Every R_peak is zero or positive, and every R_trough is zero or negative. A sign error here is the single easiest mistake to make and the hardest to spot later.
- R_at_close and R_realized both fall between R_trough and R_peak on every row, and on any position closed in a single deal the two are equal. The writer folds every exit price into both extremes, so the first part holds by construction. A row that violates it means an exit was recovered from the wrong position.
- Spot-check one position by hand. Take its entry and exit from the tester, compute R yourself from the ATR at entry, and confirm the row agrees.
That fourth check is the one people skip and the one that catches the real errors. The first three verify internal consistency; only the hand calculation verifies that the thing being measured is the thing you think it is.
One known limitation worth stating plainly: the recorder creates its tracking slot from the entry deal, so every position produces a row, but the excursion is sampled on the timer. A position that opens and closes inside one timer interval is written with the closing price in both extremes and nothing else, so its peak and trough are lower bounds rather than true extremes. On a five-second timer against H1 trading the gap is negligible. On a scalping system it is not — a large share of rows would carry only their exit, and you would need to sample on every tick and accept the cost. Filter by minutes_open before trusting the reach-rate table on a fast system.Reading the file
The single most informative view is a reach-rate table: for each asset class, the share of positions whose R_peak got to each candidate level.
Here is an illustrative table from 226 positions. Sample metadata: positions closed between 23 September and 15 October 2026 (the earliest entry in the file is 16 September), pooled from two retail MetaTrader 5 hedging accounts, forward-traded on build 6230 rather than backtested. Symbol names are given without broker suffixes and ticket numbers have been renumbered sequentially.
Thirty-two instruments: BTCUSD, ETHUSD, XAUUSD, XAGUSD, fourteen major and cross FX pairs, and five Volatility and High Frequency Vol synthetic indices. Instrument specifications, spreads, swap and symbol availability differ between brokers, so the same recorder run elsewhere will produce different reach rates and different giveback; treat the levels as a worked example, not a universal benchmark.
No data file is attached. What is attached is the recorder and the report script, because a table like the one below only means anything when the rows behind it came from your own symbols, spreads and settings. Run them for a few weeks and you will have your own version of it.
How often a position actually reaches each level

Figure 2. From the 226 positions described above. Each bar is the share of that class whose peak excursion reached the level on the x-axis. The shaded columns mark the EA’s single flat ladder: T1 the first scale-out at 1.5R, T2 the second at 2.5R, TP the take profit at 3.0R.
Class n 0.8R 1.0R 1.2R 1.5R 2.0R 2.5R 3.0R Crypto 72 76% 64% 57% 54% 19% 12% 0% Metals 37 59% 54% 49% 41% 30% 22% 14% FX 76 39% 28% 17% 9% 1% 0% 0% Synthetic 41 44% 34% 29% 15% 10% 2% 0%
| Class | n | 0.8R | 1.0R | 1.2R | 1.5R | 2.0R | 2.5R | 3.0R |
|---|---|---|---|---|---|---|---|---|
| Crypto | 72 | 76% | 64% | 57% | 54% | 19% | 12% | 0% |
| Metals | 37 | 59% | 54% | 49% | 41% | 30% | 22% | 14% |
| FX | 76 | 39% | 28% | 17% | 9% | 1% | 0% | 0% |
| Synthetic | 41 | 44% | 34% | 29% | 15% | 10% | 2% | 0% |
This EA was running a single flat ladder for every symbol: first scale-out at 1.5R, second at 2.5R, take profit at 3.0R. Read the table against those numbers.
The take profit was not merely rare, it was unreachable for three classes out of four. Not one crypto, FX or synthetic position in the sample ever peaked at 3.0R. Crypto came closest and still fell short: its best position peaked at 2.97R. Only metals touched the level at all, 5 positions out of 37. A take profit that fires on one class and never on the other three is not a target; it is an accident of which symbols happened to be in the basket.
The first scale-out was mostly inert on the largest class. On FX — 76 of the 226 positions in the sample, a third of the book and the largest single class, just ahead of crypto’s 72 — 1.5R was reached by only 9% of trades. The staged exit that was supposed to bank part of each winner did almost nothing on the class that supplied the most trades.
And the classes needed different ladders. Crypto’s median peak was 1.54R, metals’ 1.02R, synthetics’ 0.72R, and FX’s 0.51R. One set of numbers cannot serve a spread that wide. Setting each level where roughly half the class reaches it gives different ladders, and makes the staged exit mean something on all of them.
Reading the file without a spreadsheet
Everything above asks you to compute the table by hand. That is fine once. It is not fine monthly, which is the cadence the data actually needs, and a table you have to rebuild in a spreadsheet is a table you will stop rebuilding.
So the companion to the recorder is a script that reads MFE.csv and prints the whole analysis to the Experts log. The only input you must set is the file name. Two more are optional: InpMAEAlarmR, the depth the MAE audit reports (2.5R by default), and InpPerSymbol, a switch for a per-symbol breakdown. It reads up to MAX_ROWS — 20,000 rows — in a single pass. The time is dominated by file reading and logging rather than by the arithmetic.
Three details make the parsing less obvious than it looks.
The first is that MQL5's CSV reading is field-oriented, not line-oriented. With FILE_CSV set, each call to FileReadString() returns one comma-separated field, not one row. A row is therefore read field by field until FileIsLineEnding() reports the end of the line: ten fields in a file from this version, nine in one written before R_realized existed. Reading to the line end rather than a fixed count is what lets one loader accept both. The header row is consumed the same way and discarded.
The second is classification. The recorder writes a symbol name, not an asset class, because the class is an interpretation and interpretations belong in analysis rather than in the log. The script classifies by name, and the order of the tests matters: named synthetic indices are tested first, because several of those names contain substrings that the crypto and metal tests would otherwise match. Get that order wrong and your crypto rows quietly land in the wrong row of the table.
The third is that percentiles need a sorted copy, not a sorted original. ArraySort() sorts in place, so sorting the live array would scramble the correspondence between a position's peak and everything else about it.
//+------------------------------------------------------------------+ //| Classify a symbol by name. | //| | //| Order matters: named synthetics are tested first, because some | //| of those names contain substrings the crypto and metal tests | //| would otherwise match. | //| | //| FREQUENCY is in the synthetic list for a reason worth stating: | //| "High Frequency Vol 10 Index" matches none of the other keywords | //| and would otherwise fall through every test into FX, silently | //| inflating the FX row and shrinking the synthetic one. | //+------------------------------------------------------------------+ int ClassifySymbol(string symbol) { string u = symbol; StringToUpper(u); if(StringFind(u, "VOLATILITY") >= 0 || StringFind(u, "BOOM") >= 0 || StringFind(u, "CRASH") >= 0 || StringFind(u, "STEP") >= 0 || StringFind(u, "JUMP") >= 0 || StringFind(u, "DRIFT") >= 0 || StringFind(u, "FREQUENCY") >= 0 || StringFind(u, "RANGE BREAK") >= 0) return 3; // SYNTHETIC if(StringFind(u, "BTC") >= 0 || StringFind(u, "ETH") >= 0 || StringFind(u, "LTC") >= 0 || StringFind(u, "XRP") >= 0 || StringFind(u, "SOL") >= 0 || StringFind(u, "ADA") >= 0 || StringFind(u, "BNB") >= 0 || StringFind(u, "DOT") >= 0 || StringFind(u, "XMR") >= 0) return 1; // CRYPTO if(StringFind(u, "XAU") >= 0 || StringFind(u, "XAG") >= 0 || StringFind(u, "GOLD") >= 0 || StringFind(u, "SILVER") >= 0) return 2; // METAL return 0; // FX }
The loader is the part that most people get wrong on the first attempt, because the field-at-a-time behaviour is easy to miss.
//+------------------------------------------------------------------+ //| One parsed row of the CSV, with the symbol already classified. | //+------------------------------------------------------------------+ struct Row { string openTime; string symbol; int cls; double rClose; // R_at_close: the final exit only double rPeak; double rTrough; int minutes; double rRealized; // R_realized, valid only when hasRealized bool hasRealized; // row came from a 10-column file }; Row g_rows[]; bool g_useRealized = false; // true only when every row carries R_realized //+------------------------------------------------------------------+ //| Read one CSV line into f[]. Returns the number of fields. | //| | //| With FILE_CSV, FileReadString() returns one FIELD per call, not | //| one row, so a line is read field by field until | //| FileIsLineEnding(). Reading to the line end rather than a fixed | //| count is what lets one loader accept both the 10-column layout | //| and the 9-column layout of earlier versions. | //+------------------------------------------------------------------+ int ReadCsvLine(const int h, string &f[]) { ArrayResize(f, 0); int k = 0; while(!FileIsEnding(h)) { string s = FileReadString(h); ArrayResize(f, k + 1); f[k++] = s; if(FileIsLineEnding(h)) break; } return k; } //+------------------------------------------------------------------+ //| Load the CSV. Returns the number of rows parsed, or -1. | //| | //| The first line is the header and is read and discarded. Rows | //| with ten fields carry R_realized; rows with nine do not. | //+------------------------------------------------------------------+ int LoadRows() { int h = FileOpen(InpFileName, FILE_READ | FILE_CSV | FILE_ANSI, ','); if(h == INVALID_HANDLE) { Print("MFEReport: cannot open MQL5/Files/", InpFileName, " - error ", GetLastError()); Print("This script reads a file your own terminal writes. Attach the recorder"); Print("to a chart, let it run until some positions have closed, and the file"); Print("will appear. No sample file is supplied: the levels only mean anything"); Print("when they come from your own symbols, spreads and settings."); return -1; } ArrayResize(g_rows, 0); int n = 0; int withReal = 0; bool header = true; while(!FileIsEnding(h) && n < MAX_ROWS) { string f[]; int nf = ReadCsvLine(h, f); if(nf == 0 || f[0] == "") // blank or trailing line continue; if(header) // discard the column titles { header = false; continue; } if(nf < 9) // malformed row continue; ArrayResize(g_rows, n + 1); g_rows[n].openTime = f[0]; g_rows[n].symbol = f[2]; g_rows[n].cls = ClassifySymbol(f[2]); g_rows[n].rClose = StringToDouble(f[5]); g_rows[n].rPeak = StringToDouble(f[6]); g_rows[n].rTrough = StringToDouble(f[7]); g_rows[n].minutes = (int)StringToInteger(f[8]); g_rows[n].hasRealized = (nf >= 10 && f[9] != ""); g_rows[n].rRealized = (g_rows[n].hasRealized ? StringToDouble(f[9]) : g_rows[n].rClose); if(g_rows[n].hasRealized) withReal++; n++; } FileClose(h); g_useRealized = (n > 0 && withReal == n); if(withReal > 0 && withReal < n) Print("MFEReport: ", withReal, " of ", n, " rows carry R_realized; the file mixes ", "layouts, so result and giveback fall back to the final exit for all rows."); return n; } //+------------------------------------------------------------------+ //| The result a row is judged on: R_realized when every row has it, | //| otherwise the final exit, R_at_close. | //+------------------------------------------------------------------+ double RowResult(const int i) { return (g_useRealized ? g_rows[i].rRealized : g_rows[i].rClose); }
Note the guard on an empty first field. A CSV written with FileWrite often ends with a trailing newline, and without that check the last iteration appends a row of zeros, which quietly drags every median down.
The shape table uses R_realized when every row carries it. When it does not, because the file came from an earlier version or mixes both layouts, the table falls back to R_at_close and says so in its column titles, medFinalR and finalGiveback. It never presents a final-leg figure as the position's result.
With the rows in memory the rest is counting. The reach-rate table is two nested loops — class by level — and a division.
//+------------------------------------------------------------------+ //| The reach-rate table: share of each class reaching each level. | //+------------------------------------------------------------------+ void PrintReachTable() { string head = Pad("Class", 11) + Pad("n", 6); for(int L = 0; L < N_LEVELS; L++) head += Pad(DoubleToString(Levels[L], 1) + "R", 7); Print(head); for(int c = 0; c < N_CLASSES; c++) { int n = 0; int hit[N_LEVELS]; ArrayInitialize(hit, 0); for(int i = 0; i < ArraySize(g_rows); i++) { if(g_rows[i].cls != c) continue; n++; for(int L = 0; L < N_LEVELS; L++) if(g_rows[i].rPeak >= Levels[L]) hit[L]++; } if(n == 0) continue; string line = Pad(ClassName[c], 11) + Pad(IntegerToString(n), 6); for(int L = 0; L < N_LEVELS; L++) line += Pad(DoubleToString(100.0 * hit[L] / n, 0) + "%", 7); Print(line); } } //+------------------------------------------------------------------+ //| Script entry point | //+------------------------------------------------------------------+ void OnStart() { int n = LoadRows(); if(n <= 0) { Print("MFEReport: no rows to analyse."); return; } Print("=================================================================="); Print(" EXCURSION REPORT - ", n, " closed positions from ", InpFileName); Print("=================================================================="); PrintReachTable(); PrintShape(); PrintMAEAudit(); if(InpPerSymbol) PrintPerSymbol(); Print(""); Print("Reminder: a class with fewer than ~100 rows is indicative, not"); Print("settled. Re-run this monthly and watch whether the levels move."); Print("=================================================================="); }
PrintShape(), PrintMAEAudit() and PrintPerSymbol() follow the same counting pattern and are in the attached file, along with MFEGetATR(), MFECheckHeader(), the configuration globals, the Pad() helper and the level and class constants.
Run it as a script on any chart, and the log fills with the table from the previous section, computed from your own trading rather than mine. The sample file predates the R_realized column, so the shape table below appears in its fallback form. The output looks like this.
Class n 0.5R 0.8R 1.0R 1.2R 1.5R 2.0R 2.5R 3.0R FX 76 51% 39% 28% 17% 9% 1% 0% 0% CRYPTO 72 90% 76% 64% 57% 54% 19% 12% 0% METAL 37 84% 59% 54% 49% 41% 30% 22% 14% SYNTHETIC 41 76% 44% 34% 29% 15% 10% 2% 0% Class n medPeak p90Peak medFinalR finalGiveback FX 76 0.51R 1.44R 0.20R 0.35R CRYPTO 72 1.54R 2.61R 0.51R 0.80R METAL 37 1.02R 3.02R 0.51R 0.49R SYNTHETIC 41 0.72R 1.76R 0.34R 0.40R note: no R_realized column, so result and giveback use the FINAL exit only. On scaled-out positions that understates the result and overstates the giveback. Files from MFETracker 1.20 carry the column.
The rule used here is mechanical and stated so it can be checked: T1 at the class median peak, T3 at the 90th percentile, T2 midway between them, each rounded to the nearest 0.05R.
Giveback: the column that grades your trailing stop
Giveback is the peak minus the result, R_peak minus R_realized: what the position was worth at its best moment, minus what it actually returned across all of its exits. Some giveback is unavoidable and healthy — a trailing stop that gives back nothing is a stop sitting so close that it is stopping you out of noise. The question is proportion.
The sample above predates R_realized, so its giveback is the final-leg figure: R_peak minus the last exit. On a position that scaled out, the legs banked at T1 and T2 are missing from it, so it overstates what the position surrendered. The distortion is uneven across classes, because it only touches positions that reached T1 at 1.5R: 54% of crypto, 41% of metals, 15% of synthetics and 9% of FX. Read the figures below as an upper bound for crypto and metals, and as close to the whole-position value for FX.
With that caveat, crypto's median final leg closed 0.80R below a median peak of 1.54R, and metals' 0.49R below 1.02R. FX, at 0.35R below a 0.51R median peak, surrendered roughly two thirds, and because so few FX positions scaled out, that figure is close to the whole-position value. It is consistent with a trail that engages too late for FX's short moves, but the table alone cannot separate that hypothesis from market differences. Instruments, spreads, volatility regimes and signal composition all differ between classes. To move from description to cause you need a controlled comparison: the same entries over the same period with one trail parameter varied, or the same trail applied across symbols with differing characteristics. Until that test exists, treat this as a diagnostic hypothesis, not a finding. Re-run the table on a file that carries R_realized before drawing conclusions about crypto or metals. The number to compare against is your first target: when median giveback approaches T1, that is a flag worth investigating, not a proven cause.
One caution on reading this column. Giveback on a position that exited at its catastrophic stop is not a trailing-stop failure — the trail never engaged. Separate the two before concluding anything: filter to positions whose result was positive, and the remaining giveback is the part your trailing logic is actually responsible for.
MAE depth: the column that audits your stop logic
MAE is the column that found the real bug.
The system that produced this file was configured with rMultiple at 1.5 and a catastrophic stop at 3.0 × ATR. On that configuration R is an ATR unit rather than the stop distance, and the stop sits at −2R — so no position should ever have printed worse than about −2R. The log says 25% of positions ran past −2.5R, and the worst reached −32.41R. A single number that far outside the design is never a tuning problem. It is a code path.
In this case the stop-attachment routine had a branch for positions already beyond the stop distance at the moment it first ran. It logged a warning and attached nothing, on the reasoning that attaching a stop there would close the trade instantly as a surprise. The reasoning was sound, and the consequence was that those positions stayed unprotected for the rest of their lives.
To be precise about what this was and was not: the system had a stop design and applied it correctly in the normal case. One branch, covering one edge case, skipped attachment and then never revisited the decision. The defect was found through this column, fixed by making that branch attach a stop at the broker's minimum permissible distance instead of attaching none, and the fix shipped in the version that followed this sample period. The table above is from the data that exposed it, so it shows the behaviour before the fix.
In hindsight the mismatch is worth stating plainly, because it is the same mistake in a smaller form: passing 1.5 while stopping at 3.0 meant the output had to be read with a conversion in mind. Passing 3.0 instead would have put the stop at −1R and made the −32.41R row obviously impossible at a glance, rather than obviously impossible after a moment’s arithmetic.
Nothing in the account statement pointed at this. The affected trades mostly recovered and closed positive, so they appear in the report as wins. Only the MAE column shows what they survived on the way.
That is the general lesson, and it is worth more than any target level: the result of a trade tells you what happened; the excursion tells you what was possible, and what was risked. A system can look healthy on results for a long time while carrying an exposure its author does not know about. Check this column first, before you touch a single target. A ladder tuned on a book whose downside is unbounded is a ladder tuned on the wrong system.
Four ways this will mislead you
Sample size. The Metals row above is 37 trades. A reach rate computed on 37 observations has a 95% confidence interval of roughly ±16 percentage points; at the 1.5R level the intervals are ±16 pp for metals, ±12 pp for crypto, ±11 pp for synthetics and ±7 pp for FX. Do not re-tune a ladder on 20 trades and call it evidence. Aim for 100 or more per class before treating a level as settled, and recompute as the file grows.
One regime is not the market. Three weeks of data describes three weeks. A trend that ran through your sample inflates every reach rate; a chop that dominated it deflates them. Re-run the table monthly and watch whether the levels move. If they move a lot, the ladder should be adaptive rather than fixed, which is a different article.
Scaled-out positions: judge results on R_realized, not R_at_close. On a staged exit R_at_close is only the final leg and understates what the position earned; R_realized weights every closing deal by its volume. Files from earlier versions lack the column, so any result or giveback drawn from them is about the final leg only. That includes the giveback figures in this article's sample. R_peak and R_trough are valid in both layouts, because they were sampled live.
The file only contains positions your EA opened. If an entry filter is rejecting trades, you never see what they would have done. MFE tells you about the exits of the trades you took. It is silent on the trades you did not.
From table to targets
A reach-rate table does not set your levels for you. It narrows the argument to one you can have with evidence.
The rule I use is simple enough to state in a line: put the first target near the class median, the second between the median and the p90, and the take profit near the p90. The reasoning is that a first scale-out exists to bank something on a typical winner, so it must sit where a typical winner actually goes; a take profit exists to catch the unusually good one, so it belongs where the top tenth land, not beyond them.
Apply that to the four classes above and the numbers fall out.
Class median peak p90 peak ladder that follows ladder it replaced FX 0.51R 1.44R 0.50/1.00/1.45 1.5/2.5/3.0 Crypto 1.54R 2.61R 1.55/2.10/2.60 1.5/2.5/3.0 Metals 1.02R 3.02R 1.00/2.00/3.00 1.5/2.5/3.0 Synthetic 0.72R 1.76R 0.70/1.25/1.75 1.5/2.5/3.0
| Class | median peak | p90 peak | ladder that follows | ladder it replaced |
|---|---|---|---|---|
| FX | 0.51R | 1.44R | 0.50/1.00/1.45 | 1.5/2.5/3.0 |
| Crypto | 1.54R | 2.61R | 1.55/2.10/2.60 | 1.5/2.5/3.0 |
| Metals | 1.02R | 3.02R | 1.00/2.00/3.00 | 1.5/2.5/3.0 |
| Synthetic | 0.72R | 1.76R | 0.70/1.25/1.75 | 1.5/2.5/3.0 |
These ladder levels are a calculation example, not a recommendation. They are derived from the same three weeks of data used to diagnose the problem, so they are in-sample by construction. Before changing live parameters, validate on the following month out of sample, or run a walk-forward across several periods and confirm the levels are stable. If they move month to month, a fixed ladder is the wrong tool and the ladder should be adaptive instead.
Only the metals take profit survives. Its 3.0R target sits almost exactly on the class p90 of 3.02R, which is why metals is the one class where the flat ladder made sense. Its lower rungs still come down — T1 from 1.5R to 1.00R — because metals has the widest spread between median and p90 of any class here: it rarely peaks high, but when it does it runs a long way. That is what a single global setting does. It fits one feature of one class and quietly misfits everything else.
FX is the uncomfortable one. Its targets come down by more than half, which makes the staged exit function, but a class whose median winner peaks at 0.51R is a class with very little room between the spread and the target. Lowering the ladder is a patch. The question the table actually raises is whether that class earns its place in the basket at all, and no amount of target tuning answers that one.
Two mechanical cautions when you implement this. Your scale-out percentages are a separate decision from your levels, and the table says nothing about them. Moving T1 from 1.5R down to 0.50R without revisiting the percentage means you are now banking the same share of the position for a third of the move. And check that the levels still clear your costs. A target at 0.50R on a symbol whose spread is 20% of one ATR is a target that spends a meaningful slice of the move on getting in and out. The reach-rate table is computed from excursions that already net the spread, because the recorder measures at bid for a buy, but your minimum sensible target is still a cost question, not an excursion question.
Conclusion
The recorder is a single include file and costs one function call per management cycle, plus one forwarded event. The reader is a script that runs on demand. What they buy between them is the end of an entire category of guesswork: you stop choosing a take profit because 1:3 sounds disciplined, and start choosing it because you know what share of your trades actually get there.
In the example above the answer was that the 3R take profit was never reached by a single crypto, FX or synthetic position — only metals got there, 5 times in 37 — and the first scale-out had been almost inert on FX, a third of the book and its largest class, for the life of the system. Nothing in the account statement said so, and the tester's pooled MFE histogram did not separate the four classes enough to say so either. The per-position excursion log said so immediately.
Run it for a month before you change anything. Then let the table, rather than the convention, pick your numbers.
File Description MFETracker.mqh The recorder. Include it, call MFEFlushClosed() from your timer and forward OnTradeTransaction. Goes in MQL5/Include/MFERecorder/.
MFEReport.mq5 The reader. Run it as a script to print the reach-rate table, the shape table and the MAE audit. Goes in MQL5/Scripts/MFERecorder/. MFE.csv Output, written by the recorder to MQL5/Files/MFERecorder/. Not attached — it is produced by your own terminal. MQL5.zip Archive with all files that can be unpacked into the terminal installation directory, and all files will be located in the required places.
| File | Description |
|---|---|
| MFETracker.mqh | The recorder. Include it, call MFEFlushClosed() from your timer and forward OnTradeTransaction. Goes in MQL5/Include/MFERecorder/. |
| MFEReport.mq5 | The reader. Run it as a script to print the reach-rate table, the shape table and the MAE audit. Goes in MQL5/Scripts/MFERecorder/. |
| MFE.csv | Output, written by the recorder to MQL5/Files/MFERecorder/. Not attached — it is produced by your own terminal. |
| MQL5.zip | Archive with all files that can be unpacked into the terminal installation directory, and all files will be located in the required places. |
Testing environment. The script and the recorder were tested on MetaTrader 5 build 6230 (25 September 2026). Both a live retail terminal and the standard MetaQuotes terminal were used during testing. Testing was conducted on a hedging account. Netting and exchange accounts are not supported: MFEInit() checks the account's margin mode and disables the recorder, with a message in the log, on anything other than a hedging account.
References
1. J. Sweeney, Maximum Adverse Excursion: Analyzing Price Fluctuations for Trading Management, John Wiley & Sons, 1997. ISBN 978-0-471-14152-5.
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.
Good one, the per class table is the part the built-in report cant give. Question about R frozen at entry. Lot of EAs send a market order without stop and add the SL a second later with a modify, some brokers even require that. At the moment of entry the risk is unknown. Do you take the first SL that appears or skip those positions? And positions that never get a stop have no R at all so I guess they drop out of the table?