Six Backtest Traps That Produce a Fake Holy Grail (and How to Catch Them in MQL5)
Introduction
Almost every trader who writes Expert Advisors has seen this. The Strategy Tester shows a smooth equity curve, 60 or 70 percent winning trades and a small drawdown. The EA goes to a demo or live account and the curve turns flat or goes down. Then the questions start. Is the idea bad? Is there a bug in the code? Or was the test itself wrong?
Over the last year I tested several hundred trading rules on forex and crypto futures data. Many of them looked excellent at first. When I looked closer, a large part of the "edge" came not from the market but from the way the test was built. The same few mistakes appeared again and again, and each of them can turn a losing rule into a holy grail on paper.
This article describes six of these traps. For each one I show a real example from my own research with the result before and after the fix, explain why it happens, and give a small MQL5 tool that helps you find it in your own EA. All tools are attached at the end of the article. None of them needs special settings: you can run them on your EA in a few minutes.
The six traps are:
- The signal and the fill on the same bar.
- A limit order that is filled on a simple touch.
- Stop loss and take profit inside one bar.
- Indicators that repaint, and pivots that are known only later.
- Data that knows the future.
- A sharp peak in the optimization table.
Trap 1. The signal and the fill on the same bar
What happens. The rule looks at the close of a bar, and the trade is opened at a price inside the same bar, usually at its open. In real trading the close of the bar is known only when the bar is finished, so the earliest possible entry is the open of the next bar. If the entry is placed earlier, the test already knows where the bar will close.
How big the effect is. Take the simplest rule: if an H1 bar closes above EMA(20), buy for one bar. There are no costs in this test, and the only difference between the two lines is the entry bar.

Fig. 1. Trap 1: the same rule, entered one bar apart
On BTCUSDT H1 from 2023 to 2026 the version that enters inside the signal bar makes +2,247 percent. The honest version that enters at the next bar makes +108 percent, which is close to just holding the coin during the up hours. On EURUSD H1 from 2015 to 2026 the picture is the same: +1,022 percent with 61 percent winners against -14.5 percent with 48 percent winners. A filter that "wins" 61 percent of the time is simply reading the answer.
Where it hides in MetaTrader 5. The MT5 Strategy Tester itself does not let an order be filled at a past price. The trap appears in other places:
- in indicators that draw arrows and a "profit statistics" panel on the chart. Very often these statistics count the entry at the open of the signal bar;
- in your own analysis scripts, Excel tables and Python notebooks that you use before writing the EA;
- in EAs that make the decision on the current, unfinished bar (bar 0) on every tick. The signal may appear in the middle of the bar and disappear by its close, so the EA trades signals that never existed on the final chart.
How to catch it. First, run the attached script TrapSameBar.mq5 on your symbol and timeframe. It counts the same signals in both ways and prints the gap. If your own statistics look like the first line and not like the second, check where your entry is.
Second, make the EA decide once per bar, on the closed bar (index 1), and enter at the open of the new bar:
CNewBar g_bar; // from BacktestTraps.mqh
void OnTick()
{
if(!g_bar.IsNew()) // decide only once, when a new bar opens
return;
double atr;
if(Signal(1, atr)) // bar 1 is closed, its values will not change
g_trade.Buy(InpLots, _Symbol, SymbolInfoDouble(_Symbol, SYMBOL_ASK), ...);
} Third, a quick test without reading any code: run the EA in the tester twice, once in "Open prices only" mode and once in "Every tick based on real ticks". An EA that decides on closed bars gives similar results in both modes. A large difference is a sign that the EA reads the unfinished bar.
The attached TrapDemoEA.mq5 has the input InpDecideOnTick. With false it decides on the closed bar, with true it decides on the current bar on every tick. Run both and compare the trade lists.
Trap 2. A limit order filled on a simple touch
What happens. The rule places a buy limit below the market. In the test the order is counted as filled as soon as the low of a bar touches the level. In a real market a touch does not mean a fill: there is a queue of orders at the same price, and the price often touches a level exactly because there were enough buyers to stop it there. The worst version of this trap is a limit that is filled inside the same bar that produced the signal, before the signal was even known.
How big the effect is. I tested a popular idea: after a break of structure, place a limit order at the edge of the fair value gap, stop behind the gap, target 2R. The test used 70 crypto futures from May to October 2026. The first version counted a touch as a fill and allowed the take profit in the same bar as the fill. The second version required the price to pass the level by 0.05 percent and did not count a take profit in the fill bar (more on this in trap 3).

Fig. 2. Traps 2 and 3: limit entry into a fair value gap
The signals are identical, only the fill rules differ. On H1 the result goes from +0.09R per trade (4,339 trades, 45 percent winners) to -0.30R (30 percent winners). On H4 it goes from +0.19R to -0.14R. A rule that looked like a small but stable edge with a t-statistic near 4 is in fact a clear loser.
How to catch it. Require the price to trade through the level, not just touch it. In MQL5 the simplest way is a virtual limit: the EA keeps the level in memory and opens a market order only when the price has passed it by a few points:
//--- from BacktestTraps.mqh
bool HonestLimitTouched(const bool is_buy, const double level, const double pass_points,
const double bid, const double ask)
{
double pass = pass_points * _Point;
if(is_buy)
return(ask <= level - pass);
return(bid >= level + pass);
} The fill price of the market order will be a little better than the level. If you want to stay strict, calculate the stop and the target from the level, as TrapDemoEA does. The level is also set only after the signal bar has closed, so it cannot be filled inside the signal bar.
TrapDemoEA has three entry modes: market order at the next bar, a normal pending buy limit (the tester fills it on a touch) and the virtual limit with a pass. Run the last two on your symbol. If the profit disappears when you add 1 to 3 spreads of pass, the rule lived on the touches.
Trap 3. Stop loss and take profit inside one bar
What happens. The price reaches both the stop loss and the take profit inside one bar. Which one came first? On bar data nobody knows. A simple backtest written in a loop usually checks the take profit first, or checks the bar high before the low, and silently chooses the better outcome. In the MT5 tester the same question is answered by the tick model: in "1 minute OHLC" and "Every tick" modes the ticks inside the bar are generated, not real, so the order of the stop and the target is a guess.
A close relative is the take profit in the fill bar. A limit order is filled at the low of a bar, and the same bar closes high enough to reach the target. On bar data it looks like a perfect trade. In reality the price may have reached the target first and only then fallen to the limit.
How big the effect is. In the fair value gap example above, these two rules together with the pass rule turned +0.09R into -0.30R on H1. In my experience the effect is largest for short stops and short holding times, where a big share of the trades ends in the same bar where it started.
How to catch it. The safe rule is simple: if the stop and the target are both inside one bar, count it as a stop. If you want a precise answer, check these trades on M1 bars or on real ticks.
The attached BacktestTraps.mqh has the class CExitAudit. Add three lines to your EA:
#include <BacktestTraps\BacktestTraps.mqh>
CExitAudit g_audit;
int OnInit() { g_audit.Init(_Symbol, _Period); return(INIT_SUCCEEDED); }
void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result)
{
g_audit.OnTransaction(trans);
}
double OnTester()
{
g_audit.Report("my_ea_exit_audit.csv");
return(TesterStatistics(STAT_PROFIT));
} After the test the journal shows how many trades had the stop and the target inside the exit bar, how many trades were closed in the entry bar and how many of those were closed by the take profit, with their total profit. The list of these trades is saved to Common\Files. If these trades carry a large part of the profit, re-run the test in "Every tick based on real ticks" mode and compare.
Trap 4. Indicators that repaint, and pivots that are known only later
What happens. Some indicators change their past values. ZigZag is the best known example: the last leg moves while the price moves, and a top is confirmed only after the price has gone down far enough. Fractals need two bars on the right side. Indicators based on centered averages or smoothing "both ways" also look at bars that are still in the future.
On the chart all of this looks perfect, because the chart shows the final picture. An EA does not live in the final picture. It sees only what was known on the bar that just closed.
There is a less obvious form of the same trap. In my research I found swing highs and lows with a fractal rule and then "cleaned" the list: if two highs came one after another without a low between them, I kept only the higher one. This looks harmless, but at the moment of the first high nobody knows that a higher one will come. The cleaned list uses the future, and rules built on it looked better than they were. The fix was to use raw confirmed fractals, each with its confirmation delay, and never merge them afterwards.
How to catch it. Log what the indicator showed on each bar at the moment the bar closed and compare it with the final chart. The attached RepaintCheckEA.mq5 does this for any indicator and buffer. Run it in the tester (visual mode is not needed). At the end it prints:
- how many non-empty values are on the final chart;
- how many of them were already visible when their bar closed;
- how many appeared later, and the average delay in bars;
- how many values were shown at some moment and removed later;
- how many values changed after the bar closed.
For a ZigZag most of the pivots will appear later, and some will be removed. That is normal for this indicator. The rule for the EA is: use a value only from the moment it became visible, and test the rule on the logged values, not on the chart.
Trap 5. Data that knows the future
What happens. The list of symbols or the history itself is built with knowledge of the future. Typical cases:
- the test runs on symbols that are popular today. Symbols that were delisted, merged or forgotten are not in the list, but a real trader in the past would have traded them;
- the history of a symbol starts only shortly before it became popular, because the data was downloaded for "the symbols we care about";
- the portfolio is chosen by today's ranking, for example the top 20 by volume now, and tested over the last five years.
How big the effect is. This one cost me the most time. For several weeks I searched for rules on an hourly data set that contained only the crypto futures that had at some point been in the top 25 by volume, and the history of each started 40 days before it first entered the top. Without noticing it, every rule was trading coins that were about to become popular.
When I rebuilt the data with all contracts, including delisted ones, and took the universe from yesterday's volume ranking only, one of the best rules, a long on volatility expansion, lost most of its edge. On the "future stars" it made +0.9 to +1.7 percent per trade. On all other coins it made -0.2 to -1.6 percent. On the honest universe in 2026 its result was about -0.06 percent per trade, which is zero after costs.
How to catch it. There is no single script for this trap, but there is a checklist:
- build the list of symbols for each day from data known on the previous day;
- keep delisted symbols in the data. If your broker does not have them, at least be aware that the result is too optimistic;
- check where the history of each symbol starts and why;
- a strong warning sign: the rule works much better on the symbols that are popular today than on the others.
Trap 6. A sharp peak in the optimization table
What happens. The optimizer tries thousands of parameter sets and some of them will look excellent just by luck. If you take the best line of the table, you mostly take the best luck. The more combinations you try, the higher the lucky peak and the bigger the disappointment later.
How big the effect is. I optimized long entries after a change of character on 10 crypto futures on M5: 4,050 parameter sets (zigzag size, entry type including Fibonacci 0.5 and 0.618, stop, target and holding time). The parameters were chosen on April to July 2026, checked on August and September, and then followed on live data in October and November.

Fig. 3. Trap 6: the best optimization result does not carry forward
The top 15 sets made +0.21R per trade on the optimization period, +0.07R on the check period and -0.90R on live data. The control, an entry on a random bar with the same exits, made -0.32R on live data, so the "best" sets were much worse than random. Not one of the 4,050 sets was positive in all three periods. The rank correlation between the optimization result and the live result was +0.01, that is, none.
How to catch it. Three tests help.
Neighbours. A real effect usually gives a plateau: if the best value of a parameter is 20, then 18 and 22 are also good. A lucky result is a lonely peak with weak neighbours. The attached script PlateauCheck.mq5 reads the optimization table (save it from the tester to Excel, keep the columns Result, Param1, Param2 and save as CSV into MQL5\Files). For each of the best sets it prints the average of its grid neighbours and marks it as a PEAK or a plateau. This is how the output looks (the numbers here only show the format):
PlateauCheck: 400 sets, grid 20 x 20 #1 p1=17 p2=2.5 result 1840.00 neighbours 310.00 (8) PEAK #2 p1=24 p2=1.5 result 1620.00 neighbours 1290.00 (8) plateau ... best neighbourhood: p1=24 p2=1.5, own result 1620.00, neighbours 1290.00
In such a table choose the second line, not the first, and expect less than the table shows.
A control test. Remove the key condition of the rule and run the test again. If the result stays almost the same, the condition is not what makes the money. In my tests a large part of "smart" filters gave the same result as an entry on a random bar.
A period held back. Do not use the last year in the optimization at all. Choose the parameters on the earlier years and run the chosen set on the last year once. If you have to go back and adjust after looking at the last year, it is no longer a clean test.
A short checklist before you trust a backtest
- The decision is made on a closed bar, the entry is at the next bar or later.
- "Open prices only" and "Every tick based on real ticks" give similar results.
- Limit orders need the price to pass the level, not touch it, and they are never filled in the signal bar.
- Trades with the stop and the target inside one bar are counted as stops or checked on real ticks; a take profit in the fill bar is not counted on bar data.
- Indicator values are used only from the moment they became visible; the rule is tested on logged values.
- The list of symbols is built from data known at that time, delisted symbols are included.
- The chosen parameters sit on a plateau, the rule is better than a control without its key condition, and it works on a period that was not used in the optimization.
- Costs are included: spread, commission, slippage and swaps.
If a rule passes all eight points, it is not guaranteed to make money, but at least the result is about the market and not about the test.
Conclusion
All six traps have the same root: the test knows something that a trader at that moment could not know. It may be the close of the bar, the order of prices inside the bar, the future shape of an indicator, the future popularity of a symbol or the future result of thousands of parameter sets. The attached tools do not make a strategy profitable. They help you see which part of the backtest result is real before you put money on it.
Attached files
| File | Type | Description |
|---|---|---|
| BacktestTraps.mqh | Include | CNewBar (decide once per closed bar), HonestLimitTouched (limit with a pass), CExitAudit (stop and target in one bar, exits in the entry bar). Put it into MQL5\Include\BacktestTraps\ |
| TrapDemoEA.mq5 | Expert Advisor | One simple rule with switchable decision and entry handling: closed bar or every tick, market, limit on touch or limit with a pass. Prints the exit audit after the test |
| TrapSameBar.mq5 | Script | Trap 1 on your symbol: the same signals counted with the entry inside the signal bar and at the next bar |
| RepaintCheckEA.mq5 | Expert Advisor | Trap 4: logs any indicator buffer bar by bar in the tester and compares it with the final chart |
| PlateauCheck.mq5 | Script | Trap 6: reads an optimization table from CSV and marks lonely peaks and plateaus |


