Adaptive Bar Replay Tool in MQL5: Using MFE and MAE Percentile Analysis
Introduction
Bar replay tools provide a controlled environment for studying historical price action, testing trading ideas, and evaluating decision-making without the pressure of live market execution. By reconstructing historical price movement one bar at a time, traders can simulate entries and observe how hypothetical positions would have developed in past market conditions. However, a replay system becomes more useful when it goes beyond reproducing historical price movement and manual Stop Loss (SL) and Take Profit (TP) levels. By incorporating the Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) of historical trades, a replay tool can instead derive adaptive risk and reward levels from observed market behavior.
This article presents an Adaptive Bar Replay Tool in MQL5 that uses Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) analysis to make replay-based simulation more data-driven. Instead of treating SL and TP distances as arbitrary, the tool analyzes a maximum of 20 historical trade samples from the account's trading history up to the selected replay starting point, applying percentile analysis to estimate representative price distances. These statistical levels are then used to provide adaptive parameters for simulated trades during the replay process. The replay environment is also designed to handle multiple imaginary trade positions gracefully. Each simulated position is tracked independently, allowing the user to open and manage multiple Buy and Sell positions simultaneously during a replay session without interfering with one another.
The implementation therefore focuses on four major components:
- Historical trade analysis
- MFE and MAE percentile-based analysis
- Management of multiple imaginary trade positions
- Tick-based imaginary position management
By combining these components, the replay tool evolves from a simple historical playback mechanism into an experimental environment for studying how statistical properties of previous trades can influence trade management during replay.
Project Overview
The Adaptive Bar Replay Tool extends the conventional replay concept by using historical trade Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) data to derive adaptive trade-management levels through percentile analysis. During initialization, the tool retrieves historical trades, calculates their MFE and MAE values, and applies the selected percentile to determine adaptive Stop Loss (SL) and Take Profit (TP) distances. The user can choose between two automatic trade-management modes: percentile-derived SL and TP, where both levels are automatically calculated and cannot be adjusted, or percentile-derived SL only, where the SL is automatically determined while the TP remains manually adjustable. Initially, the program places the TP at a distance of SYMBOL_TRADE_STOPS_LEVEL * 10 * _Point from the entry price. However, when SYMBOL_TRADE_STOPS_LEVEL returns zero, it uses a fallback distance of 200 * _Point to establish the initial TP level.
The indicator also inherits the single- and dual-anchor replay modes and playback speed controls from the Trade Replay Tool, including Ctrl+'+' and Ctrl+'-' hotkeys for adjusting playback speed. It further supports imaginary Buy and Sell positions, allowing multiple replay positions to be managed independently as the simulation progresses. The result is a replay environment that combines historical trade statistics with interactive bar-by-bar simulation. It evaluates decisions using risk and reward levels derived from observed market behavior, rather than manual distances.
Percentile
A percentile is a statistical measure used to determine the value below which a given percentage of observations fall. Unlike the average, which describes the central tendency of a dataset, a percentile identifies a specific position within an ordered distribution. In this implementation, percentile analysis is applied to the historical Maximum Adverse Excursion (MAE) and Maximum Favorable Excursion (MFE) values collected from previous trades. The MAE percentile is used to determine the adaptive Stop Loss (SL) distance, while the MFE percentile is used to determine the adaptive Take Profit (TP) distance.
After sorting the observations in ascending order, the percentile position is calculated using:

where:
- (n) is the number of observations,
- (p) is the requested percentile,
- (h) is the calculated position within the sorted dataset.
If (h) is an integer, the observation at that position is used directly. Otherwise, the percentile value is obtained by linear interpolation between the two surrounding observations.

The computePercentile() function implements the core percentile calculation used to derive adaptive Stop Loss (SL) and Take Profit (TP) levels. It accepts the isMAE parameter to determine which trade excursion metric to analyze: when true, it calculates the selected percentile from the Maximum Adverse Excursion (MAE) values for SL estimation; when false, it uses the Maximum Favorable Excursion (MFE) values for TP estimation. The function sorts the selected values and applies linear interpolation to return the percentile value, providing a data-driven basis for determining adaptive risk and reward levels.
//+------------------------------------------------------------------+ //| PERCENTILE FUNCTION | //+------------------------------------------------------------------+ double computePercentile(const bool isMAE, st_AdaptiveReplay &arr[]) { //--- int size = ArraySize(arr); if(size <= 0) return EMPTY_VALUE; double sorted[]; ArrayResize(sorted, size); for(int w = 0; w < ArraySize(arr); w++) { sorted[w] = (isMAE) ? arr[w].mae : arr[w].mfe; } ArraySort(sorted); //--- CONVERT PERCENTILE TO FRACTION double p = percentile / 100.0; //--- CALCULATE PERCENTLE POSITION double h = (size - 1) * p; //--- CALCULATE INDEXES int lowerIndex = (int)MathFloor(h); int upperIndex = (int)MathCeil(h); //--- CALCULATE INTERPOLATE FRACTION double fraction = h - lowerIndex; double lowerValue = sorted[lowerIndex]; double upperValue = sorted[upperIndex]; //--- LINEAR INTERPOLATION return lowerValue + fraction * (upperValue - lowerValue); }
MQL5 Implementation
Having established the underlying percentile analysis and its role in determining adaptive Stop Loss (SL) and Take Profit (TP) levels, we can now implement the Adaptive Bar Replay Tool using native MQL5 functionality. This section covers the core components, from retrieving historical trade data and calculating MFE and MAE statistics to integrating percentile-based risk and reward levels into the replay environment. We will also examine how the tool manages multiple imaginary trade positions independently while preserving interactive trade management throughout the replay process.
Compiler Directives
We begin by defining the indicator's properties and the symbolic identifiers used throughout the implementation. The tool is configured as a chart-window indicator with five buffers to support DRAW_COLOR_CANDLES, allowing historical price bars to be rendered progressively during replay. We also define macros for the replay controls, timeline anchors, speed adjustment interface, and imaginary trade components, including entry, Stop Loss, and Take Profit levels. Finally, the DealInfo.mqh library is included to facilitate access to historical deal properties required for analyzing previous trades and calculating their MFE and MAE values.
//+------------------------------------------------------------------+ //| Adaptive Bar Replay Tool.mq5 | //| © 2026, ChukwuBuikem | //| https://www.mql5.com/en/users/bikeen | //+------------------------------------------------------------------+ #property copyright "© 2026, ChukwuBuikem" #property link "https://www.mql5.com/en/users/bikeen" #property indicator_chart_window #property indicator_plots 1 #property indicator_buffers 5 #property indicator_type1 DRAW_COLOR_CANDLES #property indicator_color1 clrGreen,clrRed,clrNONE; #property indicator_width1 2 #property indicator_label1 "REPLAY: OPEN;REPLAY: HIGH;REPLAY: LOW;REPLAY: CLOSE" #define _PROG_NAME "Adaptive Bar Replay Tool" #define _MENU_BUTTON _PROG_NAME + "MENU_BUTTON" #define _REPLAY_ANCHOR1 _PROG_NAME + "REPLAY_VLINE#1" #define _REPLAY_ANCHOR2 _PROG_NAME + "REPLAY_VLINE#2" #define _REPLAY_PRICE _PROG_NAME + "REPLAY_PRICE" #define _REPLAY_PLAY_BUTTON _PROG_NAME + "REPLAY_PLAY_BUTTON" #define _REPLAY_UPPER_DASHBOARD _PROG_NAME + "REPLAY_UPPER_DASHBOARD" #define _REPLAY_LOWER_DASHBOARD _PROG_NAME + "REPLAY_LOWER_DASHBOARD" #define _REPLAY_SPEED_UP_BUTTON _PROG_NAME + "REPLAY_SPEED_UP_BUTTON" #define _REPLAY_SPEED_LABEL _PROG_NAME + "REPLAY_SPEED_LABEL" #define _REPLAY_SPEED_DOWN_BUTTON _PROG_NAME + "REPLAY_SPEED_DOWN_BUTTON" //--- PLAY AND PAUSE UNICODE SYMBOLS #define _PLAY_SYMBOL ShortToString(0X25B6) #define _PAUSE_SYMBOL ShortToString(0X23F8) //--- REPLAY TRADE MACROS #define _REPLAY_BUY_BUTTON _PROG_NAME + "REPLAY_BUY_BUTTON" #define _REPLAY_SELL_BUTTON _PROG_NAME + "REPLAY_SELL_BUTTON" #define _REPLAY_POSITION_ENTRY _PROG_NAME + "REPLAY_POSITION_ENTRY" #define _REPLAY_POSITION_TP _PROG_NAME + "REPLAY_POSITION_TP" #define _REPLAY_POSITION_SL _PROG_NAME + "REPLAY_POSITION_SL" #include <Trade\DealInfo.mqh>
Custom Enumeration
To provide flexibility in configuring the adaptive risk management system, we define a custom enumeration, ENUM_AUTOMATIC_PROPERTY, which determines how Stop Loss (SL) and Take Profit (TP) levels are managed. The AUTOMATIC_SL option enables percentile-based automatic Stop Loss calculation while allowing the Take Profit level to remain adjustable. Conversely, AUTOMATIC_TP_SL enables automatic calculation of both levels using the selected MAE and MFE percentiles, respectively.
//--- CUSTOM ENUMERATION enum ENUM_AUTOMATIC_PROPERTY { AUTOMATIC_SL, //Automatic Stop loss AUTOMATIC_TP_SL//Automatic TP and SL };
Data Structures
The st_AdaptiveReplay structure stores each imaginary trade's key properties: position ID, direction, entry/exit times, entry price, SL, TP, and the calculated MFE/MAE values. The st_ChartInfo structure preserves the chart's original color settings and provides methods to customize the chart for replay and restore its previous appearance when replay ends.
//--- DATA STRUCTURES struct st_AdaptiveReplay { long positionID; ENUM_DEAL_TYPE dealType; ulong entryMsc; ulong exitMsc; double entryPrice; double sl; double tp; double vol; double mae; double mfe; //--- CONSTRUCTOR st_AdaptiveReplay() { positionID = LONG_MIN; dealType = DEAL_TYPE_CREDIT; entryMsc = 0; exitMsc = 0; entryPrice = EMPTY_VALUE; sl = EMPTY_VALUE; tp = EMPTY_VALUE; vol = EMPTY_VALUE; mae = 0; mfe = 0; } }; //--- struct st_ChartInfo { private: color barUpClr; color barDownClr; color bullClr; color bearClr; color lineClr; color askClr; color bidClr; public: //--- CONSTRUCTOR st_ChartInfo() { barUpClr = (color)ChartGetInteger(0, CHART_COLOR_CHART_UP); barDownClr = (color)ChartGetInteger(0, CHART_COLOR_CHART_DOWN); bullClr = (color)ChartGetInteger(0, CHART_COLOR_CANDLE_BULL); bearClr = (color)ChartGetInteger(0, CHART_COLOR_CANDLE_BEAR); lineClr = (color)ChartGetInteger(0, CHART_COLOR_CHART_LINE); askClr = (color)ChartGetInteger(0, CHART_COLOR_ASK); bidClr = (color)ChartGetInteger(0, CHART_COLOR_BID); } //--- FUNCTIONS void customize(); void restore(); color getPriceColor(); } chartState;
Input Parameter
Next, we define the configurable input parameters that allow users to customize the tool's trade management behavior. The inpAutoMode parameter selects whether only the Stop Loss or both Stop Loss and Take Profit are calculated automatically. The inpPercentilePercent parameter specifies the percentile used for the MFE and MAE analysis. It is an integer that must not exceed 100, with a default value of 75.
//--- INPUT PARAMETERS input ENUM_AUTOMATIC_PROPERTY inpAutoMode = AUTOMATIC_SL;//Trade management mode input int inpPercentilePercent = 75; //Percentile percent
Global Variables
With the input parameters defined, we declare the global variables required to coordinate replay execution and trade analysis. These include historical price data and indicator buffers, replay position records, anchor timestamps, and playback state flags. The playback speed arrays define the available replay intervals and their corresponding labels, while percentile, slPercentile, and tpPercentile store the selected percentile and the resulting adaptive Stop Loss and Take Profit values. The remaining variables track calculation progress, position identification, and interface information.
//--- GLOBAL VARIABLES MqlRates rates[]; double openBuffer[], highBuffer[], lowBuffer[], closeBuffer[], colorBuffer[]; double lastPrice = EMPTY_VALUE; st_AdaptiveReplay replayPositions[]; st_AdaptiveReplay trade, data[]; int lastCalculated = 0, endCalculate = 0, bars = 0; datetime anchor1Time, anchor2Time; bool replayMode = false; bool isPlay = false; bool isPercentileReady = false; //--- PLAYBACK SPEED VARIBLES int speedIntervals[7] = {100, 200, 500, 800, 1000, 1500, 2000}; string speedTexts[7] = {"0.1s", "0.2s", "0.5s", "0.8s", "1.0s", "1.5s", "2.0s"}; int speedIndex = 2, systemID = 0, percentile = 0; double slPercentile = 0, tpPercentile = 0; string tooltip = "";
Helper Functions
We now define a set of helper functions that handle the tool's core operations. These functions manage historical trade retrieval, MFE and MAE calculations, percentile analysis, imaginary trade management, and chart object interactions. By encapsulating these responsibilities into dedicated functions, we maintain a modular and organized implementation that is easier to understand, maintain, and extend.
Replay Trade Management
To manage imaginary trade positions effectively, we define a set of helper functions responsible for position identification, visualization, closure, and monitoring. These functions ensure that each position is tracked independently, its entry, Stop Loss (SL), and Take Profit (TP) levels are properly represented on the chart, and its status is continuously evaluated as new price bars emerge during replay.
//+------------------------------------------------------------------+ //| GENERATE SYSTEM POSITION ID | //+------------------------------------------------------------------+ int generatePositionID() { //--- return ++systemID; } //+------------------------------------------------------------------+ //| EXTRACT POSITION ID | //+------------------------------------------------------------------+ int extractPositionID(const string objname) { //--- int start = StringLen(_REPLAY_POSITION_TP); string idString = StringSubstr(objname, start); return (int)StringToInteger(idString); } //+------------------------------------------------------------------+ //| IMAGINARY REPLAY PAPER TRADE | //+------------------------------------------------------------------+ void showPosition(st_AdaptiveReplay &pos, const string entryToolTip) { //--- createHLine(_REPLAY_POSITION_ENTRY + IntegerToString(pos.positionID), pos.entryPrice, clrBlue, false, entryToolTip, STYLE_DOT); createHLine(_REPLAY_POSITION_SL + IntegerToString(pos.positionID), pos.sl, clrRed, false, "SL", STYLE_DASHDOT); createHLine(_REPLAY_POSITION_TP + IntegerToString(pos.positionID), pos.tp, clrLimeGreen, (inpAutoMode == AUTOMATIC_SL) ? true : false, "TP", STYLE_DASHDOT); ChartRedraw(); } //+------------------------------------------------------------------+ //| CLOSE POSITION | //+------------------------------------------------------------------+ void closePosition(const int positionID) { //--- ObjectDelete(0, _REPLAY_POSITION_ENTRY + IntegerToString(positionID)); ObjectDelete(0, _REPLAY_POSITION_SL + IntegerToString(positionID)); ObjectDelete(0, _REPLAY_POSITION_TP + IntegerToString(positionID)); ChartRedraw(); } //+------------------------------------------------------------------+ //| GET POSITION INDEX | //+------------------------------------------------------------------+ int getPositionIndex(const int positionID, st_AdaptiveReplay &searchArr[]) { //--- for(int w = 0; w < ArraySize(searchArr); w++) { if(searchArr[w].positionID == positionID) return w; } return -1; } //+------------------------------------------------------------------+ //| POSITION CLOSURE MANAGEMENT | //+------------------------------------------------------------------+ void checkOpenPositions(const datetime replayTime) { //--- if(ArraySize(replayPositions) <= 0) return; bool tpHit = false; bool slHit = false; ResetLastError(); MqlTick ticks[]; ArraySetAsSeries(ticks, true); ulong fromMsc = (ulong)replayTime * 1000; ulong endMsc = (ulong)((replayTime + PeriodSeconds()) * 1000) - 1; if(CopyTicksRange(_Symbol, ticks, COPY_TICKS_ALL, fromMsc, endMsc) <= 0) { Print("Failed to retrieve ticks for replay bar. Error: ", GetLastError()); return; } for(int w = ArraySize(replayPositions) - 1; w >= 0; w--) { tpHit = false; slHit = false; //--- LOOP THROUGH TICK DATA for(int t = ArraySize(ticks) - 1; t >= 0; t--) { if(replayPositions[w].dealType == DEAL_TYPE_BUY) { //--- CHECK AGAINST BID PRICE tpHit = (ticks[t].bid >= replayPositions[w].tp); slHit = (ticks[t].bid <= replayPositions[w].sl); if(tpHit || slHit) break; } if(replayPositions[w].dealType == DEAL_TYPE_SELL) { //--- CHECK AGAINST ASK PRICE tpHit = (ticks[t].ask <= replayPositions[w].tp); slHit = (ticks[t].ask >= replayPositions[w].sl); if(tpHit || slHit) break; } } if(tpHit || slHit) { //--- CLOSE POSITION AND REMOVE ITS DATA FROM THE ARRAY closePosition((int)replayPositions[w].positionID); ArrayRemove(replayPositions, w, 1); PlaySound("ok.wav"); } } }
Explanation:
- generatePositionID(): This function generates a unique, incrementing identifier for each imaginary position, allowing its associated chart objects to be distinguished from others.
- extractPositionID(): Extracts the position identifier from a chart object's name by removing the Take Profit object-name prefix and converting the remaining string to an integer.
- showPosition(): Displays an imaginary position on the chart using horizontal lines for its entry price, SL, and TP. The lines use distinct colors and styles, with TP adjustability determined by the selected trade management mode.
- closePosition(): Removes the entry, SL, and TP lines associated with a specified position ID and refreshes the chart.
- getPositionIndex(): Searches an array of replay positions for a specified position ID and returns its index, or -1 if no matching position is found.
- checkOpenPositions(): Retrieves tick data for the current replay bar and evaluates each open position against the tick-level Bid or Ask prices to determine whether its TP or SL has been reached. When either level is triggered, the position is closed, its data is removed from the active positions array, and a sound notification is played.
Historical Trade Analysis
The getDeals() function retrieves and organizes historical trade data for subsequent MFE and MAE analysis, limiting the initial collection to a maximum of 20 entry deals for the current symbol. It begins by filtering for DEAL_ENTRY_IN records to obtain each position's identifier, entry price, and the exact entry time in milliseconds. It then searches the deal history for corresponding DEAL_ENTRY_OUT records using the position ID to determine each position's exit time. Finally, entries without a valid exit time are removed, ensuring that only completed positions are retained for further analysis.
//+------------------------------------------------------------------+ //| HISTORICAL TRADE ANALYSIS | //+------------------------------------------------------------------+ void getDeals(const datetime endTime, st_AdaptiveReplay &arr[]) { //--- CDealInfo deal1, deal2; st_AdaptiveReplay temp[]; if(HistorySelect(0, endTime)) { int count = 0; /* LOOP THROUGH HISTORICAL DEALS AND GET ENTRY DEALS WITH ONE OPENING */ for(int a = HistoryDealsTotal() - 1; a >= 0; a--) { count = 0; if(deal1.SelectByIndex(a)) { if(deal1.DealType() != DEAL_TYPE_BUY && deal1.DealType() != DEAL_TYPE_SELL) continue; if(deal1.Entry() == DEAL_ENTRY_IN && deal1.Symbol() == _Symbol) { //--- COUNT NUMBER OF OPENING DEALS for(int b = HistoryDealsTotal() - 1; b >= 0; b--) { if(deal2.SelectByIndex(b)) { if(deal2.DealType() != DEAL_TYPE_BUY && deal2.DealType() != DEAL_TYPE_SELL) continue; if(deal2.Entry() == DEAL_ENTRY_IN && deal2.Symbol() == _Symbol) if(deal1.PositionId() == deal2.PositionId()) count++; } } //--- REJECT POSITIONS WITH MULTIPLE OPENING DEALS if(count != 1) continue; ArrayResize(temp, ArraySize(temp) + 1); temp[ArraySize(temp) - 1].positionID = deal1.PositionId(); temp[ArraySize(temp) - 1].dealType = (ENUM_DEAL_TYPE)deal1.DealType(); temp[ArraySize(temp) - 1].entryPrice = deal1.Price(); //--- GET AS MILLISECONDS temp[ArraySize(temp) - 1].entryMsc = deal1.TimeMsc(); temp[ArraySize(temp) - 1].vol = deal1.Volume(); } } } //--- IDENTIFY EXACTLY ONE CORRESPONDING CLOSING DEAL USING POSITION ID for(int b = 0; b < ArraySize(temp); b++) { for(int c = HistoryDealsTotal() - 1; c >= 0 ; c--) { count = 0; if(deal1.SelectByIndex(c)) { if(deal1.DealType() != DEAL_TYPE_BUY && deal1.DealType() != DEAL_TYPE_SELL) continue; if(deal1.Entry() == DEAL_ENTRY_OUT && deal1.Symbol() == _Symbol) { if(temp[b].positionID != deal1.PositionId()) continue; if(temp[b].vol != deal1.Volume()) continue; //--- COUNT ALL CLOSING DEALS ASSOCIATED WITH THE SAME POSITION ID for(int d = HistoryDealsTotal() - 1; d >= 0; d--) { if(deal2.SelectByIndex(d)) { if(deal2.DealType() != DEAL_TYPE_BUY && deal2.DealType() != DEAL_TYPE_SELL) continue; if(deal2.Entry() == DEAL_ENTRY_OUT && deal2.Symbol() == _Symbol) if(deal1.PositionId() == deal2.PositionId()) count++; } } //--- REJECT POSITIONS WITH MULTIPLE CLOSING DEALS if(count != 1) continue; //--- GET AS MILLISECONDS temp[b].exitMsc = deal1.TimeMsc(); } } } } //--- REMOVE POSITIONS WITHOUT CLOSING TIMESTAMPS for(int w = ArraySize(temp) - 1; w >= 0; w--) { if(temp[w].exitMsc <= 0) { ArrayRemove(temp, w, 1); } } //--- APPLY THE 20-POSITION LIMIT if(ArraySize(temp) > 20) ArrayRemove(temp, 20, ArraySize(temp) - 20); } ArrayResize(arr, ArraySize(temp)); ArrayCopy(arr, temp); }
Note: This implementation is limited to positions with exactly one opening deal (DEAL_ENTRY_IN) and one full closing deal (DEAL_ENTRY_OUT). Positions involving multiple partial closing deals, or closing deals with volumes that do not match the original opening volume are not supported.
MFE and MAE Computation
To quantify the favorable and adverse price movements of each historical trade, the computeExcursions() function analyzes the tick data within its entry-to-exit interval. It identifies the highest and lowest prices recorded during each trade's lifespan and calculates the MFE and MAE based on the trade direction and entry price. These values are then stored for subsequent percentile analysis.
//+------------------------------------------------------------------+ //| Compute MFE and MAE | //+------------------------------------------------------------------+ void computeExcursions(st_AdaptiveReplay &arr[]) { //--- if(ArraySize(arr) <= 0) return; //--- GET EARLIEST ENTRYMSC AND LATEST TOMSC TIME VALUES ulong fromMsc = LONG_MAX; ulong toMsc = 0; for(int c = 0; c < ArraySize(arr); c++) { toMsc = MathMax(toMsc, arr[c].exitMsc); fromMsc = MathMin(fromMsc, arr[c].entryMsc); } ulong currMillSec = 0; MqlTick ticks[]; ArraySetAsSeries(ticks, true); //--- COPY TICK DATA FROM FIRST ENTRY TIME TO LAST EXIT TIME if(CopyTicksRange(_Symbol, ticks, COPY_TICKS_ALL, fromMsc, toMsc) <= 0) { Print("Failed to retrieve ticks for excursion. Error: ", GetLastError()); return; } //--- for(int w = ArraySize(arr) - 1; w >= 0; w--) { double highestPrice = -DBL_MAX; double lowestPrice = DBL_MAX; double favorable = 0; double adverse = 0; //--- LOOP THROUGH TICK DATA for(int m = ArraySize(ticks) - 1; m >= 0; m--) { currMillSec = (ulong)ticks[m].time_msc; if(currMillSec >= arr[w].entryMsc && currMillSec <= arr[w].exitMsc) { //--- OBTAIN THE HIGHEST BID-ASK PRICE LEVELS WITHIN EACH TRADE LIFESPAN if(arr[w].dealType == DEAL_TYPE_BUY) { if(ticks[m].bid > highestPrice) highestPrice = ticks[m].bid; if(ticks[m].bid < lowestPrice) lowestPrice = ticks[m].bid; } //--- if(arr[w].dealType == DEAL_TYPE_SELL) { if(ticks[m].ask > highestPrice) highestPrice = ticks[m].ask; if(ticks[m].ask < lowestPrice) lowestPrice = ticks[m].ask; } } if(currMillSec > arr[w].exitMsc) break; } if(highestPrice > 0 && lowestPrice > 0) { if(arr[w].dealType == DEAL_TYPE_BUY) { favorable = MathMax(0, highestPrice - arr[w].entryPrice); adverse = MathMax(0, arr[w].entryPrice - lowestPrice); } //--- if(arr[w].dealType == DEAL_TYPE_SELL) { favorable = MathMax(0, arr[w].entryPrice - lowestPrice); adverse = MathMax(0, highestPrice - arr[w].entryPrice); } arr[w].mfe = favorable; arr[w].mae = adverse; } } }
Chart Configuration
Next, we implement the member functions declared earlier in the custom data structure. The customize() function hides the default bullish and bearish candle and bar colors during replay, while restore() reinstates their original colors when replay ends. Finally, getPriceColor() returns the stored Bid price color for rendering the replay price line.//+------------------------------------------------------------------+ //| CUSTOMIZE CHART | //+------------------------------------------------------------------+ void st_ChartInfo::customize(void) { //--- ChartSetInteger(0, CHART_COLOR_CANDLE_BULL, clrNONE); ChartSetInteger(0, CHART_COLOR_CANDLE_BEAR, clrNONE); ChartSetInteger(0, CHART_COLOR_CHART_UP, clrNONE); ChartSetInteger(0, CHART_COLOR_CHART_DOWN, clrNONE); ChartRedraw(); } //+------------------------------------------------------------------+ //| RESTORE CHART SETTINGS | //+------------------------------------------------------------------+ void st_ChartInfo::restore(void) { //--- ChartSetInteger(0, CHART_COLOR_CANDLE_BULL, bullClr); ChartSetInteger(0, CHART_COLOR_CANDLE_BEAR, bearClr); ChartSetInteger(0, CHART_COLOR_CHART_UP, barUpClr); ChartSetInteger(0, CHART_COLOR_CHART_DOWN, barDownClr); ChartRedraw(); } //+------------------------------------------------------------------+ //| OBTAIN PRICE COLOR | //+------------------------------------------------------------------+ color st_ChartInfo::getPriceColor(void) { //--- return bidClr; }
Viewport Detection and Time Normalization
To ensure the anchor line is initialized at a valid chart position and its movement remains aligned with the current chart timeframe, we implement two functions to handle viewport detection and time normalization.//+------------------------------------------------------------------+ //| VIEWPORT DETECTION | //+------------------------------------------------------------------+ datetime getViewportMiddleTime(void) { //--- datetime start = 0, end = 0; int first = (int) ChartGetInteger(0, CHART_FIRST_VISIBLE_BAR); int visibleBars = (int) ChartGetInteger(0, CHART_VISIBLE_BARS); int last = first - visibleBars + 2; if(last < 0) last = 0; start = iTime(_Symbol, PERIOD_CURRENT, last); end = iTime(_Symbol, PERIOD_CURRENT, first); datetime rawMiddleTime = (start + end) / 2; int nearestBar = iBarShift(_Symbol, PERIOD_CURRENT, rawMiddleTime, false); if(nearestBar < 0) return 0; return iTime(_Symbol, PERIOD_CURRENT, nearestBar); } //+------------------------------------------------------------------+ //| TIME NORMALIZATION | //+------------------------------------------------------------------+ datetime normalizeToChartTime(const datetime time) { //--- int shift = iBarShift(_Symbol, PERIOD_CURRENT, time); if(shift < 0) shift = 0; return iTime(_Symbol, PERIOD_CURRENT, shift); }
Chart Visualization Utilities
To manage chart objects and the user interface consistently, we define a set of utility functions responsible for creating and configuring the visual components of the replay tool. These functions encapsulate the object-creation process, allowing buttons, labels, horizontal lines, anchor lines, and dashboards to be initialized through reusable interfaces rather than repeatedly implementing their configuration throughout the program.//+------------------------------------------------------------------+ //| BUTTON CREATION | //+------------------------------------------------------------------+ void createButton(const string objName, const int xDistance, const int yDistance, const int xSize, const int ySize, const ENUM_BASE_CORNER corner, const color clr, const color bgClr, const color bdClr, const int fontsize, const string objTooltip, const string display, const string font = "Arial") { //--- if(ObjectCreate(0, objName, OBJ_BUTTON, 0, 0, 0)) { ObjectSetInteger(0, objName, OBJPROP_CORNER, corner); ObjectSetInteger(0, objName, OBJPROP_XDISTANCE, xDistance); ObjectSetInteger(0, objName, OBJPROP_YDISTANCE, yDistance); ObjectSetInteger(0, objName, OBJPROP_XSIZE, xSize); ObjectSetInteger(0, objName, OBJPROP_YSIZE, ySize); ObjectSetInteger(0, objName, OBJPROP_COLOR, clr); ObjectSetInteger(0, objName, OBJPROP_BGCOLOR, bgClr); ObjectSetInteger(0, objName, OBJPROP_BORDER_COLOR, bdClr); ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, false); ObjectSetInteger(0, objName, OBJPROP_STATE, false); ObjectSetInteger(0, objName, OBJPROP_FONTSIZE, fontsize); ObjectSetString(0, objName, OBJPROP_TOOLTIP, objTooltip); ObjectSetString(0, objName, OBJPROP_TEXT, display); ObjectSetString(0, objName, OBJPROP_FONT, font); ChartRedraw(); } } //+------------------------------------------------------------------+ //| LABEL CREATION | //+------------------------------------------------------------------+ void createLabel(const string objName, const int xDistance, const int yDistance, const int xSize, const int ySize, const ENUM_BASE_CORNER corner, const color clr, const string text, const int font) { //--- if(ObjectCreate(0, objName, OBJ_LABEL, 0, 0, 0)) { ObjectSetInteger(0, objName, OBJPROP_XDISTANCE, xDistance); ObjectSetInteger(0, objName, OBJPROP_YDISTANCE, yDistance); ObjectSetInteger(0, objName, OBJPROP_XSIZE, xSize); ObjectSetInteger(0, objName, OBJPROP_YSIZE, ySize); ObjectSetInteger(0, objName, OBJPROP_COLOR, clr); ObjectSetInteger(0, objName, OBJPROP_FONTSIZE, font); ObjectSetInteger(0, objName, OBJPROP_CORNER, corner); ObjectSetString(0, objName, OBJPROP_FONT, "Arial Black"); ObjectSetString(0, objName, OBJPROP_TEXT, text); ObjectSetString(0, objName, OBJPROP_TOOLTIP, "Replay Speed"); ChartRedraw(); } } //+------------------------------------------------------------------+ //| HORIZONTAL LINE CREATION | //+------------------------------------------------------------------+ void createHLine(const string objName, const double price1, const color clr, const bool selectable, const string toolTip = "\n", const ENUM_LINE_STYLE style = STYLE_SOLID) { //--- if(ObjectCreate(0, objName, OBJ_HLINE, 0, 0, price1)) { ObjectSetInteger(0, objName, OBJPROP_COLOR, clr); ObjectSetInteger(0, objName, OBJPROP_WIDTH, 1); ObjectSetInteger(0, objName, OBJPROP_HIDDEN, true); ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, selectable); ObjectSetInteger(0, objName, OBJPROP_SELECTED, selectable); ObjectSetInteger(0, objName, OBJPROP_STYLE, style); ObjectSetString(0, objName, OBJPROP_TEXT, toolTip); ObjectSetString(0, objName, OBJPROP_TOOLTIP, toolTip); } } //+------------------------------------------------------------------+ //| ANCHOR LINE CREATION | //+------------------------------------------------------------------+ void drawAnchorLine(const string objName, const datetime vTime, const string objTooltip = "\n") { //--- if(ObjectCreate(0, objName, OBJ_VLINE, 0, vTime, 0)) { ObjectSetInteger(0, objName, OBJPROP_COLOR, clrBlue); ObjectSetInteger(0, objName, OBJPROP_WIDTH, 1); ObjectSetInteger(0, objName, OBJPROP_HIDDEN, true); ObjectSetInteger(0, objName, OBJPROP_SELECTABLE, true); ObjectSetInteger(0, objName, OBJPROP_SELECTED, true); ObjectSetInteger(0, objName, OBJPROP_STYLE, STYLE_DASHDOTDOT); ObjectSetString(0, objName, OBJPROP_TEXT, objTooltip); ObjectSetString(0, objName, OBJPROP_TOOLTIP, objTooltip); ChartRedraw(); } } //+------------------------------------------------------------------+ //| BUILD UPPER DASHBOARD | //+------------------------------------------------------------------+ void createUpperDashboard(void) { //--- if(ObjectCreate(0, _REPLAY_UPPER_DASHBOARD, OBJ_RECTANGLE_LABEL, 0, 0, 0)) { ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_XDISTANCE, 10); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_YDISTANCE, 20); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_XSIZE, 130); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_YSIZE, 40); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_BGCOLOR, clrBlack); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_BORDER_TYPE, BORDER_FLAT); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_BORDER_COLOR, clrBlue); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_COLOR, clrBlack); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, _REPLAY_UPPER_DASHBOARD, OBJPROP_WIDTH, 3); createButton(_REPLAY_SPEED_DOWN_BUTTON, 15, 25, 28, 28, CORNER_LEFT_UPPER, clrLimeGreen, clrBlack, clrLimeGreen, 12, "Slower, Ctrl+'-'", ShortToString(0X003C) + ShortToString(0X003C), "Segoe UI"); createLabel(_REPLAY_SPEED_LABEL, 50, 25, 28, 28, CORNER_LEFT_UPPER, clrBlue, speedTexts[speedIndex], 15); createButton(_REPLAY_SPEED_UP_BUTTON, 105, 25, 28, 28, CORNER_LEFT_UPPER, clrLimeGreen, clrBlack, clrLimeGreen, 12, "Faster, Ctrl+'+'", ShortToString(0X003E) + ShortToString(0X003E), "Segoe UI"); ChartRedraw(); } } //+------------------------------------------------------------------+ //| BUILD LOWER DASHBOARD | //+------------------------------------------------------------------+ void createLowerDashboard(void) { //--- if(ObjectCreate(0, _REPLAY_LOWER_DASHBOARD, OBJ_RECTANGLE_LABEL, 0, 0, 0)) { ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_XDISTANCE, 70); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_YDISTANCE, 50); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_XSIZE, 110); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_YSIZE, 40); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_BGCOLOR, clrBlack); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_BORDER_TYPE, BORDER_FLAT); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_CORNER, CORNER_LEFT_LOWER); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_COLOR, clrBlack); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, _REPLAY_LOWER_DASHBOARD, OBJPROP_WIDTH, 3); //--- CREATE PLAYBACK, BUY, AND SELL BUTTONS createButton(_REPLAY_PLAY_BUTTON, 75, 45, 30, 30, CORNER_LEFT_LOWER, clrWhite, clrGray, clrGray, 15, "Playback Control", _PLAY_SYMBOL, "Segoe UI"); createButton(_REPLAY_BUY_BUTTON, 110, 45, 30, 30, CORNER_LEFT_LOWER, clrWhite, clrBlue, clrBlue, 8, "BUY", "BUY", "Bold"); createButton(_REPLAY_SELL_BUTTON, 145, 45, 30, 30, CORNER_LEFT_LOWER, clrWhite, clrRed, clrRed, 8, "SELL", "SELL", "Bold"); ChartRedraw(); } }
Button Toggle System
To provide intuitive control over the replay environment, we implement two toggle functions that manage the activation state of the tool and the playback process independently. The toggleMenuButton() function handles replay initialization and cleanup, while togglePlayButton() switches between playback and pause states, coordinating the button appearance, anchor interaction, and replay execution state.
//+------------------------------------------------------------------+ //| TOGGLE MENU BUTTON | //+------------------------------------------------------------------+ void toggleMenuButton(void) { //--- static bool isMenuOn = false; isMenuOn = !isMenuOn; if(!isMenuOn) { ObjectSetInteger(0, _MENU_BUTTON, OBJPROP_BGCOLOR, clrBlue); ObjectSetString(0, _MENU_BUTTON, OBJPROP_TEXT, "ON"); ObjectSetInteger(0, _MENU_BUTTON, OBJPROP_STATE, false); //--- RESTORE CHART SETTINGS ChartSetInteger(0, CHART_EVENT_OBJECT_DELETE, false); ChartSetInteger(0, CHART_SHOW_ONE_CLICK, true); ChartSetInteger(0, CHART_SHOW_OBJECT_DESCR, false); ChartSetInteger(0, CHART_KEYBOARD_CONTROL, true); ChartSetInteger(0, CHART_SHOW_PRICE_SCALE, true); //--- CLEAR AND RESTORE DEFAULT CANDLE SETTINGS ObjectsDeleteAll(0, _PROG_NAME + "REPLAY_"); clearReplayCandles(); chartState.restore(); replayMode = false; ChartRedraw(); } else { ObjectSetInteger(0, _MENU_BUTTON, OBJPROP_BGCOLOR, clrRed); ObjectSetString(0, _MENU_BUTTON, OBJPROP_TEXT, "OFF"); ObjectSetInteger(0, _MENU_BUTTON, OBJPROP_STATE, false); //--- CUSTOMIZE CHART SETTINGS ChartSetInteger(0, CHART_EVENT_OBJECT_DELETE, true); ChartSetInteger(0, CHART_SHOW_ONE_CLICK, false); ChartSetInteger(0, CHART_SHOW_OBJECT_DESCR, true); ChartSetInteger(0, CHART_KEYBOARD_CONTROL, false); ChartSetInteger(0, CHART_SHOW_PRICE_SCALE, false); //--- ArrayResize(replayPositions, 0); systemID = 0; anchor1Time = getViewportMiddleTime(); anchor2Time = iTime(_Symbol, PERIOD_CURRENT, 0); drawAnchorLine(_REPLAY_ANCHOR1, anchor1Time, "Replay Anchor"); createUpperDashboard(); createLowerDashboard(); chartState.customize(); renderReplayCandles(anchor1Time, anchor2Time); //--- INITIALIZATION getDeals(anchor1Time, data); computeExcursions(data); if(((tpPercentile = computePercentile(false, data)) == EMPTY_VALUE && inpAutoMode == AUTOMATIC_TP_SL) || ((tpPercentile = computePercentile(false, data)) <= 0 && inpAutoMode == AUTOMATIC_TP_SL) || (slPercentile = computePercentile(true, data)) == EMPTY_VALUE || (slPercentile = computePercentile(true, data)) <= 0) { Print("Error: Failed to calculate TP/SL percentile. Trading restricted"); isPercentileReady = false; return; } isPercentileReady = true; tpPercentile = NormalizeDouble(tpPercentile, _Digits); slPercentile = NormalizeDouble(slPercentile, _Digits); //--- SYSTEM SUMMARY Print("+=================================+"); Print("Adaptive Bar Replay Tool - MFE and MAE Percentile Analysis"); Print("Symbol : ", _Symbol, "(" + EnumToString(_Period) + ") || Percentile : " + IntegerToString(percentile) + "%"); Print("Historical trades up to: ", anchor1Time); if(inpAutoMode == AUTOMATIC_TP_SL) Print("TP percentile : ", tpPercentile); Print("SL percentile : ", slPercentile); ChartRedraw(); } } //+------------------------------------------------------------------+ //| TOGGLE PLAYBACK BUTTON | //+------------------------------------------------------------------+ void togglePlayButton(void) { //--- isPlay = !isPlay; if(!isPlay) { ObjectSetString(0, _REPLAY_PLAY_BUTTON, OBJPROP_TEXT, _PLAY_SYMBOL); ObjectSetInteger(0, _REPLAY_PLAY_BUTTON, OBJPROP_STATE, false); ObjectSetInteger(0, _REPLAY_ANCHOR1, OBJPROP_SELECTED, true); ObjectSetInteger(0, _REPLAY_ANCHOR2, OBJPROP_SELECTED, true); replayMode = false; } else { ObjectSetString(0, _REPLAY_PLAY_BUTTON, OBJPROP_TEXT, _PAUSE_SYMBOL); ObjectSetInteger(0, _REPLAY_PLAY_BUTTON, OBJPROP_STATE, false); ObjectSetInteger(0, _REPLAY_ANCHOR1, OBJPROP_SELECTED, false); ObjectSetInteger(0, _REPLAY_ANCHOR2, OBJPROP_SELECTED, false); replayMode = true; //--- PREVENT EXPOSING FUTURE PRICE INFORMATION if(ObjectFind(0, _REPLAY_ANCHOR2) >= 0) { //--- REVERSE THE INDEX DIRECTION int index = iBarShift(_Symbol, PERIOD_CURRENT, anchor2Time); bars = Bars(_Symbol, PERIOD_CURRENT); index = bars - 1 - index; for(int w = index; w < bars; w++) { openBuffer[w] = EMPTY_VALUE; highBuffer[w] = EMPTY_VALUE; lowBuffer[w] = EMPTY_VALUE; closeBuffer[w] = EMPTY_VALUE; colorBuffer[w] = 2; } } } ChartRedraw(); }
Custom Replay Candles
The core of the replay system is the ability to control the visibility of historical price data, revealing candles progressively as the simulation advances. To achieve this, we use a custom DRAW_COLOR_CANDLES indicator to control the visibility of historical OHLC data independently of the chart's native candlesticks. This allows the replay system to conceal unrevealed candles and progressively display them as playback advances. Three functions handle this process: initializing the replay view, clearing the custom candles, and revealing individual candles during playback.
//+------------------------------------------------------------------+ //| SHOW CUSTOM REPLAY CANDLES | //+------------------------------------------------------------------+ void renderReplayCandles(const datetime time1, const datetime time2) { //--- bars = iBars(_Symbol, PERIOD_CURRENT); if(CopyRates(_Symbol, PERIOD_CURRENT, 0, bars, rates) > 0) { lastCalculated = (ArraySize(rates) - (iBarShift(_Symbol, PERIOD_CURRENT, time1))); endCalculate = (ArraySize(rates) - (iBarShift(_Symbol, PERIOD_CURRENT, time2) + 2)); for(int w = 0; w < ArraySize(rates) - 1 && !IsStopped(); w++) { openBuffer[w] = rates[w].open; highBuffer[w] = rates[w].high; lowBuffer[w] = rates[w].low; closeBuffer[w] = rates[w].close; colorBuffer[w] = (closeBuffer[w] > openBuffer[w]) ? 0 : 1; if(rates[w].time > time1 && rates[w].time < time2) { //--- EMPTY BUFFER SLOTS THAT FALLS IN BETWEEN BOTH TIME VALUES openBuffer[w] = EMPTY_VALUE; highBuffer[w] = EMPTY_VALUE; lowBuffer[w] = EMPTY_VALUE; closeBuffer[w] = EMPTY_VALUE; colorBuffer[w] = 2; } } //--- CREATE REPLAY PRICE LINE createHLine(_REPLAY_PRICE, 0, chartState.getPriceColor(), false, "Replay Price"); lastPrice = iClose(_Symbol, PERIOD_CURRENT, iBarShift(_Symbol, PERIOD_CURRENT, time1)); } ChartRedraw(); } //+------------------------------------------------------------------+ //| HIDE CUSTOM REPLAY CANDLES | //+------------------------------------------------------------------+ void clearReplayCandles() { //--- int total = iBars(_Symbol, PERIOD_CURRENT); for(int w = 0; w < total && !IsStopped(); w++) { openBuffer[w] = EMPTY_VALUE; highBuffer[w] = EMPTY_VALUE; lowBuffer[w] = EMPTY_VALUE; closeBuffer[w] = EMPTY_VALUE; colorBuffer[w] = 2; } ChartRedraw(); } //+------------------------------------------------------------------+ //| REVEAL ONE CANDLE AT A TIME | //+------------------------------------------------------------------+ void revealOneCandle(const int prevCalculated) { //--- if(CopyRates(_Symbol, PERIOD_CURRENT, 0, bars, rates) > 0) { datetime time = INT_MAX; openBuffer[prevCalculated] = rates[prevCalculated].open; highBuffer[prevCalculated] = rates[prevCalculated].high; lowBuffer[prevCalculated] = rates[prevCalculated].low; closeBuffer[prevCalculated] = rates[prevCalculated].close; colorBuffer[prevCalculated] = (closeBuffer[prevCalculated] > openBuffer[prevCalculated]) ? 0 : 1; lastPrice = closeBuffer[prevCalculated]; time = rates[prevCalculated].time; //--- TICK-BASED POSITION EVALUATION checkOpenPositions(time); } //--- ENSURE REPLAY BAR IS IN VIEW int replayBar = iBarShift(_Symbol, PERIOD_CURRENT, rates[prevCalculated].time); int visible = (int)ChartGetInteger(0, CHART_VISIBLE_BARS); ChartNavigate(0, CHART_END, -(replayBar - (visible / 4))); //--- UPDATE REPLAY PRICE ObjectMove(0, _REPLAY_PRICE, 0, 0, lastPrice); ChartRedraw(); }
Explanation:
- renderReplayCandles(): This function initializes the replay visualization by copying historical price data using CopyRates() and calculating the replay boundary indices with iBarShift(). It populates the OHLC buffers and assigns candle colors based on price direction. Candles within the selected replay interval are concealed by setting their OHLC values to EMPTY_VALUE. Finally, the function creates the replay-price line and initializes lastPrice from the starting bar's closing price.
- clearReplayCandles(): When replay mode is disabled, clearReplayCandles() resets the OHLC buffers to EMPTY_VALUE and the color buffer to index 2, clearing the custom candle display without altering the underlying historical price data. A final call to ChartRedraw() refreshes the chart.
- revealOneCandle(): During playback, revealOneCandle() progressively displays historical candles by populating their OHLC and color buffers. It updates lastPrice, evaluates open positions against the current replay bar's tick data to detect TP or SL hits, adjusts the viewport to keep the replay candle visible, and moves the replay-price line to reflect the latest price before refreshing the chart.
Initialization Logic (OnInit)
With the custom replay functions in place, we implement OnInit() to initialize the interface, configure the indicator buffers, and prepare the replay system. The function creates the menu button, binds and initializes the five OHLC and color buffers, sets the indicator's price precision, and starts the playback timer using the selected speed interval. The percentile input is validated to keep it within the acceptable range of 10–100%. Values above 100 are capped at 100, while values below 1 default to 10. This prevents invalid percentile selections and ensures that the statistical calculations use a meaningful percentile threshold.
//+------------------------------------------------------------------+ //| INITIALIZATION | //+------------------------------------------------------------------+ int OnInit() { //--- createButton(_MENU_BUTTON, 10, 50, 40, 40, CORNER_LEFT_LOWER, clrWhite, clrBlue, clrBlack, 10, "Menu Button", "ON"); SetIndexBuffer(0, openBuffer, INDICATOR_DATA); SetIndexBuffer(1, highBuffer, INDICATOR_DATA); SetIndexBuffer(2, lowBuffer, INDICATOR_DATA); SetIndexBuffer(3, closeBuffer, INDICATOR_DATA); SetIndexBuffer(4, colorBuffer, INDICATOR_COLOR_INDEX); ArrayInitialize(openBuffer, EMPTY_VALUE); ArrayInitialize(highBuffer, EMPTY_VALUE); ArrayInitialize(lowBuffer, EMPTY_VALUE); ArrayInitialize(closeBuffer, EMPTY_VALUE); ArraySetAsSeries(data, true); IndicatorSetInteger(INDICATOR_DIGITS, _Digits); EventSetMillisecondTimer(speedIntervals[speedIndex]); percentile = inpPercentilePercent; //--- VALIDATE INPUT if(percentile > 100) percentile = 100; if(percentile < 1) percentile = 10; return(INIT_SUCCEEDED); }
Cleanup (OnDeinit)
To ensure the chart and terminal are returned to a clean state when the indicator is removed or reinitialized, OnDeinit() handles the cleanup process. It stops the playback timer, restores the chart's default interaction settings, and deletes objects associated with the replay tool. It then clears the custom replay candles, restores the original chart configuration through chartState.restore(), and calls ChartRedraw() to apply the changes.
//+------------------------------------------------------------------+ //| DEINITIALIZATION | //+------------------------------------------------------------------+ void OnDeinit(const int32_t reason) { //--- EventKillTimer(); ChartSetInteger(0, CHART_EVENT_OBJECT_DELETE, false); ChartSetInteger(0, CHART_SHOW_ONE_CLICK, true); ChartSetInteger(0, CHART_SHOW_OBJECT_DESCR, false); ChartSetInteger(0, CHART_KEYBOARD_CONTROL, true); ChartSetInteger(0, CHART_SHOW_PRICE_SCALE, true); ObjectsDeleteAll(0, _PROG_NAME); clearReplayCandles(); chartState.restore(); ChartRedraw(); }
Calculation Event
Unlike conventional indicators that perform calculations in response to incoming price data or new bars, this tool is primarily driven by user interactions and timer events. Consequently, OnCalculate() contains no additional processing logic and simply returns rates_total, allowing the indicator to maintain its calculation state while replay progression, candle rendering, and trade management are handled by dedicated functions and event handlers.
//+------------------------------------------------------------------+ //| CALCULATE EVENT FUNCTION | //+------------------------------------------------------------------+ int OnCalculate(const int32_t rates_total, const int32_t prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int32_t &spread[]) { //--- return(rates_total); }
Interactive Engine
The interactive engine handles user interactions with the Adaptive Bar Replay Tool through MQL5’s event-driven OnChartEvent() function. It processes button clicks, keyboard shortcuts, drag-and-drop operations, and object deletion. These actions control playback, adjust replay boundaries, manage simulated positions, and keep chart objects synchronized with internal data.
//+------------------------------------------------------------------+ //| CHART EVENT FUNCTION | //+------------------------------------------------------------------+ void OnChartEvent(const int32_t id, const long &lparam, const double &dparam, const string &sparam) { //--- switch(id) { case CHARTEVENT_OBJECT_CLICK: //--- TOGGLE MENU BUTTON if(sparam == _MENU_BUTTON) { toggleMenuButton(); } //--- TOGGLE PLAY BUTTON if(sparam == _REPLAY_PLAY_BUTTON) { togglePlayButton(); } //--- TOGGLE PLAY BUTTON WHEN START ANCHOR IS SELECTED if(sparam == _REPLAY_ANCHOR1 && ObjectGetInteger(0, _REPLAY_ANCHOR1, OBJPROP_SELECTED)) { isPlay = true; togglePlayButton(); } //--- TOGGLE PLAY BUTTON WHEN END ANCHOR IS SELECTED if(sparam == _REPLAY_ANCHOR2 && ObjectGetInteger(0, _REPLAY_ANCHOR2, OBJPROP_SELECTED)) { isPlay = true; togglePlayButton(); } //--- INCREASE PLAYBACK SPEED if(sparam == _REPLAY_SPEED_UP_BUTTON) { ObjectSetInteger(0, _REPLAY_SPEED_UP_BUTTON, OBJPROP_STATE, false); if(speedIndex > 0) { speedIndex--; EventSetMillisecondTimer(speedIntervals[speedIndex]); ObjectSetString(0, _REPLAY_SPEED_LABEL, OBJPROP_TEXT, speedTexts[speedIndex]); ChartRedraw(); } } //--- REDUCE PLAYBACK SPEED if(sparam == _REPLAY_SPEED_DOWN_BUTTON) { ObjectSetInteger(0, _REPLAY_SPEED_DOWN_BUTTON, OBJPROP_STATE, false); if(speedIndex < ArraySize(speedIntervals) - 1) { speedIndex++; EventSetMillisecondTimer(speedIntervals[speedIndex]); ObjectSetString(0, _REPLAY_SPEED_LABEL, OBJPROP_TEXT, speedTexts[speedIndex]); ChartRedraw(); } } //--- CREATE IMAGINARY BUY POSITION if(sparam == _REPLAY_BUY_BUTTON) { if(isPercentileReady) { double initialTP = (SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) > 0) ? ((SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * 10) * _Point) : (200 * _Point); trade.positionID = generatePositionID(); trade.entryPrice = lastPrice; trade.sl = NormalizeDouble(trade.entryPrice - slPercentile, _Digits); trade.tp = (inpAutoMode == AUTOMATIC_SL) ? trade.entryPrice + initialTP : trade.entryPrice + tpPercentile; tooltip = (string)("BUY" + " @ " + DoubleToString(trade.entryPrice, _Digits)); showPosition(trade, tooltip); //--- APPEND TO REPLAY POSITIONS ARRAY ArrayResize(replayPositions, ArraySize(replayPositions) + 1); replayPositions[ArraySize(replayPositions) - 1].dealType = DEAL_TYPE_BUY; replayPositions[ArraySize(replayPositions) - 1].positionID = trade.positionID; replayPositions[ArraySize(replayPositions) - 1].entryPrice = lastPrice; replayPositions[ArraySize(replayPositions) - 1].sl = trade.sl; replayPositions[ArraySize(replayPositions) - 1].tp = trade.tp; } else { Print("Unable to open position. PERCENTILE ERROR"); } } //--- CREATE IMAGINARY SELL POSITION if(sparam == _REPLAY_SELL_BUTTON) { if(isPercentileReady) { double initialTP = (SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) > 0) ? ((SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * 10) * _Point) : (200 * _Point); trade.positionID = generatePositionID(); trade.entryPrice = lastPrice; trade.sl = NormalizeDouble(trade.entryPrice + slPercentile, _Digits); trade.tp = (inpAutoMode == AUTOMATIC_SL) ? trade.entryPrice - initialTP : trade.entryPrice - tpPercentile; tooltip = (string)("SELL" + " @ " + DoubleToString(trade.entryPrice, _Digits)); showPosition(trade, tooltip); //--- APPEND TO REPLAY POSITIONS ARRAY ArrayResize(replayPositions, ArraySize(replayPositions) + 1); replayPositions[ArraySize(replayPositions) - 1].dealType = DEAL_TYPE_SELL; replayPositions[ArraySize(replayPositions) - 1].positionID = trade.positionID; replayPositions[ArraySize(replayPositions) - 1].entryPrice = lastPrice; replayPositions[ArraySize(replayPositions) - 1].sl = trade.sl; replayPositions[ArraySize(replayPositions) - 1].tp = trade.tp; } else { Print("Unable to open position. PERCENTILE ERROR"); } } ChartRedraw(); break; case CHARTEVENT_KEYDOWN: //--- END ANCHOR CREATION if(ObjectGetInteger(0, _REPLAY_ANCHOR1, OBJPROP_SELECTED)) { //--- SHIFT + E if(TerminalInfoInteger(TERMINAL_KEYSTATE_SHIFT) && lparam == 'E') { //--- EXTEND END ANCHOR BY 20 BARS TO THE RIGHT anchor2Time = (anchor1Time + PeriodSeconds() * 20); ChartSetInteger(0, CHART_SHOW_PRICE_SCALE, true); drawAnchorLine(_REPLAY_ANCHOR2, anchor2Time, "Replay End Anchor"); ObjectsDeleteAll(0, _REPLAY_POSITION_ENTRY); ObjectsDeleteAll(0, _REPLAY_POSITION_SL); ObjectsDeleteAll(0, _REPLAY_POSITION_TP); renderReplayCandles(anchor1Time, anchor2Time); ArrayResize(replayPositions, 0); systemID = 0; ChartRedraw(); } } //--- HOTKEYS if(ObjectFind(0, _REPLAY_SPEED_LABEL) != -1) { //--- CTLR + '+' if(TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) && lparam == 187) { if(speedIndex > 0) { speedIndex--; EventSetMillisecondTimer(speedIntervals[speedIndex]); ObjectSetString(0, _REPLAY_SPEED_LABEL, OBJPROP_TEXT, speedTexts[speedIndex]); ChartRedraw(); } } //--- CTLR + '-' if(TerminalInfoInteger(TERMINAL_KEYSTATE_CONTROL) && lparam == 189) { if(speedIndex < ArraySize(speedIntervals) - 1) { speedIndex++; EventSetMillisecondTimer(speedIntervals[speedIndex]); ObjectSetString(0, _REPLAY_SPEED_LABEL, OBJPROP_TEXT, speedTexts[speedIndex]); ChartRedraw(); } } } break; case CHARTEVENT_OBJECT_DRAG: //--- DRAG-AND-DROP OPERATIONS if(sparam == _REPLAY_ANCHOR1) { //--- ENSURE REPLAY START ANCHOR IS PLACED CORRECTLY anchor1Time = (datetime)ObjectGetInteger(0, _REPLAY_ANCHOR1, OBJPROP_TIME); anchor1Time = normalizeToChartTime(anchor1Time); anchor1Time = (anchor1Time > iTime(_Symbol, PERIOD_CURRENT, 1)) ? iTime(_Symbol, PERIOD_CURRENT, 1) : anchor1Time; anchor1Time = (anchor1Time > anchor2Time) ? anchor2Time - (PeriodSeconds() * 20) : anchor1Time; renderReplayCandles(anchor1Time, anchor2Time); ArrayResize(replayPositions, 0); systemID = 0; //--- DELETE IMAGINARY POSITION LEVELS ObjectsDeleteAll(0, _PROG_NAME + "REPLAY_POSITION"); ChartRedraw(); //--- RUN ADAPTIVE SYSTEM AT EACH ANCHOR1 DRAG-AND-DROP getDeals(anchor1Time, data); computeExcursions(data); if(((tpPercentile = computePercentile(false, data)) == EMPTY_VALUE && inpAutoMode == AUTOMATIC_TP_SL) || ((tpPercentile = computePercentile(false, data)) <= 0 && inpAutoMode == AUTOMATIC_TP_SL) || (slPercentile = computePercentile(true, data)) == EMPTY_VALUE || (slPercentile = computePercentile(true, data)) <= 0) { Print("Error: Failed to calculate TP/SL percentile. Trading restricted"); isPercentileReady = false; return; } isPercentileReady = true; tpPercentile = NormalizeDouble(tpPercentile, _Digits); slPercentile = NormalizeDouble(slPercentile, _Digits); //--- SYSTEM SUMMARY Print("+=================================+"); Print("Adaptive Bar Replay Tool - MFE and MAE Percentile Analysis"); Print("Symbol : ", _Symbol, "(" + EnumToString(_Period) + ") || Percentile : " + IntegerToString(percentile) + "%"); Print("Historical trades up to: ", anchor1Time); if(inpAutoMode == AUTOMATIC_TP_SL) Print("TP percentile : ", tpPercentile); Print("SL percentile : ", slPercentile); } if(sparam == _REPLAY_ANCHOR2) { //--- ENSURE REPLAY END ANCHOR IS PLACED CORRECTLY anchor2Time = (datetime)ObjectGetInteger(0, _REPLAY_ANCHOR2, OBJPROP_TIME); anchor2Time = normalizeToChartTime(anchor2Time); anchor2Time = (anchor2Time > iTime(_Symbol, PERIOD_CURRENT, 1)) ? iTime(_Symbol, PERIOD_CURRENT, 1) : anchor2Time; anchor2Time = (anchor2Time < anchor1Time) ? anchor1Time + (PeriodSeconds() * 20) : anchor2Time; ObjectSetInteger(0, _REPLAY_ANCHOR2, OBJPROP_TIME, anchor2Time); ObjectsDeleteAll(0, _PROG_NAME + "REPLAY_POSITION"); renderReplayCandles(anchor1Time, anchor2Time); ArrayResize(replayPositions, 0); systemID = 0; ChartRedraw(); } //--- HANDLE TP MODIFICATIONS if(StringFind(sparam, _REPLAY_POSITION_TP) >= 0) { int positionID = extractPositionID(sparam); double price = ObjectGetDouble(0, sparam, OBJPROP_PRICE); int index = -1; if((index = getPositionIndex(positionID, replayPositions)) >= 0) { double diff = (SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) > 0) ? ((SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * 10) * _Point) : (200 * _Point); if(replayPositions[index].dealType == DEAL_TYPE_BUY) { //--- price = (price <= replayPositions[index].entryPrice) ? replayPositions[index].entryPrice + diff : price; replayPositions[index].tp = price; } if(replayPositions[index].dealType == DEAL_TYPE_SELL) { price = (price >= replayPositions[index].entryPrice) ? replayPositions[index].entryPrice - diff : price; replayPositions[index].tp = price; } price = NormalizeDouble(price, _Digits); ObjectSetDouble(0, sparam, OBJPROP_PRICE, price); } } ChartRedraw(); break; case CHARTEVENT_OBJECT_DELETE: //--- OBJECT DELETION RESTORATION if(sparam == _REPLAY_ANCHOR1) { Print("Replay start anchor line deleted. RESTORED"); drawAnchorLine(_REPLAY_ANCHOR1, anchor1Time, "Replay Anchor"); } if(sparam == _REPLAY_ANCHOR2) { Print("Replay end anchor line deleted. RESTORED"); drawAnchorLine(_REPLAY_ANCHOR2, anchor2Time, "Replay Anchor#2"); } if(StringFind(sparam, _REPLAY_POSITION_TP) != -1) { //--- RECREATE TP LINES IF DELETED int positionID = extractPositionID(sparam); int index = -1; if((index = getPositionIndex(positionID, replayPositions)) >= 0) createHLine(sparam, replayPositions[index].tp, clrLimeGreen, (inpAutoMode == AUTOMATIC_SL), "TP", STYLE_DASHDOT); } ChartRedraw(); break; } }
The following section explains the implementation in four layers:
- Object Click — CHARTEVENT_OBJECT_CLICK
The object-click event handles interactions with the tool's interface. It toggles the menu and playback buttons, allows clicking either replay anchor to initiate playback, and adjusts playback speed through the speed-up and speed-down buttons. It also handles the creation of hypothetical buy and sell positions by capturing the current replay price, calculating the initial SL and TP levels, displaying the position on the chart, and storing its details in the replayPositions array for subsequent management. - Keyboard Presses — CHARTEVENT_KEYDOWN
To streamline replay control, the engine incorporates keyboard shortcuts that let traders define the replay range and adjust playback speed directly from the keyboard. Shift + E creates the end anchor 20 bars ahead of the start anchor, while Ctrl + '+' and Ctrl + '-' increase and decrease playback speed, respectively.
- Drag-and-Drop Operations — CHARTEVENT_OBJECT_DRAG
The drag-and-drop handler manages replay anchor movements and simulated position modifications. When either anchor is moved, the engine normalizes its time, enforces valid boundaries, clears existing position objects, and redraws the replay candles for the updated range. For Take Profit adjustments, it extracts the positionID from the dragged object's name and uses it to locate the corresponding position in replayPositions[]. The engine then validates the new TP against the position's direction and entry price, updates the stored TP value, and synchronizes the chart object with the adjusted price. - Object Deletion — CHARTEVENT_OBJECT_DELETE
The final layer protects essential replay objects from accidental removal. If either replay anchor is deleted, the engine recreates it using its stored time, preserving the selected historical range. Similarly, when a Take Profit line is deleted, the engine extracts its positionID from the object name and uses getPositionIndex() to locate the corresponding simulated position in replayPositions[]. If the position exists, the TP line is recreated at the stored tp price, restoring the original target level. Finally, ChartRedraw() refreshes the chart to reflect the restored objects.
Timer Event Handler
The OnTimer() function drives candle-by-candle replay progression whenever replayMode is active. It updates the current bar count, checks the replay boundary, and calls revealOneCandle() to display the next candle before advancing lastCalculated.
When the replay reaches its end, the function disables replay mode and calls togglePlayButton() to switch the interface back to its paused state. This automatic button toggle provides clear visual feedback that playback has finished, improving the user experience without requiring manual intervention.
//+------------------------------------------------------------------+ //| TIMER EVENT FUNCTION | //+------------------------------------------------------------------+ void OnTimer() { //--- if(replayMode) { bars = iBars(_Symbol, PERIOD_CURRENT); //--- SAFETY BOUNDARY if(lastCalculated > endCalculate) { replayMode = false; togglePlayButton(); //--- EXPOSE THE HIDDEN FUTURE PRICE INFORMATION if(ObjectFind(0, _REPLAY_ANCHOR2) >= 0) { //--- REVERSE THE INDEX DIRECTION int index = iBarShift(_Symbol, PERIOD_CURRENT, anchor2Time); bars = iBars(_Symbol, PERIOD_CURRENT); index = bars - 1 - index; if(CopyRates(_Symbol, PERIOD_CURRENT, 0, bars, rates) > 0) { for(int w = index; w < ArraySize(rates) && !IsStopped(); w++) { openBuffer[w] = rates[w].open; highBuffer[w] = rates[w].high; lowBuffer[w] = rates[w].low; closeBuffer[w] = rates[w].close; colorBuffer[w] = (closeBuffer[w] > openBuffer[w]) ? 0 : 1; } } } ChartRedraw(); return; } revealOneCandle(lastCalculated); lastCalculated++; } }
Final Testing
To evaluate the tool's adaptability across different market conditions and instrument characteristics, testing was conducted on two currency pairs: GBPUSD and AUDUSD, on PERIOD_H1 (one hour timeframe) respectively using the default indicator settings. Before displaying the summary, an additional ArrayPrint() statement was temporarily added to the toggleMenuButton() function to output the collected historical trade data to the Journal. This made it possible to verify the number of qualifying historical trades and inspect the corresponding Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) values used in the percentile-based calculations. The resulting Journal outputs for both instruments are presented below.

Test on GBPUSD

Test on AUDUSD
With the collected historical excursion data, the tool calculated the automatic Stop Loss (SL) distances as follows:
- GBPUSD: 0.00225
- AUDUSD: 0.0018
The difference in the calculated values illustrates how the tool derives instrument-specific SL distances from historical trade excursion data rather than applying a fixed distance across all symbols. Consequently, the resulting risk parameters reflect the historical price movement characteristics captured for each instrument.
Note: These results are illustrative and are based on a private trading account. Users can obtain their own historical MFE and MAE samples by adding an ArrayPrint(data); statement inside toggleMenuButton(), immediately before the system summary. These results demonstrate percentile-based level calculations, not improved trading performance.
Conclusion
We implemented an adaptive bar replay tool that applies percentile analysis to historical Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE) values to derive data-driven trade-management parameters. By analyzing historical trades, the tool extracts representative excursion levels and integrates them into the replay process for adaptive Stop Loss and Take Profit management.
The implementation combines historical trade retrieval, excursion analysis, percentile calculation, and event-driven replay execution into a unified MQL5 system. This approach reduces reliance on arbitrary fixed parameters and provides a reproducible framework for evaluating trade-management strategies. The resulting parameters remain dependent on the selected symbol, timeframe, historical sample, and percentile settings, making further testing essential before applying them to live trading.
The default 75th percentile and the 20-position historical sample limit are implementation choices rather than universally optimal trading parameters. Users are encouraged to experiment with different percentile settings and sample sizes to assess their suitability.
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.