Look-Ahead Bias and Other Code Bugs That Make EA Backtests Lie

Most discussions of unreliable backtests focus on overfitting: rules tuned so closely to the past that they capture noise. That is a real problem, with its own warning signs, and tests such as walk-forward analysis are designed to expose it.

There is a second problem that gets less attention and does more damage. Sometimes a backtest is not overfit at all. It is simply wrong, because the code uses information that would not have been available at the moment the trade was taken. That is look-ahead bias, and a strategy that benefits from it can pass a walk-forward test, survive a Monte Carlo simulation and still fail the moment it trades in real time.

This guide covers the most common ways future information leaks into Expert Advisor (EA) and Python backtests, how to recognise the symptoms, and a simple test that detects many leaks directly.

One point up front: robustness tests cannot detect look-ahead bias. Walk-forward, Monte Carlo and parameter sensitivity tests all run on the backtest's trades. If those trades were produced with information from the future, every test inherits the same flaw. Leaks have to be found in the code and the data, before any robustness testing begins.

What look-ahead bias is

Look-ahead bias happens when a backtest makes a decision at time T using information that only became known after T. In live trading this is impossible, so the backtest is describing a strategy nobody can actually run.

The leak is rarely obvious. It is usually one index off by one, one resampling setting left at its default, or one indicator that redraws its past values. The code looks reasonable. The results look excellent. That combination is exactly why it survives.

Common leaks in MQL5 EAs

Reading the current, unfinished bar

In MQL5, bar index 0 is the bar that is still forming. Its close is the latest price, and its high and low are still changing. Code that calculates a signal from bar 0 and treats it as a completed bar can behave very differently in the tester and live, especially in faster modelling modes where the tester sees less of the price path inside each bar.

A safer default for rule-based strategies is to calculate signals from bar 1, the last completed bar, and to run that calculation once per new bar.

Using today's high or low too early

A rule such as "buy if price closes above yesterday's high, with a stop at today's low" sounds clean. But today's low is not known until today ends. If the code reads the daily bar's low during the day and uses it as a stop, the backtest is placing stops with knowledge of where the day will bottom.

The same applies to any value from a higher timeframe bar that is still forming: today's range, this week's high, this hour's close.

Repainting indicators

Some indicators change their past values as new data arrives. Classic examples are swing-point indicators such as ZigZag and fractals, which can only confirm a turning point after later bars have printed, and any centred moving average or smoothing that uses bars on both sides of a point. On a historical chart they appear to mark turning points perfectly. In real time, the marks appear later, move, or disappear.

An EA that reads a repainting indicator's historical values will see confirmed signals at bars where, in real time, nothing was yet confirmed. Before using any custom indicator, find out whether it repaints. If you don't have the source code, the truncation test below will tell you.

Pending orders at prices the strategy couldn't know

Watch for entries or exits placed at a bar's exact high or low when that bar's extremes were unknown at the time the order was placed. A stop placed at "the lowest low of the last ten bars" is fine if it excludes the current bar. If it includes the current bar, it is quietly moving the stop with information from the future.

Common leaks in Python backtests

Filling on the signal bar's close

A vectorized backtest calculates a signal from a bar's close and then applies a return that starts at that same close. In reality, the earliest you can act is after the bar closes, at the next available price. The fix is a one-bar shift between signal and position:

position = signal.shift(1)          # act on the bar after the signal
returns = position * bars["close"].pct_change()

Without the shift, the strategy earns the move of the very bar that produced the signal.

Negative shifts and centred windows

shift(-1) reads the next row. It belongs in code that builds labels for analysis, never in code that builds signals. Similarly, rolling(..., center=True) uses data from both sides of each point and should never feed a trading signal.

Resampling labels

When you resample one-minute or hourly data into daily or four-hour bars with pandas, the default labels can place a bar's timestamp at its start. If you then join that bar back onto intraday data by timestamp, every intraday row from the start of the day can see that day's final high, low and close. Be explicit about label and closed, and always lag higher-timeframe values before joining them to lower-timeframe data.

Joining a higher timeframe correctly

A daily value is known only after the day closes. Shift it by one daily bar, then carry it forward onto the intraday data:

daily = intraday.resample("1D").agg(
    {"open": "first", "high": "max", "low": "min", "close": "last"}
).dropna()

# yesterday's completed daily values, available from the start of today
daily_known = daily.shift(1)
intraday = intraday.join(
    daily_known.add_prefix("d_").reindex(intraday.index, method="ffill")
)

Note that resample("1D") uses midnight in whatever time zone the index is in. If the data is in UTC and your broker's day starts at a different hour, align the time zone first, or the "day" boundaries will not match the ones your EA sees.

Normalising with the whole dataset

Scaling a feature by its full-history mean and standard deviation, or fitting a model on all the data before splitting it, lets future statistics shape past signals. Calculate any scaling with rolling or expanding windows that only use past values, and fit anything trained strictly on in-sample data.

Using data that was revised later

Some data series are corrected after their first release, and historical files often contain only the corrected version. If your strategy uses this kind of data, the backtest sees numbers that were not available at the time. For price data this matters less, but it is worth knowing if you add economic or sentiment inputs.

Symptoms that suggest a leak

None of these proves a leak on its own, but each deserves a closer look:

  • Results far better than the logic would justify. A simple moving average strategy with a very high win rate is more likely to contain a bug than a discovery.
  • Entries clustered at bar extremes. Buying repeatedly at or near the exact low of a bar suggests the code knew where the low was.
  • Performance that collapses in a slower or faster modelling mode. A strategy whose results depend heavily on how ticks inside a bar are modelled may be reading the current bar.
  • A large gap between backtest and demo results from the very first trades. Execution costs widen the gap gradually; a leak breaks it immediately.
  • Signals that change when you re-run the test with more recent data added. Past signals should never change because of later data.

The truncation test

The most direct way to detect a leak is to check that a value calculated at time T does not change when you remove all data after T. If it changes, the calculation is using future data.

import numpy as np

def truncation_test(compute, data, checkpoints):
    """compute(data) -> Series indexed like data. Returns checkpoints where values changed."""
    full = compute(data)
    leaks = []
    for t in checkpoints:
        partial = compute(data.loc[:t])
        if not np.isclose(partial.iloc[-1], full.loc[t], equal_nan=True):
            leaks.append((t, partial.iloc[-1], full.loc[t]))
    return leaks

Run it on every indicator and on the final signal series, at a few dozen checkpoints spread across the history. Any mismatch is a leak, with one exception: values that depend on a long warm-up, such as an exponential moving average, can differ slightly when the truncated series is very short. Use checkpoints well past the start of the data to avoid false alarms.

The same idea works in MT5. Run the EA in the visual tester, pause at a bar, and note the indicator values and any signal. Then let the test continue and look back at that bar. If the indicator line or a signal arrow has moved, the indicator repaints.

Other code bugs that inflate backtests

Look-ahead bias is the most damaging bug, but not the only one. These also make results look better than reality:

  1. Pip and point confusion. A stop intended as twenty pips but coded in points can be ten times tighter or wider than intended.
  2. Ignoring the spread on exits. Closing a long at the bid and a short at the ask matters; using one price for both flatters every short.
  3. Positions that never close. A bug that leaves losing trades open past the end of the test removes their loss from the closed-trade statistics.
  4. Double counting. Two positions opened on one signal, both counted, inflate both profit and trade count.
  5. Compounding errors. Position sizes calculated from equity that includes open, unrealised profit can make a sequence of wins look much stronger than fixed-risk sizing would.
  6. Excluding inconvenient periods. Dropping data around a crisis "because it was abnormal" is a choice that should be written down and justified, not made silently.

A short leak-detection checklist

  • Signals calculated from completed bars only, and acted on at the next available price
  • No reads of a still-forming higher-timeframe bar's high, low or close
  • Every custom indicator checked for repainting
  • No negative shifts or centred windows in signal code
  • Higher-timeframe values lagged one bar before joining, with time zones aligned
  • Scaling and model fitting use only past or in-sample data
  • Truncation test run on every indicator and on the final signal series
  • Trade list spot-checked for entries clustered at bar extremes
  • Pip and point sizes, spread on exits and position closing verified in the code

Frequently asked questions

What is look-ahead bias in a trading backtest?

It is when a backtest uses information that would not have been available at the time of the trade, such as a bar's final close before the bar has finished, or a higher-timeframe value before that timeframe's bar has closed. It makes results look better than any real-time version of the strategy could achieve.

How is look-ahead bias different from overfitting?

Overfitting means the rules fit past noise too closely; the backtest is honest about the past but unlikely to repeat. Look-ahead bias means the backtest itself is wrong, because it used future information. Overfitting is detected with out-of-sample and walk-forward testing. Look-ahead bias is detected by checking the code and data.

How do I know if an indicator repaints?

Watch it in the visual tester or on a live chart and see whether past values change as new bars arrive. In Python, run the truncation test: calculate the indicator on data cut off at a past time and compare its last value with the value at the same time from the full calculation.

Can the MT5 Strategy Tester have look-ahead bias?

The tester only feeds data up to the current simulated time, so it cannot show your EA the future directly. But an EA can still behave in ways it cannot reproduce live, for example by reading the current unfinished bar in a mode that models it crudely, or by using a repainting indicator whose historical values were recalculated with later data.

If my backtest passes all robustness tests, can it still have look-ahead bias?

Yes. Robustness tests work with the trades the backtest produced. If those trades depended on future information, the tests inherit the problem. Leak checks need to come first.

Want a second pair of eyes?

Start with our free Sample Stress-Test Report. It walks one anonymized, illustrative strategy through a full stress test, start to finish, so you can see what rigorous validation looks like before you test your own.

Read the Sample Stress-Test Report

Want your own backtest checked? The Strategy Audit + 60-minute call is a paid service at a launch price of £100, credited in full against our build and portfolio offers. You send an MT4/MT5 Strategy Tester report or trade-list CSV; what we can check depends on the files you supply, and walk-forward and parameter sweeps are not included because they need the strategy itself. It is analysis of strategy testing, not investment advice, and does not promise any trading or evaluation outcome. See the Strategy Audit

Disclaimers

CollosoTrading provides educational content and analytical services for retail and professional algorithmic traders. We do not provide regulated investment advice, financial advice, or personal recommendations. Trading derivatives, leveraged products, and CFDs carries a high level of risk and may result in losses exceeding deposits. Past performance, including any verified or unverified historical results referenced on this site, is not indicative of future results. Consult an independent regulated financial adviser before making investment decisions.

All figures are backtests or simulations unless marked LIVE. Hypothetical or backtested performance results have inherent limitations and may not reflect actual trading. No representation is made that any account will or is likely to achieve profits or losses similar to those shown. Individual results vary. This article contains no performance figures from any strategy or account. We do not guarantee the outcome of any prop firm challenge.