Backtest vs Live Results: How to Diagnose the Gap Step by Step

When live results differ from the backtest, do not start by changing inputs. First re-run the backtest over exactly the live period, with the same inputs, broker server and costs, and pair each live trade with its counterpart in that test. The pairing splits the gap into causes: trades that exist in both runs but at different prices point to execution and costs; trades that exist in only one run point to data, time zone handling or code that only runs live. Only when these are ruled out does a change in market regime become the likely explanation. This guide works through the steps with MetaTrader 5 as the example and names a metric for each, as of November 2026.

Step 1: re-run the backtest and pair the trades

A fair comparison needs a backtest that differs from the live run only where market access differs. Collect the live account history with every deal, the EA’s logs, the exact EA version and its set file. Then re-run the test over exactly the live period, on the same broker server, in “Every tick based on real ticks”, with the live deposit, leverage and commission settings and a fixed delay close to your measured ping. The tester keeps price history separately for each trade server, so a test on another broker’s data is a different test.

Then pair the trades: same symbol, same direction, entry within a tolerance such as one bar. Three groups result: matched pairs, live-only trades and backtest-only trades. Each later step has its own metric:

StepMetricPoints to
PairingMatch rate, entry time offsetLow match rate: data, time zone, code paths
ExecutionSlippage per entry and exit in points, fill ratio, rejection rate, latencyFills, spread, connection
DataBars that differ between live chart and tester, hour-sized time offsetsFeed, server, time zone
Code pathsRestarts and deals not opened by the EA near unmatched tradesBehavior that only exists live
CostsCommission, swap and fee per tradeCost settings of the test
RegimePosition of the live result among resampled backtest resultsNoise or a changed market

Typical example: over three months, the live EA made 120 trades and the re-run backtest 128; 110 pairs match. Live is 2,400 behind the test. Worse prices on matched pairs, mostly at stop exits, explain 1,300; higher commission and swap explain 400; the 10 live-only and 18 backtest-only trades explain the remaining 700. The next steps are execution and the unmatched trades, not new inputs.

A minimal pairing script, tested with Python 3.9 on sample data. Export both trade lists to CSV first:

# Pair live trades with backtest trades and split the gap (Python 3.9+, standard library only).
# CSV columns: time (YYYY-MM-DD HH:MM:SS, server time), symbol, side (buy or sell),
# entry (price), profit (net of commission and swap)
import csv, sys
from datetime import datetime, timedelta

def load(path):
    with open(path, newline="") as f:
        rows = list(csv.DictReader(f))
    for r in rows:
        r["time"] = datetime.strptime(r["time"], "%Y-%m-%d %H:%M:%S")
        r["entry"], r["profit"] = float(r["entry"]), float(r["profit"])
    return sorted(rows, key=lambda r: r["time"])

def pair(live, test, tolerance):
    free, pairs, live_only = list(test), [], []
    for lt in live:
        near = [bt for bt in free if bt["symbol"] == lt["symbol"] and bt["side"] == lt["side"]
                and abs(bt["time"] - lt["time"]) <= tolerance]
        if not near:
            live_only.append(lt)
            continue
        bt = min(near, key=lambda b: abs(b["time"] - lt["time"]))
        free.remove(bt)
        pairs.append((lt, bt))
    return pairs, live_only, free

if __name__ == "__main__":
    live, test = load(sys.argv[1]), load(sys.argv[2])
    point = float(sys.argv[3])            # e.g. 0.00001 for a 5-digit FX symbol
    pairs, live_only, test_only = pair(live, test, timedelta(minutes=15))
    sign = {"buy": 1, "sell": -1}
    slip = [sign[lt["side"]] * (lt["entry"] - bt["entry"]) / point for lt, bt in pairs]
    gap = sum(r["profit"] for r in live) - sum(r["profit"] for r in test)
    matched = sum(lt["profit"] - bt["profit"] for lt, bt in pairs)
    print(f"match rate live {len(pairs)}/{len(live)}, test {len(pairs)}/{len(test)}")
    if slip:
        print(f"entry slippage in points: mean {sum(slip) / len(slip):.1f}, worst {max(slip):.1f}")
    print(f"gap {gap:.2f} = matched pairs {matched:.2f} + unmatched {gap - matched:.2f}")

It pairs each live trade with the nearest free backtest trade within 15 minutes, reports the match rate and the entry slippage of matched trades in points, and splits the gap into matched pairs and unmatched trades. Positive slippage means a worse price than in the test.

Step 2: check execution (slippage, spread, partial fills)

For matched pairs, measure slippage per trade as the difference between the live fill price and the backtest price in points, signed so that a positive value means worse for you. Evaluate entries, Stop Loss exits, Take Profit exits and signal exits separately; the deal reason in the account history (DEAL_REASON_SL, DEAL_REASON_TP, DEAL_REASON_EXPERT) tells them apart. Look at the worst cases as well as the average.

  • Tester assumptions. “No Delay” executes all orders at the requested prices, and the other delay modes only delay requests the EA sends, not the execution of pending orders. According to the help page on testing features, in “1 minute OHLC” and “Open prices only”, pending orders, Stop Loss and Take Profit are executed at the prices specified in the orders; the help page on tick generation and the MQL5 reference say that in “Open prices only” they may trigger at a different price. Check which applies in your own terminal; either way, a reference test with these settings did not model the stop slippage seen live.
  • Spread. With real ticks, the spread can change within a minute bar; with generated ticks, the tester uses the spread fixed in each minute bar. Log bid and ask at every live signal to compare.
  • Partial fills. With Immediate or Cancel, the available volume is executed and the rest is canceled; with Return, the rest stays in the market as an order, which Market Execution does not allow. Return code 10010 means only part of the request was completed. Compare filled with requested volume.
  • Requotes and rejections. Codes 10004 (requote), 10020 (prices changed) and 10021 (no quotes) show how often requests failed. In Request and Instant Execution, the request includes a maximum price deviation; for Market Execution, the MQL5 reference lists neither price nor deviation among the required fields.
  • Latency. Compare the signal time in your log with the deal time in milliseconds (DEAL_TIME_MSC).

Metrics: average and worst slippage by exit type, fill ratio, rejection rate and latency. Failed requests themselves are covered in the MT5 diagnostic checklist.

Step 3: check the data (feed, time zone, bar building)

If many trades exist in only one of the two runs, compare the inputs to the signal before the code. Three causes are common:

  • Feed and server. Brokers deliver different prices, and the tester stores history per server. A backtest on one broker’s data and live trading on another’s produce different bars and therefore different signals. Even on the same server, the tester discards real ticks that contradict the minute bars and uses generated ticks instead, as it does for minute bars without tick data.
  • Time zone. The tester deliberately makes local time, server time and GMT identical: TimeLocal(), TimeTradeServer() and TimeGMT() return the same value. Live, they differ. Code that derives an offset from them, or filters sessions with TimeGMT() or TimeLocal(), behaves differently in the two runs. The typical trace is a set of live-only and backtest-only trades that would pair up if shifted by exactly one or more hours, often around daylight saving changes; re-run the pairing with the times shifted to check.
  • Bar building. A new minute bar opens with its first tick, not at the full minute. An EA that acts at the open of a new bar acts on that first price, which depends on the feed. Compare the bars around unmatched trades on the live chart with the tester’s bars for the same period.

Metrics: the share of unmatched trades, the number of them that pair up after an hour shift, and the distribution of entry time offsets among the matched ones.

Step 4: code paths that only run live

Some code only runs live, and some runs differently in the tester. Search the source for these points and read the live logs around unmatched trades:

  • Branches that check MQLInfoInteger() for tester, optimization or visual mode.
  • Functions that are not executed in the tester: Alert(), MessageBox(), PlaySound(), SendFTP(), SendMail(), SendNotification() and WebRequest(). If a trade decision waits for a web request, the test never took that path.
  • Sleep() does not pause the test; the simulated time moves forward by the interval instead, and pending orders or stops can trigger in between.
  • Files and global variables: in the tester, file operations run in the testing agent’s own folder and the terminal’s global variables are emulated, so state the EA stores there live is absent in the test.
  • Restarts: a terminal or server restart starts the EA again with whatever state it can recover. The tester runs it once from start to end.
  • Deals the EA did not make: the deal reason shows whether a deal came from an MQL5 program (DEAL_REASON_EXPERT), from the desktop, mobile or web platform, or from a stop out (DEAL_REASON_SO).

Metrics: restarts and re-initializations in the Experts log within a few bars of an unmatched trade, and the number of deals not opened by the EA.

Step 5: compare costs (commission, swap, fees)

Compare the costs per trade in the live account history with those in the test. Each deal carries commission (DEAL_COMMISSION), swap (DEAL_SWAP, cumulative on close) and a fee charged right after the deal (DEAL_FEE). In the tester, check which commission settings were active: it can use the account’s predefined commissions or custom ones, and profit calculation in pips removes swap and commission altogether. Also check swaps on positions held over the daily rollover, and the conversion of profits if the deposit currency differs from the symbol’s profit currency.

Metrics: cost per trade and cost as a share of gross profit, live against test. If costs alone close most of the gap, the edge was smaller than the test suggested, and the next decision concerns account conditions rather than code.

Step 6: regime, the last explanation

Only when execution, data, code paths and costs explain little is a change in the market the likely cause. Even then, first check whether the gap is unusual at all. Compare trade frequency, share of profit trades, average win, average loss and holding time between live and test. Then draw many random samples from the backtest trades, each as large as the live sample, and see where the live result falls in their distribution.

Typical example: 60 live trades lost 900. Among 10,000 random samples of 60 backtest trades, about one in eight ends with a loss of that size or worse. That is uncomfortable but within the range the backtest itself implies; a result beyond the worst 1 percent would be a stronger sign that the market or the strategy has changed. Decide in advance which threshold leads to which action, so that the latest losses do not drive the decision.

Limits and risks of the diagnosis

  • With a few dozen live trades, a changed market and an ordinary losing streak look alike, even though a single paired trade can already reveal an execution or code problem.
  • The re-run is a model too: tick history, spread and delay in the tester remain approximations of live conditions.
  • Fixing the measured causes makes backtest and live comparable; it does not improve the strategy. Re-optimizing on the latest live data adds fitting risk.
  • Automated trading with leverage can lose money fast; depending on product and broker, losses can exceed the deposit. Past results, simulated or real, are not a reliable indicator of future results.

Next steps: the diagnosis in order

  1. Secure the evidence: account history with all deals, the Experts and Journal logs, the EA version and the set file.
  2. Re-run the backtest for the live period on the live server, with real ticks, the measured delay and the live costs.
  3. Pair the trades and compute match rate, slippage, fill ratio and cost per trade.
  4. Work through execution, data, code paths and costs in that order, and fix one cause at a time.
  5. Only then compare the live result with resampled backtest results.
  6. Write down which result will make you reduce size or stop the EA.

If you want the comparison done independently, the system audit in the trading system code review covers backtest methodology and the comparison with live results. How to read the report you start from is explained in how to read an MT5 Strategy Tester report.

Frequently asked questions

Why is an EA profitable in the backtest but losing money live?

Check the causes in this order: test settings that were too optimistic, such as a rough tick generation mode, no delay or missing costs; execution, meaning slippage, spread and partial fills; different data or time zone handling; code paths that only run live; and costs. A change in the market comes last. Pairing live trades with a re-run backtest over the same period shows which cause applies.

How do you measure slippage in MetaTrader 5?

Log bid, ask and the intended price when the EA decides to trade, then read the fill price of the resulting deal (DEAL_PRICE) and its time in milliseconds (DEAL_TIME_MSC). Slippage is the difference in points, signed so that a positive value means worse for you. Evaluate entries, Stop Loss exits and Take Profit exits separately, and look at the worst cases as well as the average.

Does the MT5 Strategy Tester simulate slippage?

Partly. With Random Delay or Fixed Delay, the tester inserts a delay between the EA’s request and its execution, so the price can change in between; pending orders are executed without delay, and No Delay executes all orders at the requested price. For 1 minute OHLC and Open prices only, MetaQuotes’ help pages and the MQL5 reference contradict each other on whether stops fill at their specified prices, so check it in your own terminal. None of these settings models the stop slippage seen live.

How many live trades are needed before comparing with the backtest?

For execution and code problems, a single paired trade can be enough: a fill far from the test price or a trade without a counterpart has a cause you can trace. To judge whether the strategy still works, you need far more, because with a few dozen trades a normal losing streak and a changed market look alike. Set the sample size and thresholds before you start.

Should you re-optimize when live results lag the backtest?

Not as a first step. Re-optimizing on recent data without knowing the cause fits the inputs to the latest noise and can hide execution, data or code problems that will persist. Fix the measurable causes first, then decide by rules set in advance whether the remaining gap justifies a change, a smaller position size or stopping the EA.

Sources and status

As of November 2026. Third-party rules, prices and APIs may have changed since; the providers' current documentation and the official texts are authoritative.

This article is also available in German: Live weicht vom Backtest ab: Ursachen schrittweise finden.

Live results drifting away from your backtest? Get in touch — a free intro call clarifies which logs, settings and trade lists are needed to trace the gap to its cause. More: Trading system code review and audit.