Python vs MT5 Backtesting: Why the Same Strategy Gives Different Results

Many systematic traders research in Python and trade in MetaTrader 5. Python is fast to iterate in and has excellent data tools. MT5 is where the Expert Advisor (EA) actually runs. Sooner or later, almost everyone who uses both runs the same strategy in each and gets two different answers.

The trade counts differ. The entry prices differ. Sometimes one version looks clearly better than the other. The natural question is: which one is accurate?

The honest answer is that neither is accurate by default. Each backtest is a model built on assumptions, and the two tools make different assumptions unless you deliberately align them. This guide lists the usual causes of a Python vs MT5 backtest mismatch, explains which assumptions are closer to real execution, and shows how to reconcile the two trade by trade.

One point up front: a mismatch between Python and MT5 is useful information, not just a nuisance. It almost always points to an assumption that one of the two backtests is making without telling you. Finding it makes both tests more trustworthy. Matching results still do not predict live performance.

Why the two backtests disagree

1. When the order is filled

This is the most common cause, and the most important.

A typical vectorized Python backtest calculates a signal from a bar's close and then applies that bar's return, or the next bar's return measured from the same close. In effect it assumes you traded at the exact closing price of the bar that produced the signal. In real trading you cannot: by the time the bar has closed and your EA has calculated the signal, the next price is the first tick of the next bar.

MT5 handles this naturally. An EA that checks for a new bar and then sends an order is filled at the current price on the new bar, not at the old bar's close.

On daily bars the difference per trade may be small, though weekend and overnight gaps can make it large. On intraday bars, especially for strategies that trade breakouts or momentum, filling at the signal bar's close is often a quiet form of look-ahead bias, and it can flatter results substantially.

2. Bid, ask and spread

MT5 charts and bar data are built from bid prices. Buys fill at the ask, which is bid plus spread. Many Python backtests use a single price series, often a mid price or the bid, for both buys and sells, and ignore the spread entirely or subtract a fixed cost.

Stop-losses and take-profits are affected too. In MT5, a long position's stop-loss triggers when the bid reaches it, and a short position's stop-loss triggers when the ask reaches it. A short's stop can therefore trigger even though the bid-based chart never touched the stop level, because the spread widened. A Python test using only bid highs and lows will miss those exits.

3. Server time and bar boundaries

MT5 bars are timestamped in the broker's server time, which for many brokers is a few hours ahead of UTC and shifts with daylight saving. Data downloaded elsewhere for Python is often in UTC. That changes where daily and four-hour bars begin and end, so the highs, lows and closes are genuinely different numbers. Some data sources also produce a short Sunday bar that a broker's feed does not, adding one extra daily bar a week.

If your strategy uses daily highs, lows or closes, a time zone difference alone is enough to change signals.

4. Indicator calculation details

Two correct implementations of the "same" indicator can disagree:

  • Seeding. An exponential moving average needs a starting value. MT5's built-in EMA and a pandas ewm calculation can start differently, and the early values differ until enough history has passed.
  • Smoothing method. ATR and RSI traditionally use Wilder's smoothing. Some libraries use a simple moving average instead, which gives different values.
  • Warm-up history. MT5 calculates indicators using all the history it has loaded, including bars before the test start. A Python test that starts calculating exactly at the test start date has less warm-up history.

5. Intrabar ambiguity

When a bar's range touches both the stop-loss and the take-profit, a bar-based backtest cannot know which was hit first. Python backtests often resolve this with a fixed rule, sometimes the optimistic one. MT5 resolves it using tick data, real or generated, depending on the modelling mode. On strategies with tight stops and targets, this alone can change many trade outcomes.

6. Costs and position sizing

Commission, swap, volume rounding and compounding all differ unless configured identically. MT5 rounds every volume to the broker's volume step, rejects trades that break minimum stop distances and charges swap at rollover. A Python test that trades fractional sizes and ignores swap is testing a slightly different strategy.

7. Data source

Even after aligning time zones, two data sources are not identical. Different liquidity providers produce different ticks, and small differences in highs and lows can change whether a breakout or a stop is triggered.

Which one is "more accurate"?

It depends on what you want to measure.

AssumptionTypical vectorized Python testMT5 tester, real ticks
Fill timingOften the signal bar's close, unless coded otherwiseNext available tick after the signal
SpreadOften ignored or fixedBroker's recorded spread
Stop triggersUsually bar high or low, one price seriesBid or ask, tick by tick
Bar boundariesDepends on the data source's time zoneBroker server time
Volume rulesOften fractionalBroker's volume step and limits
Speed and flexibilityVery fast, easy to run thousands of variationsSlower, tied to one platform

For estimating how an EA would have executed on a specific broker, a carefully configured MT5 test with real tick data is usually closer to reality. For research, such as comparing ideas, running robustness tests like a Monte Carlo test on an exported trade list, and analysing results, Python is usually more flexible. The goal is not to pick a winner. It is to make the two agree closely enough that you trust your Python research to describe the strategy you will actually run.

How to reconcile Python and MT5 trade by trade

Step 1: Use the same data

The simplest way to remove data and time zone differences is to take the bar data for Python from the same MT5 terminal and broker. The official MetaTrader5 Python package can read it directly:

from datetime import datetime
import MetaTrader5 as mt5
import pandas as pd

if not mt5.initialize():
    raise RuntimeError(f"MT5 initialize failed: {mt5.last_error()}")

rates = mt5.copy_rates_range(
    "EURUSD", mt5.TIMEFRAME_H1, datetime(2020, 1, 1), datetime(2025, 1, 1)
)
mt5.shutdown()

bars = pd.DataFrame(rates)
bars["time"] = pd.to_datetime(bars["time"], unit="s")  # broker server time
bars = bars.set_index("time")
# columns: open, high, low, close, tick_volume, spread (in points), real_volume

The spread column records a spread value for each bar in points. It is a useful approximation for adding ask prices to a Python test, though it is not the same as tick-level spread.

Step 2: Align the fill rule

Make the Python test fill where MT5 would: at the open of the bar after the signal, with the spread applied to buys.

def next_bar_fills(bars, signal, point):
    """signal: +1 long, -1 short, 0 flat, calculated on each completed bar."""
    entry_signal = signal.shift(1)              # act on the next bar
    ask_open = bars["open"] + bars["spread"] * point
    fill = ask_open.where(entry_signal > 0, bars["open"])
    return entry_signal, fill

The shift(1) is the important line. It ensures a signal calculated from a completed bar is acted on during the following bar, never the same one.

Step 3: Match indicator implementations

Pick one indicator and compare its values directly. Add the indicator to an MT5 chart, export the values, and compare them with your Python calculation over the same bars. Fix seeding, smoothing and warm-up until they agree to within rounding. Only then move to the next indicator.

Step 4: Compare trade lists, not summary statistics

Export the MT5 tester's trade list and compare it with the Python trade list by entry time. Go through the differences in order:

  1. Trades that exist in one test and not the other usually come from signal differences: data, time zone or indicator calculation.
  2. Trades that match in time but differ in entry price usually come from fill rules and spread.
  3. Trades that match on entry but differ on exit usually come from stop-trigger logic or intrabar ambiguity.

Work through the first category before the second, and the second before the third. Each fix tends to remove a whole group of differences at once.

Step 5: Decide what "close enough" means

Perfect agreement is rare and usually not necessary. A practical standard is that the same trades appear in both, entry prices are within a small fraction of the average trade, and any remaining differences have a known cause. Write down what you accepted and why.

Common mistakes

  1. Comparing summary statistics instead of trades. Two tests can show similar totals for completely different reasons.
  2. Calculating a signal and filling on the same bar. It is the single most common cause of a Python backtest that looks better than MT5.
  3. Ignoring server time. Daily-bar strategies are particularly sensitive to where the day starts and ends.
  4. Mixing data sources mid-project. Switching data providers changes results in ways that look like strategy changes.
  5. Treating the more flattering test as the right one. When the two disagree, the optimistic version is usually the one making an unrealistic assumption.
  6. Stopping at agreement. Matching backtests confirm the implementation, not the strategy. Out-of-sample and walk-forward testing still need to follow.

A short reconciliation checklist

  • Python and MT5 use the same broker's data, in the same server time
  • Signals calculated on completed bars and filled on the next bar in both
  • Spread applied to buys in Python, with ask-side stop triggers for shorts
  • Each indicator compared value by value against MT5's output
  • Intrabar stop and target ambiguity handled conservatively, or tested with tick data
  • Commission, swap and volume rounding configured the same way in both
  • Trade lists compared by entry time, with every remaining difference explained
  • Robustness tests run after the implementations agree, not before

Frequently asked questions

Is Python or MT5 better for backtesting?

They suit different jobs. MT5 with real tick data is usually closer to how an EA would have executed on a particular broker. Python is better for fast research, large numbers of variations and custom analysis such as Monte Carlo and walk-forward studies. Many traders use both and reconcile them.

Why does my Python backtest look better than MT5?

The most common reasons are filling trades at the signal bar's close instead of the next available price, ignoring the spread, and resolving intrabar stop-or-target ambiguity optimistically. Each of these makes a Python test look better than real execution would.

Can I get MT5 data into Python?

Yes. The official MetaTrader5 Python package connects to a running MT5 terminal and can read bar and tick history, which removes most data-source and time zone differences between the two tests.

Should my Python and MT5 results match exactly?

Not usually. Small differences from tick-level spreads and rounding are normal. What matters is that the same trades appear in both and every remaining difference has a known cause.

Does matching backtests mean the strategy will work live?

No. Agreement shows that the two implementations describe the same strategy. It says nothing about whether the strategy will perform in future markets, and live results can still differ due to execution and changing conditions.

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.