Backtesting Indicator Signals in MQL5 Using Buffers and Chart Objects
Introduction
An indicator can display buy and sell signals without showing how they would have performed on historical data. Assessing those signals should not require writing a separate Expert Advisor (EA) for each indicator. ExternalIndicatorBacktest.mq5 backtests signals from an attached indicator via readable buffers or time-anchored chart objects. The indicator source is not modified.
The download includes the EA and three demonstration indicators: DemoSignals for buffer signals, and ObjectSignals and RSIDivergenceObjects for chart objects. The EA reconstructs virtual positions from closed bars' open, high, low, and close (OHLC) prices on a chart or in the visual Strategy Tester. It sends no orders and displays exit segments and statistics on the chart.
The diagram follows the signal snapshot through the OHLC engine to the backtest snapshot of virtual positions, exit segments, and statistics.

Image 1: Buffer and object sources share the same OHLC backtest engine.
A compiled indicator can be backtested if it exposes a readable buffer or time-anchored chart object with a defined directional rule. Arrow color alone is insufficient.
Defining the backtest rules
Before comparing an indicator’s signals, we need to decide when an entry becomes possible and how the resulting virtual position will be managed. These rules let both signal sources use the same backtest engine.
Entry interval and signal timing
Start by defining the entry window and signal delay.
| Parameter | Effect on entry selection |
|---|---|
| InpSignalShift | Entry delay in existing chart bars, including across gaps. |
| InpHistoryBars | Maximum number of closed entry bars evaluated. |
| from | Optional InpAdvanced key. Includes entries opening at or after the specified time. |
| to | Optional InpAdvanced key. Excludes entries opening at or after the specified time. |
The EA declares the delay and bar limit as inputs:
input int InpHistoryBars=3000; // Maximum closed historical entry bars to evaluate input int InpSignalShift=1; // Closed-bar offset; 3 for confirmed five-bar fractals
For example, with InpSignalShift=1 on M15, a signal on the 10:00 bar maps to the next available opening, normally 10:15. That entry is evaluated only after its bar closes.
The EA needs InpSignalShift+1 bars before the first entry bar. The delay identifies the signal bar; one additional bar provides the prior observation for comparison. If a start date is set, the EA waits when that context is unavailable.
Additional history can only increase coverage within the configured date boundaries and up to InpHistoryBars. Without a start date, the entry window may be shorter after reserving context. Without either boundary, the window advances as bars close.
Each rebuild starts without an active virtual position. Changing the window can change coverage and subsequent entries. Compare the panel's range mode, entry boundaries, and bar count before varying exits.
One active virtual position
Only one virtual position can be active. If none remains after the opening checks, an allowed, non-conflicting signal can open one.
| Signal case | EA decision |
|---|---|
| Same direction as the active virtual position | Keep the position open. Count the signal in Skipped. |
| Allowed opposite signal | If InpCloseOnOpposite=true, close the remainder and open the reverse position at the opening quote. Otherwise, keep the position open and count the signal in Skipped. |
| Signal in a disabled direction | Count the signal in Skipped. It cannot close or reverse an active virtual position. |
| Conflict: both buy and sell on the same bar | Increment Conflicts. The conflict does not open, close, or reverse a virtual position. |
Executable prices and ambiguous bars
The table gives the execution rules used to reconstruct virtual positions from OHLC bars.
| Execution case | Rule |
|---|---|
| Bid and Ask | Historical OHLC prices are Bid. To reconstruct Ask, add the recorded bar spread to Bid. Convert the spread from points to price units, clamp negative values to zero, and keep it constant within the bar. |
| Executable side | Long positions open at Ask and close at Bid; short positions open at Bid and close at Ask. |
| Opening quote | Check existing positions for gap exits before acting on the signal. Check again after a possible entry. Fill any stop loss or target reached at the executable opening quote, checking the stop loss first. |
| Intrabar levels | Use Bid Low and High for a long position, or Ask High and Low for a short position, as the adverse and favorable extremes, respectively. Fill a stop loss at its level for the remaining fraction. If no stop loss is reached, multiple targets can fill at their respective levels. |
| Ambiguous bar | If the stop loss and the next target are both reached during the intrabar check, the OHLC data cannot establish their order. Close the remaining fraction at the stop loss and increment the ambiguous-bar count. |
| Rounding | Target fills allow a small rounding tolerance at the opening quote and within the bar. Stop loss checks and the target check used to count ambiguous bars use exact levels. |
Targets, partial exits, and break-even
The EA supports one to three take-profit targets measured from the executable entry. Active distances must be positive and strictly increasing. Each active target must close a positive fraction of the original position.
InpClosePercent1 and InpClosePercent2 specify the early partial exits when applicable. Their combined share must leave a positive remainder for the last target, which closes it in full. The table uses percentage inputs of 50 and 30.
| Active targets | Effective fractions with percentage inputs 50 and 30 |
|---|---|
| 1 | TP1: 100%; both percentage inputs are ignored. |
| 2 | TP1: 50%; TP2: 50%; the second percentage input is ignored. |
| 3 | TP1: 50%; TP2: 30%; TP3: 20%. |
With more than one target, InpBreakEven can move the remaining stop loss to the entry price plus a directional offset after TP1. With one target, TP1 closes the whole position.
If TP1 fills at the opening quote, the revised stop applies before the bar's extremes are processed. If TP1 fills intrabar, the revised stop applies from the following bar because the price sequence is unknown.
Weighted pips and completed virtual position statistics
Commission is a round-trip cost in equivalent pips per full original position. Each exit is charged in proportion to the fraction closed. InpPipSize=0 uses ten points for three- or five-digit symbols and one point otherwise. Other conventions require an explicit pip size.
For exit j, let d be +1 for a long or −1 for a short. Let X_j be its executable exit price and E the entry price. Let q be the pip size, w_j the original-size fraction, and C the commission in pips. The exit's contribution is:
P_j = w_j × (d × (X_j − E) / q − C)
With zero commission, closing 50% at +20 gross pips adds +10 weighted pips.
| Measure or exit reason | Definition |
|---|---|
| Signals | Counts non-conflicting directional events after the applicable event rule is applied. |
| Skipped / Conflicts | Counted separately according to the decision table in “One active virtual position”. Conflicts are excluded from Signals. |
| Completed virtual position result | Sum of all exit contributions in weighted pips, separate from account currency. Completed positions count as wins or losses by the sign of this sum. Results close to zero within the numerical tolerance count as flat. |
| Win rate | Wins divided by completed virtual positions, including flat results in the denominator. Long and short rates use their respective counts. The panel shows n/a if the denominator is zero. |
| Completed virtual position drawdown | Largest decline from a running peak of cumulative completed results. Partial exits enter the curve only when the virtual position is fully closed. Floating intrabar results and real account equity are excluded. |
| END_HISTORY | If a virtual position is still open at the end of the backtest, the EA closes the remaining fraction at the last closed bar’s Close using the appropriate Bid or Ask side. This exit belongs to the current snapshot and can change or disappear on a later rebuild. |
Verify source selection, decoding, and signal availability before interpreting these statistics.
Configuration requirements
Use this checklist when configuring the history, signal source, and exit rules.
- History: InpHistoryBars and InpSignalShift must each be at least 1. When both date boundaries are set, the start must precede the end. The EA also rejects combined history and signal-context counts that exceed the supported range.
- Timeframe: only fixed-duration periods are supported. The monthly timeframe, PERIOD_MN1, is rejected because calendar months vary in length. Object containment and exit timestamps use PeriodSeconds(), which returns the chart period's duration in seconds.
- Chart selection: InpChartWindow chooses the window containing the indicator or objects. Use −1 to search all windows, 0 for the main chart, and positive indices for subwindows; other negative values are rejected.
- Buffer decoding: indices must be nonnegative; two-buffer and comparison modes require distinct indices. In threshold mode, the buy threshold InpBuyLevel must be below the sell threshold InpSellLevel. Directional codes must differ and must not match the selected empty-value convention.
- Object decoding: buy and sell rules must be nonempty and different. Arrow-code rules accept integers from 1 through 255.
- Exit accounting: stop loss must be positive. Pip size, commission, break-even offset, and weighted-pip label offset must be nonnegative. Active target distances and fractions must satisfy the rules above; zero pip size selects automatic sizing.
Reading signals from indicator buffers
Select the existing instance
Set InpIndicatorSource to SOURCE_CHART to read buffers from an indicator already attached to the chart. GetAttachedIndicator() searches the windows selected by InpChartWindow: 0 for the main chart, positive indices for subwindows, and −1 for all windows.
Match the exact short name in InpChartIndicator (find it with Ctrl+I), rather than the EX5 filename or path; a blank input leaves every indicator in the selected windows eligible. Only when exactly one candidate matches does the EA call ChartIndicatorGet() to obtain its handle.
input ENUM_INDICATOR_SOURCE InpIndicatorSource=SOURCE_CHART; // Default: use the attached indicator input string InpChartIndicator=""; // Exact short name; blank selects the only chart indicator input int InpChartWindow=-1; // Subwindow; -1 searches all chart windows
Buffer indices start at zero. Enter the required indices in “Buy buffer or directional-code buffer” (InpBuyBuffer) and, when a second series is needed, “Sell buffer in two-buffer mode” (InpSellBuffer). Use the indicator documentation and Data Window values on signal and neutral bars to identify them. Plot labels can help, but some internal buffers are not exposed.
Align prices and observations before decoding
ReadHistoricalRates() loads closed price bars and the older context needed for the signal delay and prior-state comparison. That context can precede the configured start date without becoming eligible for entries.
CopyBuffer() gets values over the same interval in chronological order. Decoding starts only after every required buffer returns one value per bar.
This excerpt from RebuildChartHistory() shows the buffer read and its failure branch. The rates array supplies the time boundaries, and count is the required number of values. The preceding two flag indicates whether the decoding rule needs a second buffer.
if(CopyBuffer(g_handle,InpBuyBuffer,rates[0].time,rates[count-1].time,buy)!=count || (two && CopyBuffer(g_handle,InpSellBuffer,rates[0].time,rates[count-1].time,sell)!=count)) { //--- Discard previous statistics when a selected buffer cannot be read. int error=GetLastError(); // Buffer selection or asynchronous calculation error g_invalid_buffer=(error==ERR_INDICATOR_WRONG_INDEX); g_status=(g_invalid_buffer ? "Invalid buffer index: correct inputs" : "Buffer unavailable: verify index/history | error "+IntegerToString(error)); if(StringFind(g_selected,"(no buffers)")>=0) g_status="No buffers: set InpIndicatorSource=SOURCE_OBJECTS"; ZeroMemory(g_stats); ZeroMemory(g_trade); g_last_entry_bar=0; ObjectsDeleteAll(0,g_prefix+"Trade_"); UpdatePanel(true); return; }
The EA clears previous statistics and exit segments at the start of each rebuild. If history or buffer data are unavailable, it stops the rebuild and retries the read on a later rebuild. If the final rebuild in the visual Strategy Tester fails, it returns an invalid result.
Choose the empty-value convention and signal rule
Zero can be a valid RSI or MACD value, while an arrow buffer may use it to indicate that no signal is present. InpEmptyMode tells the EA which convention to follow. Invalid numbers and EMPTY_VALUE are always treated as empty. EMPTY_ZERO also treats zero as empty, while EMPTY_CUSTOM uses the value assigned to empty in InpAdvanced.
After checking for empty values, the EA applies the InpSignalMode rule in the table.
| Mode | Configured interpretation |
|---|---|
| SIGNAL_TWO_BUFFERS | A nonempty buy buffer signals long; a nonempty sell buffer signals short. Both together return a conflict. |
| SIGNAL_CODES | The buy-buffer input selects one directional-code buffer. Values must equal buycode or sellcode; defaults are 1 and −1. |
| SIGNAL_THRESHOLDS | The buy-buffer input selects the series. Values at or below InpBuyLevel signal long; values at or above InpSellLevel signal short. |
| SIGNAL_COMPARE | Buy when the first selected buffer exceeds the second; sell when it is below the second. Equal values are neutral. |
The decoder returns 1 for buy, −1 for sell, 0 for neutral, and 2 for conflict. InpSignalEvent selects SIGNAL_EACH_BAR to count every closed bar with a buy or sell direction, or SIGNAL_NEW_STATE to count only changes from the preceding bar. A neutral bar resets the comparison, so the same direction after it counts as a new signal.
DemoSignals uses 10/30 simple moving average (SMA) crossovers. Buffers 0 and 1 hold buy and sell arrows, and buffer 2 holds directional codes. In the Data Window below, the buy buffer is empty. The sell buffer shows the arrow price and buffer 2 shows −1.

Image 2: DemoSignals buffers in the Data Window.
For native RSI, set “Buy buffer or directional-code buffer” to 0 and “Buffer interpretation” to “Buy at or below lower level; sell at or above upper level”. Set “Lower buy threshold in threshold mode” to 30, “Upper sell threshold in threshold mode” to 70, and “Empty-value convention” to “EMPTY_VALUE only”.
To count entry into a threshold zone rather than every bar spent there, set “Repeated-signal handling” to “Signal only when the directional state changes”. For MACD, choose “Buy when first buffer exceeds second; sell when below” under “Buffer interpretation” and enter its documented main and signal buffer indices. Verify the indices for the attached implementation.
Reading signals from chart objects
For indicators that draw arrows or text objects, the EA identifies signals by matching object-name prefixes, arrow codes, or text substrings to buy and sell rules. With InpIndicatorSource set to SOURCE_OBJECTS, the following inputs select the matching method and define its buy and sell rules:
input ENUM_OBJECT_SIGNAL_MODE InpObjectMode=OBJECT_NAME_PREFIX; // How objects identify direction input string InpObjectBuy="BUY_"; // Buy prefix, arrow code, or text substring input string InpObjectSell="SELL_"; // Sell prefix, arrow code, or text substring
InpChartWindow limits the object search to the selected chart windows. The table shows how each mode identifies direction.
Use Ctrl+B to inspect an object's name, type, time, arrow code, or text. The first time anchor is its first date-and-time coordinate. Prefix and substring matching are case-sensitive. Specific prefixes exclude unrelated drawings.
| Object mode | Buy/sell rule | Supported identification |
|---|---|---|
| OBJECT_NAME_PREFIX | For example, BUY_/SELL_ | The object name starts with the configured prefix. A readable first time anchor is required. |
| OBJECT_ARROW_CODE | For example, 233/234 | The Wingdings code of a generic OBJ_ARROW. Native OBJ_ARROW_BUY and OBJ_ARROW_SELL require a different rule, such as names. |
| OBJECT_TEXT | For example, BUY/SELL | A configured substring occurs in OBJ_TEXT content. |
ObjectDirection() skips the EA's own EIBT_ objects and applies the table's buy and sell rules. Display color does not determine direction.
ReadObjectSignals() maps the first time anchor to a closed bar. Missing anchors, gaps, and anchors outside copied history are skipped. InpSignalShift then selects the entry bar.
In this excerpt from ReadObjectSignals(), stamp is the first time anchor and direction is the result of the object matching rule. The search finds the latest bar opening at or before stamp, then rejects anchors outside that bar. Buy and sell arrays collect the matched directions.
//--- Binary search associates an intrabar marker with its containing candle, never a weekend gap. int left=0; // Lower search bound int right=count-1; // Upper search bound int index=-1; // Most recent bar starting at or before the marker while(left<=right) { int middle=(left+right)/2; // Current candidate bar if(rates[middle].time<=stamp) { index=middle; left=middle+1; } else right=middle-1; } if(index<0 || stamp>=rates[index].time+PeriodSeconds(_Period)) continue; if(direction==1 || direction==2) buy[index]=1; if(direction==-1 || direction==2) sell[index]=1;
Several matching objects can identify the same bar, so the EA combines them before processing the signal. Matches in the same direction count once, while opposite directions produce a conflict. InpSignalMode, InpEmptyMode, and InpSignalEvent apply only to buffer sources.
To detect changes, the EA builds a source signature from matching object names, directions, and first time anchors, then compares it with the previous signature. Changes trigger a rebuild; changing only price leaves the historical signal unchanged.
Publication Time and Look-Ahead Bias
An object's first time anchor can precede publication: an indicator may confirm a pivot using later bars and then draw its arrow at the pivot. Treating that anchor as publication time introduces look-ahead bias. Use InpSignalShift to account for a known delay in bars. The EA does not record signals in real time, so it cannot verify variable delays, recover deleted signals, or reconstruct the original signals after arbitrary redrawing. Establish publication timing independently before interpreting the backtest.
RSIDivergenceObjects anchors BUY_RSID_ and SELL_RSID_ arrows to the confirmation bar. These prefixes exclude RSID_LINE_ pivot lines. Both sources then feed the same historical engine.
Building the historical backtest engine
Virtual position state and processing order
VirtualTrade tracks the entry price, stop loss, next target, remaining fraction, and accumulated result. Before loading data, RebuildChartHistory() calls InvalidateSnapshot() to clear the position, statistics, and both entry-bar markers.
For each closed entry bar, in chronological order:
- Check the existing virtual position for exits at the opening quote.
- Decode the delayed signal and apply the direction and conflict rules. Open or reverse a virtual position if permitted.
- Check exits again at the opening quote. The spread can trigger an immediate stop after entry.
- Check the intrabar extremes: give the stop loss priority over a target on an ambiguous bar. If the stop loss is not reached, process the partial exits for targets reached. If an intrabar TP1 fill triggers a break-even update, apply it from the next bar.
After signal handling and any entry or reversal, RebuildChartHistory() returns to the opening quote before checking the extremes. This excerpt shows the two calls in that order. The earlier opening check has already processed the position carried over from the preceding bar.
//--- Recheck the new entry at the opening quote before evaluating bar extremes.
ProcessTrade(quote);
ProcessHistoricalRange(rates[i]) After the loop, apply END_HISTORY only if a virtual position is still open. Intrabar exit timestamps use the final second of the bar as a reporting convention.
Accounting for partial exits and completed positions
A partial exit contributes to the result while leaving part of the virtual position open. CloseFraction() limits the exit to the available fraction, deducts proportional commission, and accumulates net weighted pips. The EA updates completed-position statistics once the remaining fraction reaches zero within the numerical tolerance.
The full implementations are in the attached ExternalIndicatorBacktest.mq5 source file.
Following one virtual position from signal to result
In this constructed example, a closed 10:00 M15 bar gives the only buy signal. With shift 1, a single rebuild processes the bars below once both have closed.
Use a pip size of 0.0001, a fixed two-pip spread, zero commission, and a 30-pip initial stop. Two targets at 20 and 40 pips close 50% each, with break-even enabled at zero offset. The hypothetical OHLC prices are Bid prices:
| Entry bar | Bid Open | Bid High | Bid Low | Bid Close |
|---|---|---|---|---|
| 10:15 | 1.0998 | 1.1024 | 1.0990 | 1.1018 |
| 10:30 | 1.1018 | 1.1042 | 1.1005 | 1.1038 |
| Event | Price | Closed share | Contribution (weighted pips) | Cumulative result (weighted pips) |
|---|---|---|---|---|
| 10:15 — Long entry at Ask | 1.1000 | — | — | 0 |
| 10:15 bar — TP1 | 1.1020 | 50% | +10 | +10 |
| 10:30 bar — TP2 closes the remainder | 1.1040 | 50% | +20 | +30 |
The first bar's Low stays above the initial stop at 1.0970. TP1 moves the stop to 1.1000 from the next bar. The EA skips a recheck because OHLC cannot place the Low before or after TP1.
On the 10:30 bar, neither the opening Bid nor the Low reaches the revised stop. TP2 completes one winning virtual position at +30 weighted pips, with two exit segments and nothing left for END_HISTORY.
Running the EA on chart history
Quick Start: run and adapt the SMA reference backtest
The settings below reproduce the SMA buffer configuration used in the article. The 30-pip stop loss, staged targets, partial exits, and zero-offset break-even illustrate exit handling. These settings were not optimized, and matching the published figures requires the same history and signal snapshot.
- Install the supplied MQL5 folders through File → Open Data Folder in MetaTrader 5. Compile ExternalIndicatorBacktest and DemoSignals.
- Open EURUSD M15, load price history, and attach DemoSignals. Set “Fast SMA period” to 10 and “Slow SMA period” to 30. Leave “Keep direction codes between crossovers” false for crossover-only codes.
- Attach ExternalIndicatorBacktest after the indicator. Set “Default: use the attached indicator” to “Read the indicator already attached to this chart” and “Subwindow; -1 searches all chart windows” to 0. If other indicators are present, enter DemoSignals (SMA crossover) in “Exact short name; blank selects the only chart indicator”. Apply the two settings tables below.
- Verify decoding against the Data Window or the intended chart objects. Check when the signal became available, as explained in “Publication Time and Look-Ahead Bias”. Confirm that the panel shows the intended source and entry interval. Check history coverage, older signal context, and indicator warm-up.
- Trace an individual exit segment back to its signal, entry bar, and exit level before comparing aggregate results. To adapt the example, keep the reference settings except for the inputs that differ in the relevant example. Passing initialization does not confirm that the EA is reading the intended signals.
Use these buffer settings in the EA’s Inputs:
| Input shown in MetaTrader 5 | Value |
|---|---|
| Buffer interpretation | Separate buy and sell buffers |
| Buy buffer or directional-code buffer | 0 |
| Sell buffer in two-buffer mode | 1 |
| Empty-value convention | EMPTY_VALUE only |
| Repeated-signal handling | Every valid closed bar is a signal |
| Closed-bar offset; 3 for confirmed five-bar fractals | 1 |
Paste the assignments below into “Optional key=value pairs separated by semicolons” (InpAdvanced). Omit the InpAdvanced= prefix.
The from=1735689600 and to=1738368000 values are Unix timestamps in seconds, selecting January 1, 2025, at 00:00:00 inclusively through February 1 at 00:00:00 exclusively. Unknown or duplicate keys, malformed numbers, and unsupported Boolean values are rejected.
| Input shown in MetaTrader 5 | Value |
|---|---|
| Maximum closed historical entry bars to evaluate | 3000 |
| Optional key=value pairs separated by semicolons | from=1735689600;to=1738368000;long=true;short=true;beoffset=0 |
| Price per pip; 0 = FX convention (3/5 digits: 10 points) | 0.0001 |
| Round-trip commission per full position in equivalent pips | 0 |
| Initial stop-loss distance | 30 |
| Active targets, from 1 to 3 | 3 |
| First target distance | 20 |
| Second target distance | 40 |
| Third target distance | 60 |
| Original position percentage at TP1 | 50 |
| Original position percentage at TP2 | 30 |
| Move remaining stop after TP1 | true |
| Close and reverse on an allowed opposite signal | true |
| Draw dashed entry-to-exit segments and price markers | true |
| Display realized weighted pips beside each drawn exit | true |
With three targets, TP3 closes the remaining 20% of the original virtual position.
To read the same SMA crossovers as directional codes, change “Buffer interpretation” to “One buffer containing directional codes” and set “Buy buffer or directional-code buffer” to 2. Append buycode=1;sellcode=-1 to the existing advanced settings. The interval and exit rules stay the same.
Display and Update
DrawVirtualExit() draws dashed exit segments with entry and exit markers. Optional weighted-pip labels show each exit's contribution and, on the final label, the virtual position total when there are multiple exits. Green, red, and gray indicate positive, negative, and flat exits.
Enable “Draw dashed entry-to-exit segments and price markers” (InpShowTradePaths) to display the segments and their optional labels. InpPipLabelOffset sets the distance above long exits or below short exits. If labels overlap, use the tooltips.
The panel below shows the fixed January SMA object-source backtest with three targets.

Image 3: Panel detail for the SMA object-source backtest on EURUSD M15: 98 completed virtual positions and −93.16 weighted pips.
The Events table shows when the EA rebuilds the displayed backtest.
| Event | Update behavior |
|---|---|
| OnInit() | Validate the configuration, run accounting self-tests if enabled, and attempt the first rebuild. |
| OnTick() | Rebuild when a new bar starts or the source signature changes. |
| OnTimer() | Check the same triggers and retry pending data once per second on a chart. In the visual Strategy Tester, the timer runs once per chart period or every 60 seconds, whichever is longer, in simulated time. |
| Manual update | On a chart, click Recalculate history or press R to rebuild immediately. These controls are unavailable in the visual Strategy Tester. |
| OnTester() | Rebuild from closed bars at test completion. Return net weighted pips on success or an invalid result on failure. The forming bar remains excluded, and any END_HISTORY exit uses the last closed bar rather than the final tick. |
| OnDeinit() | Stop the timer and call IndicatorRelease() if a handle exists. In the visual Strategy Tester, the final display is preserved. |
Changing buffer values alone does not change the indicator-list signature, which tracks indicator names and chart windows. After changing parameters without changing the indicator's short name, use the manual update or wait for the next bar.
Advanced settings
Enter these keys in the EA input shown as “Optional key=value pairs separated by semicolons”. The EA declares the field as follows:
input string InpAdvanced=""; // Optional key=value pairs separated by semicolons
| Advanced key | Effect |
|---|---|
| from/to | Inclusive start and exclusive end for entry opening times, given as Unix timestamps in seconds. Zero leaves the corresponding boundary unset. |
| long/short | Enable or disable long or short entries. Each key accepts true, false, 1, or 0. |
| empty/buycode/sellcode | Set the custom empty value and the buy and sell values for directional-code decoding. |
| beoffset | Break-even offset in pips. It must be nonnegative and, when break-even is enabled with multiple targets, smaller than the TP1 distance. Zero sets the revised stop to the entry price without compensating for commission. |
Visual Strategy Tester setup
- Before attaching the EA, save a chart containing only the chosen indicator as ExternalIndicatorBacktest.tpl in MQL5/Profiles/Templates. The tester loads this template to supply the indicator instance.
- Select ExternalIndicatorBacktest, the symbol, timeframe, and test dates. Enable visualization, select a local testing agent, and disable optimization. The EA does not support nonvisual tests or optimization.
- Apply the inputs for the example you want to reproduce. Restart the test after changing the template or the EA inputs.
Read the virtual position statistics on the chart. The Strategy Tester account report records account trades and does not include these virtual positions. See “Display and Update” for how the EA recalculates during and after the test.
Verified backtests
The cases use closed-bar OHLC and the SMA reference exits unless noted. They verify the EA's behavior and provide no evidence of trading performance. Two decimal places reflect calculation precision.
The EURUSD chart snapshots were saved on October 9, 2026, in MetaTrader 5 x64 build 6230 on a MetaQuotes-Demo netting demo account. They contain OHLC prices, recorded bar spreads, and buffer values or chart objects. Times are chart/server timestamps. A complete history download timestamp was not retained.
The visual Strategy Tester cases used a separate portable MetaTrader 5 build 6230 instance, a local agent, and native indicator templates. Open prices only controlled tester progression; virtual exits still use closed-bar OHLC.
The CSV inputs in “File manifest” cover only the three SMA buffer rows. ChartDemo_market.csv supplies OHLC, spreads, and buffers by time. ChartDemo_buffers.csv pairs entry and signal bars. The EA reads chart data.
The other snapshots are outside the attachment's scope. A fresh history download, even from the same broker, can change the results. Rolling windows advance as bars close.
SMA signals: the same signals through two sources
The SMA 10/30 comparison checks whether the two sources supply the same signals before comparing exits. For the object run, replace DemoSignals with ObjectSignals, select “Read time-anchored graphical signals on this chart” and “Case-sensitive object-name prefixes”, and use BUY_ and SELL_ as the direction rules.
In the recorded January 2025 snapshot, 2,098 EURUSD M15 entry bars span 2025.01.02 00:00:00 through 2025.01.31 23:45:00. With an entry delay of one bar, the contextual signal at December 31, 2024, 23:45 maps to the next available entry bar.
Load earlier signal context, then configure ObjectSignals as shown below.
| Input shown in MetaTrader 5 | Value |
|---|---|
| Optional historical start; 0 = no date limit | 2024.12.01 00:00:00 |
| Optional exclusive historical end; 0 = live history | 2025.02.01 00:00:00 |
| Latest closed candles to draw; 0 = all loaded history | 0 |
ObjectSignals includes the start, excludes the end, and draws over all loaded history when the drawing limit is zero. The EA then applies its own entry interval.
To check the other object rules, use generic arrow codes 233/234 with “Draw dated BUY/SELL text instead of generic arrows” set to false. For text matching, set it to true and use BUY/SELL substrings.
Independent decoding matched both sources across all 2,098 entries: 49 buy events, 49 sell events, 2,000 neutral bars, and no conflicts. All three object rules matched the saved buffer signals, and OHLC prices and spreads matched across runs. See “Publication Time and Look-Ahead Bias” for limits on historical signal availability.
The buffer runs vary the target count while holding signals, history, and stop loss fixed. The target share table shows how the same percentage inputs apply.
| Configuration | Signals | Virtual positions | Net weighted pips | Win rate | Exit segments |
|---|---|---|---|---|---|
| SMA buffers, three targets | 98 | 98 | −93.16 | 32.65% | 139 |
| SMA objects by prefix, three targets | 98 | 98 | −93.16 | 32.65% | 139 |
| SMA buffers, one target | 98 | 98 | −93.30 | 32.65% | 98 |
| SMA buffers, two targets | 98 | 98 | −102.80 | 32.65% | 127 |
The three-target runs match on virtual positions and partial exits. Arrow-code objects match the two-target buffer exits, and text objects match the one-target buffer exits. The agreement applies to the saved snapshots and tested settings.
Confirmed RSI divergence objects
Some indicators need later bars to confirm a signal. The included RSI divergence indicator illustrates this case by placing its arrows on the confirmation bar, allowing the EA to assign entries after confirmation.
It uses RSI 14 on Close and strict price pivots with three closed bars on each side; equal neighboring highs or lows reject a pivot. Consecutive pivots of the same type are compared only within 120 bars.
A lower price low with a higher RSI value defines regular bullish divergence; a higher price high with a lower RSI value defines regular bearish divergence. No 30/70 filter or hidden-divergence detection is used. The arrow is anchored to the third closed bar after the second pivot, when confirmation becomes available; shift 1 assigns entry to the following bar.
The chart shows the confirmation arrow, pivot line, exit segment, and backtest panel. RSIDivergenceObjects calculates RSI internally.

Image 4: RSIDivergenceObjects signal and EA backtest panel on EURUSD H1, with a pivot line and a virtual exit segment.
To reproduce this RSI backtest, attach RSIDivergenceObjects and configure its Inputs as shown below:
| Input shown in MetaTrader 5 | Value |
|---|---|
| RSI period applied to closing prices (InpRSIPeriod) | 14 |
| Closed candles required on each side of a pivot (InpPivotStrength) | 3 |
| Maximum distance between consecutive same-side pivots (InpMaxPivotGap) | 120 |
| Latest closed signal candles to draw (InpHistoryBars) | 4000 |
For EURUSD H1 or M15, change the source settings as shown and replace the dates with from=0;to=0. Keep the other SMA reference settings.
| Input shown in MetaTrader 5 | Value |
|---|---|
| Default: use the attached indicator | Read time-anchored graphical signals on this chart |
| How objects identify direction | Case-sensitive object-name prefixes |
| Buy prefix, arrow code, or text substring | BUY_RSID_ |
| Sell prefix, arrow code, or text substring | SELL_RSID_ |
The EA's 3,000-bar entry limit keeps this backtest within the indicator's 4,000-bar signal coverage.
The 3,000-bar windows cover 2026.04.17 16:00:00 to 2026.10.09 15:00:00 on H1 and 2026.08.27 10:30:00 to 2026.10.09 16:15:00 on M15.
| Chart | Signals | Virtual positions | Skipped | Conflicts | Net weighted pips | Win rate |
|---|---|---|---|---|---|---|
| EURUSD H1 | 71 | 59 | 12 | 1 | +182.39 | 62.71% |
| EURUSD M15 | 67 | 46 | 21 | 0 | −142.95 | 54.35% |
H1 has 114 exit segments and M15 has 62. M15 wins 54.35% of completed virtual positions but finishes negative in net weighted pips. The two timeframes cover different intervals, so this is a workflow check.
Standalone backtests in the visual Strategy Tester
Both template runs used EURUSD M15 over January 1–3, 2025, with evaluated entries from 2025.01.02 00:00:00 through 2025.01.02 23:30:00.
| Visual configuration | Bars | Signals | Virtual positions | Net weighted pips | Win rate |
|---|---|---|---|---|---|
| Buffer indicator template | 95 | 4 | 4 | +1.50 | 25.00% |
| Object indicator template | 95 | 4 | 4 | +1.50 | 25.00% |
Both templates produce the same results and six exit segments. With four signals per run, the test confirms access to the two configured signal sources in this setup.
Automatic object-source rebuilds
The refresh check changed matching objects on a chart without advancing the forming bar. Adding a signal increased the count from 98 to 99; adding a duplicate kept 99. An opposite signal on the same bar produced 98 signals and one conflict. Moving the added objects to the forming bar restored 98 signals and no conflicts; removal preserved that result. Every change triggered a rebuild without manual refresh.
Limitations and safeguards
Before comparing backtests, check these five points:
- Verify signal availability. Repainting can change the signal snapshot; see “Publication Time and Look-Ahead Bias”.
- Check that the OHLC execution assumptions suit the comparison. The EA reconstructs Ask from Bid and the recorded bar spread. OHLC cannot establish intrabar price order, even in the visual Strategy Tester.
- Check entry boundaries, bar count, signal coverage, decoding, and indicator warm-up. A successful read does not establish that the history is complete. Missing required data or context invalidates the rebuild and clears the results.
- Interpret weighted pips as virtual position results, separate from account returns. Margin, swap, volume constraints, and slippage require a different model. Check the pip size when testing instruments that do not follow the FX sizing convention.
- Follow “Visual Strategy Tester setup” and confirm that the indicator provides a readable signal source.
Conclusion
Backtesting an indicator’s signals provides a first assessment before committing to a dedicated EA, including when its source code is unavailable. Once signal timing and individual exits have been checked, different exit settings can be compared using the same history, signal snapshot, and costs. The resulting statistics help decide whether the signals deserve further investigation, while their usefulness depends on the available data and the assumptions of the OHLC reconstruction. They do not establish future profitability.
File manifest
| File name | Description |
|---|---|
| MQL5/Experts/ExternalIndicatorBacktest/ExternalIndicatorBacktest.mq5 | EA for closed-bar OHLC backtests on a chart or in the visual Strategy Tester. |
| MQL5/Indicators/ExternalIndicatorBacktest/DemoSignals.mq5 | SMA 10/30 test indicator with buy, sell, and directional-code buffers. |
| MQL5/Indicators/ExternalIndicatorBacktest/ObjectSignals.mq5 | SMA 10/30 crossover indicator with dated arrows or text objects. |
| MQL5/Indicators/ExternalIndicatorBacktest/RSIDivergenceObjects.mq5 | Confirmed regular RSI divergence indicator with dated arrows and pivot lines. |
| MQL5/Files/ExternalIndicatorBacktest/Examples/ChartDemo_market.csv | Saved EURUSD M15 OHLC prices, bar spreads, and SMA buffer values. |
| MQL5/Files/ExternalIndicatorBacktest/Examples/ChartDemo_buffers.csv | Entry-to-signal bar mapping with current and previous SMA buffer values. |
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.