You backtest an Expert Advisor (EA) in March and note the result. In April you change a filter, then change it back. When you re-run the March test, the trades are different. Which result is real?
If you can't reproduce a backtest, you can't compare it with the next one, you can't tell whether a code change helped, and nobody else can check it. Reproducibility is unglamorous, but every other test in a validation process depends on it. This guide covers what has to be pinned down for a backtest to repeat, how to store each run, and how to use trade-list diffs as regression tests so that each change to the code changes only what you meant it to.
One point up front: reproducibility does not make a strategy good. It makes results checkable. A poor result that repeats exactly is still a poor result, but at least you know it is the strategy's, not the setup's.
Why the same backtest gives different results
When a re-run doesn't match, the cause is almost always one of these:
- The code changed, including an include file or library the EA uses, even if the EA's main file did not.
- The inputs changed. A default value was edited, or the tester loaded a different set of inputs than you thought.
- The data changed. Brokers revise and extend history, and downloaded tick data can differ between downloads. Our guide to MT5 backtest data quality explains where data problems come from.
- The symbol specification changed. Contract size, tick value, swap rates, commission and trading hours are read from the broker at test time and can change.
- The tester settings changed: date range, modelling mode, deposit, leverage, account currency, or delay settings.
- Something is random. Random delay settings, random elements in the EA's logic, and a genetic optimization can all vary between runs.
What to pin for every run
| Item | Why it changes results | What to record |
|---|---|---|
| EA source code and include files | Any logic change changes trades | Version control commit ID; no uncommitted edits |
| Compiled EA and terminal | Compiler or terminal updates can change behaviour | Terminal build number; a hash of the compiled file |
| Inputs | Defaults drift; the wrong set gets loaded | The saved input set file, stored with the run |
| Price data | History is revised and extended | Data source, date range, download or export date, and a hash of exported data where possible |
| Symbol specification | Costs and contract details change | Spread setting, commission, swap, contract size and tick value used |
| Tester settings | Each setting changes fills and sizing | Modelling mode, deposit, leverage, account currency, delays |
| Random elements | Different runs draw differently | Random settings used, and seeds wherever you control them |
Step 1: Put the EA under version control
Version control records every change to your code and lets you return to any earlier state exactly. Git is the common choice and is free.
- Keep the EA's folder in a repository, including every include file and library it uses. An include file that lives outside the repository is a change you won't see.
- Commit every change, with a message that says why: "Widen session filter to 07:00" is useful later; "update" is not.
- Never run a test you intend to keep with uncommitted changes. If the code isn't committed, the result can't be tied to a version.
- Put a version string in the EA with
#property versionand print it, with the input values, in the log when the EA starts. Then every log and report says which version produced it.
Step 2: Save every run with a manifest
Give each run you keep its own folder: the tester report, the input set file, the exported trade list, and a manifest file that records everything in the table above. A short script can write the manifest and add a fingerprint (a SHA-256 hash) of each file, so you can later prove that nothing in the folder has changed.
import hashlib, json, pathlib, subprocess
from datetime import datetime, timezone
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def git(repo_dir, *args):
return subprocess.run(["git", "-C", repo_dir, *args],
capture_output=True, text=True, check=True).stdout.strip()
def write_manifest(run_dir, repo_dir, settings):
"""settings: dict of what you set by hand, e.g. terminal build, symbol, dates, modelling mode, deposit."""
run = pathlib.Path(run_dir)
manifest = {
"created_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"ea_commit": git(repo_dir, "rev-parse", "HEAD"),
"uncommitted_changes": git(repo_dir, "status", "--porcelain") != "",
"settings": settings,
"files": {p.name: sha256(p) for p in sorted(run.iterdir())
if p.is_file() and p.name != "manifest.json"},
}
(run / "manifest.json").write_text(json.dumps(manifest, indent=2))
return manifest
If uncommitted_changes comes back true, treat the run as a draft: commit, then run it again.
Step 3: Re-run the baseline before changing anything
Before you change the strategy, re-run the last result you kept, with the same commit, inputs and settings. The trade list should match exactly.
- If it matches, you have a clean baseline. Any difference after your next change comes from that change.
- If it doesn't match, stop and find out why before going further. The usual causes are revised data, a changed symbol specification, a terminal update or an include file outside version control. If you build your own history, our guide to sourcing tick data for MT5 custom symbols covers keeping a fixed, documented copy, which removes most data drift.
Small differences can be legitimate, for example when a broker has corrected bad ticks. Record the cause and re-baseline deliberately. Don't let the baseline drift without a note.
Step 4: Diff the trade lists after every change
A summary statistic can stay almost the same while the trades underneath change completely. Comparing trade lists, trade by trade, shows exactly what a change did. This is a regression test: a change meant to be a tidy-up should produce identical trades, and a change to a filter should remove or add only the trades that filter affects.
import pandas as pd
def diff_trades(old_csv, new_csv, key=("open_time", "direction")):
"""Compare two trade lists from the same test settings. Columns: open_time, close_time, direction, volume, profit."""
old = pd.read_csv(old_csv, parse_dates=["open_time", "close_time"])
new = pd.read_csv(new_csv, parse_dates=["open_time", "close_time"])
m = old.merge(new, on=list(key), how="outer", suffixes=("_old", "_new"), indicator=True)
removed = m[m["_merge"] == "left_only"]
added = m[m["_merge"] == "right_only"]
both = m[m["_merge"] == "both"]
changed = both[(both["close_time_old"] != both["close_time_new"])
| (both["volume_old"] != both["volume_new"])
| ((both["profit_old"] - both["profit_new"]).abs() > 0.005)]
print(f"old {len(old)} trades, new {len(new)}: "
f"{len(removed)} removed, {len(added)} added, {len(changed)} changed")
return removed, added, changed
How to use it:
- Write down what you expect before running the diff. "This filter should remove some trades during the first hour of the session and add none." Then check that the removed trades really are in that window and nothing else moved.
- Investigate every unexpected change. A trade that changed when it shouldn't have usually means a side effect in the code, such as a shared variable or a changed order of operations.
- If two trades can open at the same time in the same direction, add a sequence number to the key so each trade matches only its own counterpart.
This is especially useful when someone else, or an AI assistant, edits the code. Our guide to validating an AI-generated EA covers checking that new code does what you meant; the diff then shows what each later edit actually changed.
Step 5: Keep a research log, including what failed
A research log is a dated record of every idea you tested, the commit and run folder, the result, and what you decided. It does two jobs.
- It keeps the search honest. The number of variants you tried is part of the result. A strategy chosen from 50 variants deserves more suspicion than one tested once, and you can only say how many you tried if you wrote them down. Our guide to spotting an overfit backtest explains why a large search behind a single winner is a warning sign, and our guide to data-mining bias shows how to measure the effect of the search itself.
- It records every look at held-back data. Each time you check the out-of-sample period, some of its independence is used up. Logging each look, as our guide to out-of-sample testing recommends, shows how clean that data still is.
Log the failures as carefully as the successes. They are the part of the record most likely to be forgotten, and the part that matters most when you judge the winner.
Step 6: Freeze what goes live
The version that passed testing should be exactly the version that runs live: the same commit, the same compiled file (checked by its hash), and the same input set file. Tag that commit in version control, and have the EA print its version and inputs in the log when it starts, so the live log confirms what is running. Our EA pre-live checklist covers the other checks before going live.
If you change anything after testing, even "just" an input, you are running an untested version. Re-test it, or record that you are accepting that risk.
Common reproducibility mistakes
- Keeping results without the inputs that produced them.
- Testing with uncommitted code, so no result can be tied to a version.
- Leaving include files outside version control.
- Assuming the data is fixed when the broker's history has been revised or extended.
- Comparing runs with different tester settings, such as a different modelling mode or deposit.
- Checking only the summary figures after a change, instead of diffing the trades.
- Logging only the ideas that worked, which hides how large the search really was.
- Editing the live EA's inputs without re-testing that exact configuration.
Reproducibility checklist
- EA source and every include file in version control, with no uncommitted changes before a kept run
- Version string and input values printed in the log at start-up
- Each kept run in its own folder: report, input set file, trade list and manifest
- Manifest records commit, terminal build, data source and dates, symbol specification and tester settings
- Baseline re-run and matched before each change
- Trade lists diffed after each change, with expected differences written down first
- Research log of every variant, every result and every look at held-back data
- Live version tagged and matched to the tested commit, compiled file and inputs
Frequently asked questions
Why do my MT5 backtest results change when I re-run the same EA?
Usually because something other than the main EA file changed: an include file, the inputs, the price history, the symbol's costs or contract details, the tester settings, or a random element such as random delays. Record each of these with every run you keep, and the cause of a mismatch becomes easy to find.
Do I need Git to version-control an EA?
Any tool that records every change and lets you return to an exact earlier state will do. Git is free, widely used and works well with code files. What matters is that every result you keep can be tied to an exact version of the code.
What should I save with each backtest?
The tester report, the input set file, the exported trade list, and a note or manifest with the code version, terminal build, data source and date range, symbol costs and tester settings. A hash of each file shows later that nothing has changed.
How do I check that a code change didn't break my EA?
Run the same test before and after the change and compare the trade lists trade by trade. Write down which trades you expect to change first. A tidy-up should change nothing, and any change you didn't expect points to a side effect worth finding.
Does a reproducible backtest mean the strategy is robust?
No. Reproducibility means the result can be checked and repeated. Whether the strategy holds up is a separate question, answered by out-of-sample, walk-forward and stress tests, and none of those can predict future results.
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 ReportWant 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; the code examples produce your own test results. We do not guarantee the outcome of any prop firm challenge.