Counting signals is not a backtest. The method-spec post scored XAU-01 on real candles and graded an agent against the answer key, but it never asked what happens after the signal: where the order fills, whether SL or TP is hit first, what the spread and commission take, and whether a second signal arrives while the first trade is still open.
This post adds those four things. It locks a candle file and two periods, checks the spec’s EMA and ATR against two independent libraries, runs the spec through backtesting.py with costs, reads every trade in R with a confidence interval, compares the result with a second engine, builds reports that never touch the network, and only then opens the holdout, once.
Terms used below:
- Backtest: running a rule on historical data as if trading: entry, SL, TP, costs, one trade at a time. The result is a simulation, not a promise.
- Independent reference: a calculation written by someone else, here TA-Lib and pandas-ta-classic, used to check your own function. Only when they agree within a stated tolerance do you trust your numbers.
- EMA seed: where the first EMA value comes from. The spec’s
emastarts at the first close; TA-Lib and pandas-ta-classic start at the mean of the first n closes by default. The two differ at the start, then the gap fades. - ddof: what a standard deviation divides by: n (ddof = 0, as MT5 and TA-Lib do) or n − 1 (ddof = 1, the pandas default).
- Spread as a ratio: backtesting.py takes the spread as a fraction of price, not in USD: 0.000168 means 0.57 USD at a price of 3,391.
- Slippage: how much worse the fill is than the quoted price. backtesting.py 0.6.6 has no parameter for it, so it’s added to the spread.
- Holdout: a stretch of data kept aside and run exactly once, after every choice is written down. Open it a second time and it is no longer unused.
- R: a trade’s net profit or loss divided by its initial SL distance (1.5 × ATR14) times its size. −1R is losing exactly one SL distance.
- 95% confidence interval: the range around mean R that the data can’t rule out. An interval that contains 0 means no evidence of an edge yet.
- Self-contained HTML: a file with every script inside it: it opens with the network off and contacts no server when opened.
What a backtest adds, and a pinned set of libraries
A backtest adds four things to a signal count:
- Enter at the open of the candle right after [1] (the candle that just closed).
- Place SL and TP, then see which is hit first.
- Hold one position at most.
- Subtract costs from every trade.
With those four you get a list of trades, an R for each one and an equity curve (capital over time) to read.
The split of work stays the same as in every earlier post: code computes, the
agent writes, you decide. The entry conditions use exactly ema, atr,
evaluate and price_levels from src/xau_01.py. The lot uses
src/lot.py. The backtest library only handles fills, SL, TP and costs.
Each layer gets its own check before the numbers above it are worth reading:
| Layer | What | Checked against |
|---|---|---|
| 1 | EMA and ATR | TA-Lib and pandas-ta-classic, tolerance 0.0005 USD |
| 2 | Backtest with costs | backtesting.py fills; the rule is still src/xau_01.py |
| 3 | Trade list | A second engine’s ledger, matched by candle [1] and side |
| 4 | Report and chart | QuantStats and Plotly, checked to make no network calls |
| 5 | Strategy Tester and stop conditions | A third engine on the broker’s own history; your stop table |
The five open-source libraries, pinned:
| Library | Version | License | Job here |
|---|---|---|---|
| backtesting.py | 0.6.6 | AGPL-3.0 | Fills, SL, TP, spread, commission; the trade list |
| TA-Lib (Python package) | 0.8.3.post1 | BSD-2-Clause | Independent reference for EMA and ATR |
| pandas-ta-classic | 0.9.0 | MIT | A second independent reference |
| QuantStats | 0.0.86 | Apache-2.0 | Report from the equity curve |
| Plotly | 7.1.0 | MIT | Candle chart marking each trade |
backtesting.py is AGPL-3.0. Running it on your own machine to learn carries
no extra obligation. Obligations start when you hand it to someone else:
modify the library and let others use it over a network (section 13 then
requires you to offer them the modified source), or give or sell a tool that
bundles it, even unmodified (a packaged .exe, a .venv folder, or a
bt.plot() file carrying the library’s JavaScript), which is distribution
under sections 4 to 6. So this post runs it on your machine only. That’s a
reading of the license text, not legal advice.
QuantStats installs yfinance, an unofficial Yahoo data library in a grey area of Yahoo’s terms. Nothing here calls it: the report section hands QuantStats a benchmark built from your own CSV, and the report still builds with every network path blocked.
The TA-Lib 0.8.3.post1 package on PyPI ships only prebuilt wheels with the C library inside, for Python 3.10 to 3.15 on Windows (64-bit, 32-bit, ARM64), macOS (Intel from macOS 13, Apple Silicon from macOS 14) and Linux. No separate C install. The full requirements need Python 3.12 or later (numpy 2.5.5, scipy 1.18.1, bokeh 3.10.2), so use the 64-bit Python 3.14 from the setup post.
Create the requirements file and install, in PowerShell from the project
folder, one line at a time. At each notepad line: say Yes to creating the
file, paste, press Ctrl + S and close Notepad before the next line.
cd C:\trading-agent-lab
notepad requirements-backtest.txt
.venv\Scripts\python -m pip install -r requirements-backtest.txt
.venv\Scripts\python -c "import backtesting, talib, pandas_ta_classic, quantstats, plotly; print(backtesting.__version__, talib.__version__, pandas_ta_classic.__version__, quantstats.__version__, plotly.__version__)"requirements-backtest.txt:
# requirements-backtest.txt | Python backtest on MT5 candles | tested on Windows 11, Python 3.14
# Install: .venv\Scripts\python -m pip install -r requirements-backtest.txt
pandas==3.1.1
numpy==2.5.5
scipy==1.18.1
pytest==9.2.0
backtesting==0.6.6
bokeh==3.10.2
TA-Lib==0.8.3.post1
pandas-ta-classic==0.9.0
quantstats==0.0.86
matplotlib==3.11.2
seaborn==0.13.2
yfinance==1.8.0 # installed with QuantStats; never called here (unofficial, grey area under Yahoo's terms)
plotly==7.1.0
tzdata==2026.6pip ends with Successfully installed (or Requirement already satisfied).
The last line prints 0.6.6 0.8.3 0.9.0 0.0.86 7.1.0. TA-Lib reports 0.8.3
for 0.8.3.post1: same build.
On macOS the backtest part runs with a copied CSV if you swap \ for /,
.venv\Scripts\python for .venv/bin/python, notepad for open -e,
Get-FileHash for shasum -a 256, Copy-Item for cp, Move-Item for
mv, start for open and $env:X = ... for export X=.... It hasn’t
been tried on macOS.
| You see | Cause | Fix |
|---|---|---|
No matching distribution found for pandas==3.1.1 (or numpy) |
The .venv Python is older than 3.12 |
First line of python --version must start with 3.14 and be 64-bit; recreate .venv |
No matching distribution found for TA-Lib==0.8.3.post1 |
Python older than 3.10, or a macOS older than the wheels | Use Windows with 64-bit Python 3.14, or a recent enough Mac |
pip downloads pandas-3.1.1.tar.gz and fails to build |
32-bit Python: no prebuilt pandas, scipy or matplotlib | Recreate .venv with 64-bit Python 3.14 |
ModuleNotFoundError: No module named 'talib' |
Installed into another Python | Always type .venv\Scripts\python -m pip ... |
Pandas4Warning: DatetimeIndex.dayofweek is deprecated from backtesting\_stats.py |
backtesting.py 0.6.6 with pandas 3.1 | Results are unchanged; don’t downgrade pandas |
UserWarning: set_ticklabels() ... from quantstats\_plotting |
QuantStats plotting with a newer matplotlib | The report is unchanged; ignore it |
Data: closed H1 candles from MT5, converted to UTC, locked
A backtest needs more than the 500 candles of the MT5-reading post. About 12,000 H1 candles is roughly two years; the first 1,500 only let EMA200 settle, as the spec says.
Step 1. In src/mt5_read.py, replace the line CANDLES = 500 with:
CANDLES = int(os.environ.get("TL_CANDLES", "500")) # set TL_CANDLES to fetch more candlesThe default stays 500. The script still starts at position 1, so it only
writes closed candles, and the time column is still server time.
Step 2. Export about 12,000 candles, copy the file to
data/xauusd_h1_backtest.csv and record its SHA-256 hash (the file’s
fingerprint: change one character and the hash changes). The daily run of
mt5_read.py overwrites its own file but never this one, and
src/bt_xau_01.py compares the hash on every run and stops if the file
differs from the locked one.
Step 3. Run src/mt5_candles.py. It reads the file, converts server
time to UTC and checks itself. Set three values in it first:
HOUR_OFFSET: the hours your server runs ahead of UTC, measured in winter as in the method-spec post.DST_RULE: how the server changes with the seasons. Many MT5 servers run one hour further ahead in summer."us"follows the US calendar (second Sunday of March, first Sunday of November),"europe"the European one (last Sundays of March and October),"none"keeps it fixed all year.POINT: converts thespreadcolumn from points (the smallest price step) to USD: 0.01 when gold has 2 decimals, 0.001 with 3. Check thedigitslinemt5_read.pyprints.
How you know the conversion is right: gold pauses for 60 minutes every day at 17:00 New York time. In UTC, the missing H1 candle is 21:00 while New York is on summer time and 22:00 in winter. The script finds the missing candle in each ISO week (weeks numbered from Monday by the international standard) and prints every week that’s off.
- Off by exactly one hour in the summer weeks: change
DST_RULEfrom"none"to"us"or"europe". - Only 2 or 3 weeks in mid-March and the last week of October are off: swap
between
"us"and"europe". - Every week off by the same amount: fix
HOUR_OFFSET.
The wrong calendar does real damage. On a European-calendar sample, choosing
"us" mislabelled 909 candles, 8.4% of the file: 07:00 UTC entries were
dropped and every comparison in those weeks was one hour off. The check only
holds if your broker pauses at 17:00 New York time; if it pauses at a fixed
server hour, confirm with the ledger comparison below (trades off by exactly
one hour in those weeks).
Export, copy, hash and check, with the MT5 demo terminal open and logged in with the investor password:
cd C:\trading-agent-lab
notepad src\mt5_read.py
$env:TL_SYMBOL = "XAUUSD" # use the exact Market Watch name (Ctrl+M)
$env:TL_CANDLES = "12000"
.venv\Scripts\python src\mt5_read.py
if ($LASTEXITCODE -eq 0) { Copy-Item "data\$($env:TL_SYMBOL.ToLower())_h1_mt5.csv" data\xauusd_h1_backtest.csv }
Get-FileHash data\xauusd_h1_backtest.csv
notepad src\mt5_candles.py
notepad tests\test_mt5_candles.py
.venv\Scripts\python -m pytest -q tests\test_mt5_candles.py
.venv\Scripts\python src\mt5_candles.py data\xauusd_h1_backtest.csvsrc/mt5_candles.py:
# src/mt5_candles.py: read an MT5-style H1 CSV (time,open,high,low,close,tick_volume,spread,real_volume),
# convert the time column to UTC and check the file before a backtest. Reads files only: no network, no orders.
# Check a file: .venv\Scripts\python src\mt5_candles.py data\xauusd_h1_backtest.csv
import sys
from datetime import timedelta, timezone
from zoneinfo import ZoneInfo
import pandas as pd
HOUR_OFFSET = 0 # hours the file's clock runs ahead of UTC, measured in winter (0 on the sample file)
DST_RULE = "none" # server clock changes with the seasons: "none", "us" or "europe"; summer adds 1 hour
POINT = 0.01 # one point of XAUUSD at your broker (symbol_info().point); the spread column is in points
NY = ZoneInfo("America/New_York") # Windows needs the tzdata package
RULES = {"us": NY, "europe": ZoneInfo("Europe/London")} # London changes on the same day as the rest of Europe
def to_utc(t):
"""File time -> UTC. With a seasonal server clock, summer under that calendar adds 1 hour."""
offset = HOUR_OFFSET
if DST_RULE != "none" and (t - timedelta(hours=HOUR_OFFSET)).replace(tzinfo=timezone.utc).astimezone(RULES[DST_RULE]).dst():
offset += 1
return t - timedelta(hours=offset)
def read_mt5_candles(path, until_utc=None):
"""Index = candle open time in UTC; columns Open, High, Low, Close (BID) and Spread (USD).
until_utc: keep only candles opening before this time, so holdout rows never leak into development."""
if DST_RULE not in ("none", *RULES):
raise SystemExit(f'DST_RULE must be "none", "us" or "europe", not {DST_RULE!r}.')
raw = pd.read_csv(path, encoding="utf-8-sig")
missing = {"time", "open", "high", "low", "close", "spread"} - set(raw.columns)
if missing:
raise SystemExit(f"File lacks columns {sorted(missing)}: export it with src/mt5_read.py.")
idx = pd.DatetimeIndex([to_utc(t) for t in pd.to_datetime(raw["time"])], name="time_utc")
df = pd.DataFrame({"Open": raw["open"].to_numpy(), "High": raw["high"].to_numpy(), "Low": raw["low"].to_numpy(),
"Close": raw["close"].to_numpy(), "Spread": raw["spread"].to_numpy() * POINT}, index=idx)
if not df.index.is_monotonic_increasing or df.index.has_duplicates:
raise SystemExit("Candle times not increasing or duplicated: check HOUR_OFFSET, DST_RULE and the CSV.")
bad = (df["High"] < df[["Open", "Close"]].max(axis=1)) | (df["Low"] > df[["Open", "Close"]].min(axis=1))
if bad.any():
raise SystemExit(f"{int(bad.sum())} candles with an impossible High or Low, first at {df.index[bad][0]}")
return df if until_utc is None else df[df.index < pd.Timestamp(until_utc)]
def daily_break_by_week(df):
"""Gold pauses 60 minutes a day at 17:00 New York time: 21:00 UTC under New York summer time, 22:00 in winter.
Returns rows of (ISO week, most common missing UTC hour, expected hour, days). A mismatched week = wrong conversion."""
t = df.index.to_series()
gaps = t[(t.shift(-1) - t) == pd.Timedelta(hours=2)] + pd.Timedelta(hours=1) # the missing candle between two
iso = gaps.dt.isocalendar()
week = iso["year"].astype(str) + "-W" + iso["week"].astype(str).str.zfill(2) # ISO week, from Monday
table = []
for name, group in gaps.groupby(week):
common = int(group.dt.hour.mode().iloc[0])
mid = group.iloc[len(group) // 2].tz_localize("UTC")
expected = 21 if mid.astimezone(NY).dst() else 22
table.append((name, common, expected, len(group)))
return table
def main():
df = read_mt5_candles(sys.argv[1] if len(sys.argv) > 1 else "data/xauusd_h1_backtest.csv")
print(f"{len(df)} candles | first {df.index[0]} UTC | last {df.index[-1]} UTC | HOUR_OFFSET={HOUR_OFFSET}, DST_RULE={DST_RULE}")
hour = df.index.hour
window = df[(hour >= 7) & (hour < 21)] # candles opening in XAU-01's entry window
for year, s in window["Spread"].groupby(window.index.year):
print(f"Median spread {year}, candles opening 07:00-20:00 UTC: {s.median():.2f} USD")
table = daily_break_by_week(df)
if not table:
raise SystemExit("No missing H1 candle inside any day: the daily-break check can't be used on this file; "
"measure HOUR_OFFSET on one recognisable candle instead.")
off = [b for b in table if b[1] != b[2]]
for week, h, k, n in off:
print(f"OFF {week}: missing candle usually at {h:02d}:00 UTC, expected {k:02d}:00 ({n} days)")
print(f"Daily break matches New York in {len(table) - len(off)}/{len(table)} weeks "
f"(New York summer time: 21:00 UTC candle missing; winter: 22:00 UTC).")
if __name__ == "__main__":
main()tests/test_mt5_candles.py needs neither MT5 nor a real file: it builds fake
server-time candles for both calendars.
# tests/test_mt5_candles.py: server time to UTC, and reading an MT5-style file. Needs neither MT5 nor a real file.
from datetime import datetime, timedelta
import pandas as pd
import pytest
import src.mt5_candles as mc
SERVER_US = [(datetime(2026, 7, 13), 0), (datetime(2026, 11, 9), 0)] # server = New York + 7: break at 00:00
SERVER_EUROPE = [(datetime(2026, 3, 9), 23), (datetime(2026, 7, 13), 0), # UTC+2, European summer UTC+3: break 23:00
(datetime(2026, 10, 26), 23), (datetime(2026, 11, 9), 0)] # in the weeks the two calendars disagree
def test_server_on_us_calendar(monkeypatch):
monkeypatch.setattr(mc, "HOUR_OFFSET", 2) # measured in winter: server 2 hours ahead of UTC
monkeypatch.setattr(mc, "DST_RULE", "us")
assert mc.to_utc(datetime(2026, 11, 9, 21, 0)) == datetime(2026, 11, 9, 19, 0) # winter: minus 2
assert mc.to_utc(datetime(2026, 7, 15, 12, 0)) == datetime(2026, 7, 15, 9, 0) # US summer: minus 3
assert mc.to_utc(datetime(2026, 3, 10, 12, 0)) == datetime(2026, 3, 10, 9, 0) # US changed on 2026-03-08
def test_server_on_european_calendar(monkeypatch):
monkeypatch.setattr(mc, "HOUR_OFFSET", 2)
monkeypatch.setattr(mc, "DST_RULE", "europe")
assert mc.to_utc(datetime(2026, 11, 9, 21, 0)) == datetime(2026, 11, 9, 19, 0) # winter: minus 2
assert mc.to_utc(datetime(2026, 7, 15, 12, 0)) == datetime(2026, 7, 15, 9, 0) # summer: minus 3
assert mc.to_utc(datetime(2026, 3, 10, 12, 0)) == datetime(2026, 3, 10, 10, 0) # Europe changes on 2026-03-29
assert mc.to_utc(datetime(2026, 10, 27, 12, 0)) == datetime(2026, 10, 27, 10, 0) # back to winter on 10-25
def test_server_without_seasons(monkeypatch):
monkeypatch.setattr(mc, "HOUR_OFFSET", 2)
monkeypatch.setattr(mc, "DST_RULE", "none")
assert mc.to_utc(datetime(2026, 7, 15, 12, 0)) == datetime(2026, 7, 15, 10, 0)
def _server_file(tmp_path, weeks_and_break):
"""Fake H1 candles on server time: 4 days a week from Monday, each day missing exactly the break hour."""
rows = ["time,open,high,low,close,tick_volume,spread,real_volume"]
for start, brk in weeks_and_break:
for day in range(4):
for hour in range(24):
if hour != brk:
t = start + timedelta(days=day, hours=hour)
rows.append(f"{t:%Y-%m-%d %H:%M:%S},4000,4001,3999,4000.5,100,50,0")
p = tmp_path / "server.csv"
p.write_text("\n".join(rows) + "\n", encoding="utf-8")
return p
def test_read_file_and_break_matches_new_york(tmp_path, monkeypatch):
monkeypatch.setattr(mc, "HOUR_OFFSET", 2)
monkeypatch.setattr(mc, "DST_RULE", "us")
df = mc.read_mt5_candles(_server_file(tmp_path, SERVER_US))
assert df.index[0] == pd.Timestamp("2026-07-12 22:00") # 01:00 summer server time = 22:00 UTC day before
assert df["Spread"].iloc[0] == pytest.approx(0.50) # 50 points x 0.01
assert [(w, h, k) for w, h, k, _ in mc.daily_break_by_week(df)] == [("2026-W29", 21, 21), ("2026-W46", 22, 22)]
def test_wrong_season_rule_shows_in_the_break(tmp_path, monkeypatch):
monkeypatch.setattr(mc, "HOUR_OFFSET", 2)
monkeypatch.setattr(mc, "DST_RULE", "none") # forgot the seasonal change
table = mc.daily_break_by_week(mc.read_mt5_candles(_server_file(tmp_path, SERVER_US)))
assert [(w, h, k) for w, h, k, _ in table] == [("2026-W29", 22, 21), ("2026-W46", 22, 22)]
def test_european_server_read_as_us_is_off_in_march_and_october(tmp_path, monkeypatch):
monkeypatch.setattr(mc, "HOUR_OFFSET", 2)
p = _server_file(tmp_path, SERVER_EUROPE)
monkeypatch.setattr(mc, "DST_RULE", "us") # wrong calendar
assert [w for w, h, k, _ in mc.daily_break_by_week(mc.read_mt5_candles(p)) if h != k] == ["2026-W11", "2026-W44"]
monkeypatch.setattr(mc, "DST_RULE", "europe")
assert all(h == k for _, h, k, _ in mc.daily_break_by_week(mc.read_mt5_candles(p)))
def test_cut_before_the_holdout(tmp_path, monkeypatch):
monkeypatch.setattr(mc, "HOUR_OFFSET", 0)
monkeypatch.setattr(mc, "DST_RULE", "none")
df = mc.read_mt5_candles(_server_file(tmp_path, SERVER_US), until_utc="2026-11-01")
assert df.index.max() < pd.Timestamp("2026-11-01")
def test_missing_column_or_mistyped_rule_stops(tmp_path, monkeypatch):
p = tmp_path / "short.csv"
p.write_text("time,open,high,low,close\n2026-11-09 18:00:00,1,2,0.5,1.5\n", encoding="utf-8")
with pytest.raises(SystemExit):
mc.read_mt5_candles(p)
monkeypatch.setattr(mc, "DST_RULE", "US")
with pytest.raises(SystemExit):
mc.read_mt5_candles(_server_file(tmp_path, SERVER_US))mt5_read.py prints its safety lines and ends with
<count> closed candles -> data/xauusd_h1_mt5.csv, the count close to
12,000. Far fewer means the terminal hasn’t loaded that much history: open
the H1 chart, scroll back, run it again. Copy only when mt5_read.py ended
without an error: the old 500-candle file has the same name and would be
copied silently.
pytest prints 8 passed. On a 10,831-candle H1 BID sample in UTC (2025-01-01
to 2026-10-30, same columns as an MT5 export), mt5_candles.py prints:
10831 candles | first 2025-01-01 23:00:00 UTC | last 2026-10-30 09:00:00 UTC | HOUR_OFFSET=0, DST_RULE=none
Median spread 2025, candles opening 07:00-20:00 UTC: 0.56 USD
Median spread 2026, candles opening 07:00-20:00 UTC: 0.61 USD
Daily break matches New York in 96/96 weeks (New York summer time: 21:00 UTC candle missing; winter: 22:00 UTC).That’s not your broker’s data; on your MT5 file every number below will differ.
| You see | Cause | Fix |
|---|---|---|
Symbol not found: XAUUSD |
Another symbol name, or a new PowerShell window without TL_SYMBOL |
Set $env:TL_SYMBOL, rerun mt5_read.py, then copy |
Copy-Item : Cannot find path ..._h1_mt5.csv |
The file name follows TL_SYMBOL, or mt5_read.py stopped |
Copy the file the closed candles -> line names |
OFF in the weeks from March to October, winter weeks fine |
Seasonal server clock, DST_RULE still "none" |
Set "us" or "europe", rerun |
Only 2 or 3 weeks in March and late October OFF |
Wrong calendar | Swap "us" and "europe" |
Every week OFF by the same hours |
HOUR_OFFSET wrong |
Fix it |
No missing H1 candle inside any day ... |
The break is under an hour, or the symbol has none (EURUSD) | Measure the offset on one recognisable candle instead |
Candle times not increasing or duplicated |
Wrong offset settings make two candles collide around a clock change | Check HOUR_OFFSET and DST_RULE |
File lacks columns ... |
The file wasn’t made by mt5_read.py, or was saved by Excel |
Export again; open CSVs in Notepad only |
| Median spread of several USD, or a few cents | POINT off by 10x |
Set POINT from the digits line |
Step 4. Lock every choice in specs/backtest-xau-01-v1.md and commit it
before the first run, the same way the method spec, the pre-run threshold
and the level-2 criteria were locked. The two periods go by the entry
candle’s date: development (for trying things) through 2025-12-31; holdout
(kept aside, run once) from 2026-01-01. A development run never reads a row
from 2026-01-01 on. The conclusion threshold is also written now, before any
number exists.
Save as specs/backtest-xau-01-v1.md, fill the brackets, copy the threshold
into reports/threshold-before-run.md, and paste the same hash into
DATA_SHA256 in src/bt_xau_01.py later:
# Backtest spec xau-01-v1 | written on [DATE] | committed before the first run, never edited after a run
Rule: specs/xau-01-v1.md, code src/xau_01.py passing 9/9 tests. v1 is not optimised: EMA 21/55/200, ATR14, SL 1.5 ATR, TP 3 ATR as written.
Data: data/xauusd_h1_backtest.csv | SHA-256 [PASTE HASH]
Source: [your MT5 demo, symbol, export date] | HOUR_OFFSET = [ ] | DST_RULE = [ ] | daily break matches New York in [ ]/[ ] weeks.
Periods (by entry candle): first 1,500 candles warm up EMA200 only | development: through 2025-12-31 | holdout: from 2026-01-01, run once.
Costs: spread = median of (spread / price) over candles opening 07:00-20:00 UTC in development | slippage 0.10 USD/oz per fill,
added to the spread for both entry and exit | commission 0.07 USD/oz round trip | swap not counted.
Capital and lot: paper capital 10,000 USD | risk 100 USD per trade | lot rounded down to 0.01 (src/lot.py), skip below 0.01 | margin 1:20.
Read: trade count; mean R, its 95% interval and t; total R; max drawdown; longest losing streak.
Trial log: reports/trial-log.csv, same columns as before; the script adds a row on every run, bad ones included.
Threshold written in advance (also copy it into reports/threshold-before-run.md): write "worth running on demo" only if
the lower bound of mean R's 95% interval is above 0 in BOTH periods; otherwise write "no evidence yet".
Variants (parameters, costs, filters) run on development only: one log row each, counted in m and the adjusted t threshold.
A chosen variant becomes a new spec (v2, change VERSION), committed before the holdout is opened exactly once;
once opened, never rerun it; anything changed afterwards is tested on unused data.
Cross-checks: MT5 Strategy Tester (same period, same costs) and the stop-conditions table reports/stop-conditions.md.
Simulation on historical data, not investment advice.notepad specs\backtest-xau-01-v1.md
notepad reports\threshold-before-run.md
git add requirements-backtest.txt src\mt5_read.py src\mt5_candles.py tests\test_mt5_candles.py specs\backtest-xau-01-v1.md reports\threshold-before-run.md data\xauusd_h1_backtest.csv
git commit -m "Lock backtest spec xau-01-v1"For the sample: SHA-256
9D050CA0914090DD6F874446E6FDE2B683789DAE379BBC12534EFBF747C67C26,
HOUR_OFFSET = 0, DST_RULE = "none", break matches 96/96 weeks.
Independent references for EMA and ATR
ema and atr in src/xau_01.py were written by you and an agent. To trust
them, compare with code someone else wrote. Two open libraries do the job:
TA-Lib (a Python wrapper around a C library) and pandas-ta-classic (pure
pandas). Watch pandas-ta-classic’s talib argument: 0.9.0 defaults to
talib=False and computes in pandas; talib=True calls TA-Lib directly and
is no longer a second reference. The tests say talib=False explicitly.
EMA differs at the start because of the seed. The spec’s ema uses the
first close as the first EMA, which matches MT5 and pandas
ewm(adjust=False). TA-Lib leaves n − 1 values empty and starts from the
mean of the first n closes. pandas-ta-classic does the same by default
(sma=True); with sma=False it matches MT5.
The initial gap shrinks by a factor of 1 − 2/(n+1) per candle, so measure it on your file. On the sample, TA-Lib’s EMA200 is off by more than 0.0005 USD for the first 988 candles: 199 empty, 789 fading. EMA21 settles after 109 candles, EMA55 after 299. After candle 1,500 the largest EMA200 gap is 3.0e-06 USD. That’s why the spec asks for 1,500 warm-up candles and the tests compare only from candle 1,500.
ATR differs in the formula, not just the seed. The XAU-01 spec, like MT5,
takes the simple mean of 14 True Ranges. talib.ATR and pandas-ta-classic’s
default use Wilder smoothing (RMA), so they stay off after warm-up: on the
sample a median 0.96 USD and up to 29.32 USD, against a median ATR14 of
15.89 USD. The right reference for this spec is
talib.SMA(talib.TRANGE(...), 14), or pandas-ta-classic with
mamode="sma". Both match atr to 1e-9.
The tolerance is a written number: 0.0005 USD, half a unit of the spec’s 3-decimal rounding. Two implementations of the same formula are compared to 1e-9, leaving room only for floating-point error.
One more place specs must state: the standard deviation. MT5 computes
Bollinger bands dividing by n (ddof = 0), as do TA-Lib and pandas-ta-classic
by default. pandas std() divides by n − 1 (ddof = 1). Over 20 candles that
makes the deviation 1.026 times larger; on the sample a 2-deviation band is a
median 0.73 USD wider on each side. XAU-01 doesn’t use it; a Bollinger
method does.
| Calculation | Seed or formula | Against the XAU-01 spec |
|---|---|---|
ema() from the method-spec post |
First close, factor 2/(n+1) | Is the spec |
pandas ewm(span=n, adjust=False) |
First close | Matches from the first candle |
talib.EMA |
n − 1 NaNs, then SMA of the first n | Matches after warm-up |
pandas-ta-classic ema, default |
Like TA-Lib (sma=True) |
Matches after warm-up |
pandas-ta-classic ema(sma=False) |
First close | Matches from the first candle |
talib.SMA(talib.TRANGE(...), 14) |
Simple mean of 14 True Ranges | Matches: the ATR reference |
pandas-ta-classic atr(mamode="sma") |
Simple mean of 14 True Ranges | Matches |
talib.ATR; pandas-ta-classic atr default |
Wilder smoothing (RMA) | No match, even after warm-up |
pandas std(), default |
Divides by n − 1 | Differs from MT5 Bollinger (ddof = 0) |
cd C:\trading-agent-lab
notepad tests\test_indicators_independent.py
notepad src\indicator_diffs.py
.venv\Scripts\python -m pytest -q tests\test_indicators_independent.py
.venv\Scripts\python src\indicator_diffs.pytests/test_indicators_independent.py:
# tests/test_indicators_independent.py: compare the hand-written ema and atr (src/xau_01.py) with two open libraries.
# Runs on your candle file in data/. Tolerance 0.0005 USD = half a unit of the spec's 3-decimal rounding.
import numpy as np
import pandas as pd
import pandas_ta_classic as pta
import pytest
import talib
from src.xau_01 import MIN_CANDLES, atr, ema
TOL = 0.0005
DF = pd.read_csv("data/xauusd_h1_backtest.csv")
H, L, C = (DF[k].to_numpy(dtype=float) for k in ("high", "low", "close"))
CANDLES = [{"h": h, "l": l, "c": c} for h, l, c in zip(H, L, C)]
@pytest.mark.parametrize("n", [21, 55, 200])
def test_ema_matches_talib_after_warmup(n):
tl = talib.EMA(C, n) # TA-Lib: first value is the SMA of the first n closes, n - 1 NaNs before it
assert np.isnan(tl[: n - 1]).all() and tl[n - 1] == pytest.approx(C[:n].mean())
assert np.abs(np.array(ema(list(C), n))[MIN_CANDLES:] - tl[MIN_CANDLES:]).max() < TOL
@pytest.mark.parametrize("n", [21, 55, 200])
def test_ema_pandas_ta_classic_both_seeds(n):
s = pd.Series(C)
mt5_style = pta.ema(s, length=n, sma=False, talib=False).to_numpy() # starts at the first close
assert np.abs(np.array(ema(list(C), n)) - mt5_style).max() < 1e-9
default = pta.ema(s, length=n, talib=False).to_numpy() # default sma=True: seeded like TA-Lib
assert np.abs(default[n - 1:] - talib.EMA(C, n)[n - 1:]).max() < 1e-6
def test_ema200_warmup_of_1500_is_enough():
diff = np.abs(np.array(ema(list(C), 200)) - talib.EMA(C, 200))
off = np.flatnonzero(~(diff <= TOL)) # NaN counts as off too
assert 199 <= len(off) and off.max() < MIN_CANDLES
def test_atr_is_simple_mean_of_14_true_ranges():
mine = np.array([np.nan if v is None else v for v in atr(CANDLES)], dtype=float)
tl = talib.SMA(talib.TRANGE(H, L, C), 14)
pt = pta.atr(DF["high"], DF["low"], DF["close"], length=14, mamode="sma", talib=False).to_numpy()
assert np.isnan(mine[:14]).all() and np.isnan(tl[:14]).all() and np.isnan(pt[:14]).all()
assert np.nanmax(np.abs(mine - tl)) < 1e-9 and np.nanmax(np.abs(mine - pt)) < 1e-9
def test_wilder_atr_is_not_the_answer_for_this_spec():
"""talib.ATR and pandas-ta-classic's default smooth Wilder-style: off even after warm-up, so not an answer key."""
mine = np.array([np.nan if v is None else v for v in atr(CANDLES)], dtype=float)
wilder = talib.ATR(H, L, C, 14)
assert np.nanmedian(np.abs(mine - wilder)[MIN_CANDLES:]) > 0.1
assert np.nanmax(np.abs(pta.atr(DF["high"], DF["low"], DF["close"], length=14, talib=False).to_numpy() - wilder)) < 1e-6src/indicator_diffs.py:
# src/indicator_diffs.py: measure on your file three places where indicator calculations often differ:
# the EMA seed, the ATR smoothing and the ddof of a standard deviation. Reads files only.
# Run: .venv\Scripts\python src\indicator_diffs.py
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import talib
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.xau_01 import MIN_CANDLES, atr, ema
DF = pd.read_csv(ROOT / "data" / "xauusd_h1_backtest.csv")
H, L, C = (DF[k].to_numpy(dtype=float) for k in ("high", "low", "close"))
for n in (21, 55, 200):
diff = np.abs(np.array(ema(list(C), n)) - talib.EMA(C, n))
off = np.flatnonzero(~(diff <= 0.0005)) # TA-Lib's NaNs count as off too
print(f"EMA{n}: TA-Lib leaves {n - 1} candles empty; off by more than 0.0005 USD on {len(off)} candles, "
f"last one is candle {off.max() + 1}; after candle {MIN_CANDLES} max diff {np.nanmax(diff[MIN_CANDLES:]):.1e}")
spec = np.array([np.nan if v is None else v for v in atr([{"h": h, "l": l, "c": c} for h, l, c in zip(H, L, C)])])
wilder = np.abs(spec - talib.ATR(H, L, C, 14))[MIN_CANDLES:]
print(f"ATR14 simple mean (spec) vs Wilder (talib.ATR): after candle {MIN_CANDLES} median diff "
f"{np.median(wilder):.2f} USD, max {wilder.max():.2f} USD; median ATR14 {np.nanmedian(spec[MIN_CANDLES:]):.2f} USD")
s0, s1 = (pd.Series(C).rolling(20).std(ddof=d).to_numpy() for d in (0, 1))
print(f"20-candle std: ddof=1 (pandas default) / ddof=0 (MT5, TA-Lib) = {np.nanmedian(s1 / s0):.5f}; "
f"a 2-std Bollinger band is wider by a median {np.nanmedian(2 * (s1 - s0)):.2f} USD per side")pytest prints 9 passed. On the sample, indicator_diffs.py prints:
EMA21: TA-Lib leaves 20 candles empty; off by more than 0.0005 USD on 109 candles, last one is candle 109; after candle 1500 max diff 5.5e-12
EMA55: TA-Lib leaves 54 candles empty; off by more than 0.0005 USD on 299 candles, last one is candle 299; after candle 1500 max diff 7.3e-12
EMA200: TA-Lib leaves 199 candles empty; off by more than 0.0005 USD on 988 candles, last one is candle 988; after candle 1500 max diff 3.0e-06
ATR14 simple mean (spec) vs Wilder (talib.ATR): after candle 1500 median diff 0.96 USD, max 29.32 USD; median ATR14 15.89 USD
20-candle std: ddof=1 (pandas default) / ddof=0 (MT5, TA-Lib) = 1.02598; a 2-std Bollinger band is wider by a median 0.73 USD per side| You see | Cause | Fix |
|---|---|---|
test_ema_matches_talib_after_warmup fails for n = 200 |
Short file, or the first prices sit far from the first 200-candle mean | Export more candles at the start; never loosen the tolerance |
test_atr_is_simple_mean_of_14_true_ranges fails |
atr was changed to Wilder, or compared with talib.ATR |
Reread section 3 of the spec |
FileNotFoundError: data/xauusd_h1_backtest.csv |
pytest run from another folder | cd C:\trading-agent-lab first |
backtesting.py runs the spec: fills, SL, TP and costs
src/bt_xau_01.py has two layers.
add_signals scores every candle [1] with the spec’s own evaluate, on
numbers rounded as the spec says. The result is a Signal column: 1 BUY, −1
SELL, 0 stay out. The entry candle’s open time comes from the next row of the
file: that’s the calendar, not a future price.
The Xau01 strategy class only handles orders. In a position: skip the
signal. Lot from src/lot.py; if 0.01 lot already risks more than 100 USD,
skip. Otherwise send a market order with SL and TP.
backtesting.py fills a market order at the next candle’s open
(trade_on_close defaults to False). The 0.6.6 source checks SL and TP
inside the fill candle itself; on the sample 8 development trades and 9
holdout trades exit inside their entry candle.
The cost model has three limits in 0.6.6: the spread is a ratio of price, one number for the whole run; commission is charged twice, on entry and on exit, and may be a function; there is no slippage parameter. So:
- Spread: the median of spread ÷ price over development candles opening 07:00–20:00 UTC: 0.000168, or 0.57 USD at the median price of 3,391.
- Slippage: an assumed 0.10 USD/oz per fill, on entry and on exit. Converted to a ratio and added to the spread twice. backtesting.py charges the whole added amount at entry, so the total per trade is right.
- Commission: 0.07 USD/oz round trip, a function of size, half per side.
- Round trip at 3,391: 0.57 + 2 × 0.10 + 0.07 = 0.84 USD/oz. Swap is not counted.
Bid and Ask, briefly. Bid is what you can sell at, Ask what you pay to
buy; Ask = Bid + spread. The CSV has BID prices only, so each side needs its
own handling. A BUY enters at Ask and exits at Bid, so its SL and TP compare
directly with BID candles. A SELL enters at Bid but exits at Ask, because
closing a SELL means buying back. Its SL is hit when the Ask touches the
level, while the Bid is still one spread below it. With a 0.57 USD spread, a
SELL can be stopped while the BID candle on your chart is still 0.57 USD
under the SL line. sl_tp_levels therefore sets a SELL’s SL and TP one spread
lower on the BID scale, and the test checks both sides: the loss at SL is 1.5
ATR plus slippage, the gain at TP is 3 ATR minus slippage.
SL and TP are computed from the close of [1] plus costs, because backtesting.py needs the levels when the order is placed. On the sample the entry candle’s open differs from the close of [1] by a median 0.03 USD, under 0.50 USD in 99% of cases. So an SL exit usually loses a little more than 1R; when the entry open is better than the close of [1] by more than slippage plus fee (about 0.2 USD/oz), it loses a little less. On the sample that never happened in development and happened in 3 of 55 holdout SL exits.
Limits of the model, written down so you don’t fool yourself:
- Spread and slippage are fixed ratios, so they grow with price. At the 2026 median of 4,465 the model charges a 0.75 USD spread and 0.13 slippage, while the sample’s real 2026 median spread in the same hours is 0.61 USD.
- TP exits are charged slippage too, though limit orders usually don’t slip.
- No swap (the overnight holding fee).
For XAU-01, costs barely move the result because a 1.5 ATR SL is much wider than the costs. Development on the sample at three cost levels:
| Costs | Trades | Mean R | 95% interval |
|---|---|---|---|
| None | 71 | +0.284 | −0.067 to +0.636 |
| Spread only | 72 | +0.266 | −0.082 to +0.614 |
| This post’s model | 72 | +0.255 | −0.093 to +0.604 |
All three intervals contain 0. The cost-free run has one trade fewer: the SELL signalled at 11:00 UTC on 2025-06-26 no longer hits its SL inside the entry candle and runs to TP instead, so the 19:00 UTC SELL that day is skipped as “in a position”. Changing costs can change the trade list itself. A method on M5 or M15 with a tight SL is far more sensitive.
cd C:\trading-agent-lab
notepad src\bt_xau_01.py
notepad tests\test_bt_xau_01.py
.venv\Scripts\python -m pytest -q tests\test_xau_01.py tests\test_mt5_candles.py tests\test_indicators_independent.py tests\test_bt_xau_01.py
.venv\Scripts\python -m pytest -q tests
git add src\bt_xau_01.py src\indicator_diffs.py tests\test_indicators_independent.py tests\test_bt_xau_01.py
git commit -m "Lock backtest code xau-01-v1 before the first run"src/bt_xau_01.py:
# src/bt_xau_01.py: backtest spec xau-01-v1 with backtesting.py on an MT5-style H1 CSV, with costs.
# Reads files only: no network, no orders. backtesting.py is AGPL-3.0: run it on your own machine only.
# Run: .venv\Scripts\python src\bt_xau_01.py dev (holdout: exactly once, after everything is locked)
import csv
import hashlib
import math
import sys
from datetime import datetime
from pathlib import Path
import pandas as pd
from backtesting import Backtest, Strategy
from scipy import stats
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT)) # so src.* imports work when run as python src/...
from src.lot import lot_round_down # rounds down to steps of 0.01 lot
from src.mt5_candles import read_mt5_candles
from src.xau_01 import DECIMALS, MIN_CANDLES, atr, ema, evaluate, price_levels # the spec's own functions
DATA = ROOT / "data" / "xauusd_h1_backtest.csv"
DATA_SHA256 = "9D050CA0914090DD6F874446E6FDE2B683789DAE379BBC12534EFBF747C67C26" # paste your Get-FileHash result
PERIODS = {"dev": ("2025-01-01", "2026-01-01"), "holdout": ("2026-01-01", "2027-01-01")}
CASH, RISK_USD, MARGIN = 10_000, 100, 0.05 # paper capital USD; fixed risk per trade; margin 1:20
SLIP_USD, FEE_USD = 0.10, 0.07 # slippage per fill; round-trip commission (USD/oz, assumed)
DAILY_CAP, DD_CAP = 2.0, 20.0 # % · example thresholds from the stop-conditions table: use yours
VERSION = "backtest-xau-01-v1" # change the backtest spec, change the version
LOG_COLUMNS = ["date", "version", "change", "data", "trades", "mean_r", "interval_95", "t", "run_by", "note"]
OUT = ROOT / "reports"
def check_hash():
h = hashlib.sha256(DATA.read_bytes()).hexdigest()
if h != DATA_SHA256.lower():
raise SystemExit(f"Data file changed (SHA-256 {h[:12]}...): the backtest spec locked a different file. Stop.")
return h
def result_file(period, kind):
"""reports/<kind>-xau-01-<period>.csv, written by a backtest run; stop and name the missing step if absent."""
f = OUT / f"{kind}-xau-01-{period}.csv"
if f.exists():
return f
if period == "holdout":
raise SystemExit(f"No reports/{f.name}: the holdout hasn't been opened. Run holdout only at the unsealing "
"step (src/bt_xau_01.py holdout, exactly once); for now run dev.")
raise SystemExit(f"No reports/{f.name}: run src/bt_xau_01.py {period} first.")
def add_signals(df):
"""EMA and ATR rounded as the spec says, and a Signal column scored by the spec's own evaluate().
Signal sits on candle [1]: 1 = BUY, -1 = SELL, 0 = stay out. Position state is left to the backtest."""
closes = df["Close"].tolist()
candles = [{"h": h, "l": l, "c": c} for h, l, c in zip(df["High"], df["Low"], df["Close"])]
df = df.assign(C=df["Close"].round(DECIMALS), E21=[round(x, DECIMALS) for x in ema(closes, 21)],
E55=[round(x, DECIMALS) for x in ema(closes, 55)], E200=[round(x, DECIMALS) for x in ema(closes, 200)],
ATR14=[math.nan if x is None else round(x, 5) for x in atr(candles)])
c, e21, e55, e200 = (df[k].tolist() for k in ("C", "E21", "E55", "E200"))
signal = [0] * len(df)
for i in range(MIN_CANDLES, len(df) - 1): # needs the next (entry) candle in the file
c2 = {"c": c[i - 1], "ema21": e21[i - 1]}
c1 = {"c": c[i], "ema21": e21[i], "ema55": e55[i], "ema200": e200[i]}
act = evaluate(c2, c1, df.index[i + 1], has_position=False)["action"] # entry open time is calendar, not price
signal[i] = {"BUY": 1, "SELL": -1}.get(act, 0)
return df.assign(Signal=signal)
def costs():
"""Spread and slippage as ratios of price (backtesting.py needs ratios), measured on the development period."""
dev = read_mt5_candles(DATA, until_utc=PERIODS["dev"][1])
win = dev[(dev.index.hour >= 7) & (dev.index.hour < 21)] # candles opening in the entry window
return float((win["Spread"] / win["Close"]).median()), SLIP_USD / float(win["Close"].median())
def sl_tp_levels(side, c1, s, sl_usd, a):
"""SL and TP on the CSV's BID scale, via the spec's price_levels. c1: close of [1]; s, sl_usd: spread, slippage (USD/oz).
BUY enters at Ask + slippage and exits at Bid: compare straight with BID candles. SELL enters at Bid - slippage
but exits at Ask = Bid + s, so on BID candles a SELL's SL and TP sit one spread lower."""
if side > 0:
_, sl, tp = price_levels("BUY", None, c1 + s + sl_usd, a)
return sl, tp
_, sl, tp = price_levels("SELL", c1 - sl_usd, None, a)
return round(sl - s, DECIMALS), round(tp - s, DECIMALS)
class Xau01(Strategy):
spread_ratio = 0.0 # spread / price
slip_ratio = 0.0 # slippage / price, per fill
def init(self): # indicators and signals are precomputed by the spec's functions (add_signals)
self.skipped = {"in_position": 0, "lot_below_0_01": 0}
def next(self):
side = self.data.Signal[-1]
if side == 0:
return
if self.position: # one position at most
self.skipped["in_position"] += 1
return
c1, a = self.data.C[-1], self.data.ATR14[-1]
s, slip = self.spread_ratio * c1, self.slip_ratio * c1 # back to USD/oz at the current price
lot = lot_round_down(RISK_USD, 1.5 * a, 100) # XAUUSD: 1 lot = 100 oz
if lot == 0:
self.skipped["lot_below_0_01"] += 1 # 0.01 lot already exceeds the risk budget: skip
return
sl, tp = sl_tp_levels(side, c1, s, slip, a)
tag = self.data.index[-1].strftime("%Y-%m-%dT%H:%M:%SZ") # open time of candle [1]
if side > 0:
self.buy(size=round(lot * 100), sl=sl, tp=tp, tag=tag)
else:
self.sell(size=round(lot * 100), sl=sl, tp=tp, tag=tag)
def run(period):
start, end = PERIODS[period]
df = add_signals(read_mt5_candles(DATA, until_utc=end)) # dev never reads a candle from the holdout onward
start = max(pd.Timestamp(start), df.index[MIN_CANDLES + 1]) # the first 1,500 candles only warm up EMA200
entry = df.index.to_series().shift(-1) # entry candle open time of each candle [1]
inside = ((entry >= start) & (entry < pd.Timestamp(end))).to_numpy()
df["Signal"] = df["Signal"].where(inside, 0) # periods go by the entry candle
df = df.iloc[max(int(inside.argmax()) - 1, 0):] # backtesting.py never calls next() on the first row
spread_ratio, slip_ratio = costs()
bt = Backtest(df, Xau01, cash=CASH, spread=spread_ratio + 2 * slip_ratio, # entry and exit slippage in the spread
commission=lambda size, price: abs(size) * FEE_USD / 2, # USD/oz per side: charged in and out
margin=MARGIN, finalize_trades=True) # open at the last candle: close at close
return df, start, bt.run(spread_ratio=spread_ratio, slip_ratio=slip_ratio), spread_ratio, slip_ratio
def trade_table(res, df):
t = res["_trades"]
buy = t["Size"] > 0
risk = 1.5 * df["ATR14"].reindex(pd.to_datetime(t["Tag"]).dt.tz_localize(None)).to_numpy() # 1R = SL distance
reason = ["sl" if (b and x <= sl) or (not b and x >= sl) else "tp" if (b and x >= tp) or (not b and x <= tp)
else "end-of-data" for b, x, sl, tp in zip(buy, t["ExitPrice"], t["SL"], t["TP"])]
return pd.DataFrame({"signal_utc": t["Tag"], "entry_utc": t["EntryTime"], "exit_utc": t["ExitTime"],
"side": ["BUY" if b else "SELL" for b in buy], "oz": t["Size"].abs(),
"entry_price": t["EntryPrice"].round(3), "exit_price": t["ExitPrice"].round(3), "sl": t["SL"],
"tp": t["TP"], "pnl_usd": t["PnL"].round(2), "fee_usd": t["Commission"].round(2),
"r": (t["PnL"] / (t["Size"].abs() * risk)).round(4), "reason": reason})
def confidence_interval(r):
"""Mean R, its 95% interval from the t distribution, and the t of the mean."""
n, mean = len(r), float(r.mean())
se = float(r.std(ddof=1)) / math.sqrt(n)
half = stats.t.ppf(0.975, n - 1) * se
return n, mean, mean - half, mean + half, mean / se
def append_trial_log(log, row):
"""Add one row to the trial log; create it with the same header if it doesn't exist yet."""
old = log.read_bytes() if log.exists() else b""
with open(log, "a", newline="", encoding="utf-8") as f:
if not old.strip():
f.write(",".join(LOG_COLUMNS) + "\r\n")
elif not old.endswith(b"\n"):
f.write("\r\n") # Notepad may save the last line without a line break
csv.writer(f).writerow(row)
def main():
period = sys.argv[1] if len(sys.argv) > 1 else "dev"
if period not in PERIODS:
raise SystemExit(f"Period must be one of {list(PERIODS)}")
h = check_hash()
OUT.mkdir(exist_ok=True)
log = OUT / "trial-log.csv"
old = list(csv.DictReader(log.read_text(encoding="utf-8-sig").splitlines())) if log.exists() else []
if period == "holdout":
n_open = 1 + sum((x.get("data") or "").startswith("holdout") for x in old) # every version counts
print(f"OPENING THE HOLDOUT, time {n_open}. From the second time on, this period is no longer unused data.")
df, start, res, spread_ratio, slip_ratio = run(period)
trades = trade_table(res, df)
n, mean, low, high, t = confidence_interval(trades["r"])
append_trial_log(log, [datetime.now().strftime("%Y-%m-%d %H:%M"), VERSION, # logged before printing: seen = tried
f"slippage {SLIP_USD} USD, fee {FEE_USD} USD/oz, spread {spread_ratio:.6f} x price",
f"{period} {start:%Y-%m-%d}..{df.index[-1]:%Y-%m-%d} SHA {h[:12]}", n, f"{mean:.3f}",
f"{low:.3f}..{high:.3f}", f"{t:.2f}", "me", "src/bt_xau_01.py"])
price = float(df["Close"].median())
print(f"Data {DATA.name} | SHA-256 {h[:12]}... | entry candles {start} to {df.index[-1]} UTC")
print(f"Costs at median price {price:.0f}: spread {spread_ratio:.6f} x price = {spread_ratio * price:.2f} USD | slippage "
f"{slip_ratio:.7f} x price = {slip_ratio * price:.2f} USD per fill | commission {FEE_USD:.2f} USD/oz round trip")
for k in ("# Trades", "Equity Final [$]", "Return [%]", "Max. Drawdown [%]", "Commissions [$]", "Profit Factor"):
print(f"{k}: {res[k]:.2f}" if isinstance(res[k], float) else f"{k}: {res[k]}")
sk = res["_strategy"].skipped
print(f"Signals skipped: in a position {sk['in_position']} | 0.01 lot over {RISK_USD} USD risk {sk['lot_below_0_01']}")
print(f"{n} trades | mean R {mean:+.3f} | 95% interval [{low:+.3f}; {high:+.3f}] | t {t:.2f} | "
f"median {trades['r'].median():+.3f} | total {trades['r'].sum():+.2f} R | winners {int((trades['r'] > 0).sum())}/{n}")
print("Exit reasons:", trades["reason"].value_counts().to_dict())
eq = res["_equity_curve"]["Equity"] # equity at each H1 close
by_day = eq.groupby((eq.index + pd.Timedelta(hours=1)).date) # UTC day of the candle's close
day_start = by_day.last().shift(1).fillna(CASH) # start-of-day equity = previous day's last
day_loss = (1 - by_day.min() / day_start) * 100 # deepest intraday loss, %
dd = (1 - eq / eq.cummax()) * 100 # % below the equity peak
hit = dd[dd >= DD_CAP]
run_len = longest = 0
for r in trades["r"]:
run_len = run_len + 1 if r < 0 else 0
longest = max(longest, run_len)
print(f"Stop conditions (example thresholds): max drawdown {dd.max():.2f}% "
f"({f'first hit {DD_CAP:g}% at {hit.index[0]}' if len(hit) else f'never reached {DD_CAP:g}%'}) "
f"| longest losing streak {longest}")
print(f"Daily cap {DAILY_CAP:g}% of start-of-day equity (UTC day): hit on {int((day_loss >= DAILY_CAP).sum())} days "
f"(worst {day_loss.max():.2f}%)")
trades.to_csv(OUT / f"trades-xau-01-{period}.csv", index=False, encoding="utf-8-sig")
eq.to_csv(OUT / f"equity-xau-01-{period}.csv", encoding="utf-8-sig")
print(f"Wrote reports/trades-xau-01-{period}.csv, reports/equity-xau-01-{period}.csv; added a row to "
"reports/trial-log.csv. Simulation on historical data, not investment advice.")
if __name__ == "__main__":
main()tests/test_bt_xau_01.py. Three tests share one development run on your file
and check the rules on the trade list it produces; one checks that the log
appends correctly to the trial log you already have.
# tests/test_bt_xau_01.py: check the cost model and the spec's rules on the trade list the backtest prints.
import csv
import pandas as pd
import pytest
from src.bt_xau_01 import PERIODS, append_trial_log, run, sl_tp_levels, trade_table
@pytest.mark.parametrize("side", [1, -1])
def test_loss_at_sl_and_gain_at_tp_symmetric_both_sides(side):
c1, s, slip, a = 4104.327, 0.40, 0.10, 13.98436 # numbers in the style of a real BUY case, assumed spread
sl, tp = sl_tp_levels(side, c1, s, slip, a)
fill = c1 + s + 2 * slip if side > 0 else c1 - s - 2 * slip # backtesting.py fills at price x (1 +/- spread incl. slippage)
assert abs((fill - sl) * side - (1.5 * a + slip)) < 0.002 # loss at SL = 1.5 ATR + exit slippage
assert abs((tp - fill) * side - (3 * a - slip)) < 0.002 # gain at TP = 3 ATR - slippage already charged
@pytest.fixture(scope="module")
def result():
df, start, res, _, _ = run("dev")
return df, start, res, trade_table(res, df)
def test_entries_only_in_hours_and_in_period(result):
_, start, _, trades = result
entry = pd.to_datetime(trades["entry_utc"])
assert len(trades) > 0
assert ((entry.dt.hour >= 7) & (entry.dt.hour < 21)).all() # [07:00, 21:00) UTC by the entry candle
assert (entry.dt.day_of_week != 4).all() # no UTC Friday
assert (entry >= start).all() and (entry < pd.Timestamp(PERIODS["dev"][1])).all()
def test_entry_on_next_candle_and_one_position_at_most(result):
df, _, _, trades = result
signal = pd.to_datetime(trades["signal_utc"]).dt.tz_localize(None)
pos = df.index.get_indexer(signal)
assert (df.index[pos + 1] == pd.to_datetime(trades["entry_utc"])).all() # fills at the open after [1]
assert (pd.to_datetime(trades["entry_utc"]).iloc[1:].to_numpy()
>= pd.to_datetime(trades["exit_utc"]).iloc[:-1].to_numpy()).all() # next trade opens after the last closed
def test_log_appends_to_existing_file(tmp_path):
p = tmp_path / "trial-log.csv" # saved by Notepad, last line without a line break
p.write_text("date,version,change,data,trades,mean_r,interval_95,t,run_by,note\n"
"2026-11-24,v1,first,2023-01..2025-12,60,0.250,-0.060..0.560,1.61,me,x", encoding="utf-8")
append_trial_log(p, ["2026-11-25 10:00", "backtest-xau-01-v1", "slippage 0.1 USD", "dev", 72, "0.255",
"-0.093..0.604", "1.46", "me", "src/bt_xau_01.py"])
rows = list(csv.DictReader(p.read_text(encoding="utf-8-sig").splitlines()))
assert len(rows) == 2 and rows[0]["note"] == "x" and rows[1]["version"] == "backtest-xau-01-v1"
def test_every_trade_pays_costs(result):
df, _, res, trades = result
assert res["Commissions [$]"] > 0 and (trades["fee_usd"] > 0).all()
opens = df["Open"].reindex(pd.to_datetime(trades["entry_utc"])).to_numpy()
assert ((trades["entry_price"].to_numpy() > opens) == (trades["side"] == "BUY").to_numpy()).all() # BUY above BID open
sl = trades[trades["reason"] == "sl"]
assert sl["r"].median() < -1 # most SL trades lose a little more than 1R; next-open entries vary a bitThe first pytest line runs these four files only and prints 32 passed: 9
spec tests, 9 indicator tests, 8 time tests and 6 backtest tests. The second
runs the whole tests folder, so it passes more; it’s fine when the last
line has no failed or error. A Pandas4Warning from backtesting.py may
appear (see the install table). The commit shows 4 files changed.
| Cost | In reality | Here | In backtesting.py |
|---|---|---|---|
| Spread | Ask − Bid at the fill, changing all the time | Development median spread ÷ price: 0.000168 | spread parameter |
| Slippage | Depends on liquidity and news | 0.10 USD/oz per fill, in and out | Added twice to spread |
| Commission | The broker’s fee schedule | 0.07 USD/oz round trip (assumed) | commission function, 0.035 per side |
| Swap | Overnight holding fee | Not counted | Listed as a model limit |
| You see | Cause | Fix |
|---|---|---|
TypeError: Can't instantiate abstract class Xau01 without an implementation for abstract method 'init' |
The Strategy class lost its init |
Keep init, even with precomputed indicators |
Data file changed (SHA-256 ...) ... Stop. |
The data file was overwritten, or your hash isn’t in DATA_SHA256 yet |
Restore the locked file; new data means spec v2 |
UserWarning: ... Broker canceled the order due to insufficient margin |
Not enough margin for the size | Check CASH, MARGIN, RISK_USD; never change them after locking |
UserWarning: Some prices are larger than initial cash value ... |
Price above the paper capital (BTCUSD); backtesting.py sizes in whole units | Trade a scaled unit for such symbols |
PermissionError: ... reports\trades-xau-01-*.csv |
The CSV is open in Excel and locked | Close Excel; open CSVs in Notepad |
Every trade, R and the interval: development first, then the holdout once
Besides backtesting.py’s summary, the script computes R for every trade: net
P&L divided by size times the initial SL distance, 1.5 × ATR14 read on [1].
The list comes from stats['_trades'] and goes to
reports/trades-xau-01-dev.csv. backtesting.py documents _trades and
_equity_curve only through examples, which is one more reason to pin the
version and recheck the column names on every upgrade.
Column in reports/trades-xau-01-*.csv |
Meaning |
|---|---|
signal_utc, entry_utc, exit_utc |
Open of [1], fill time (next open), exit time; all UTC |
side, oz |
BUY or SELL; ounces (0.01 lot = 1 oz) |
entry_price, exit_price |
Fill with spread and slippage; exit on the BID scale |
sl, tp |
Levels on the BID scale; a SELL’s already one spread lower |
pnl_usd, fee_usd |
Net P&L after commission; the commission |
r, reason |
P&L over the initial SL distance; sl, tp or end-of-data (open at the last candle, closed at its close) |
Run development and open the trade list:
cd C:\trading-agent-lab
.venv\Scripts\python src\bt_xau_01.py dev
notepad reports\trades-xau-01-dev.csvOn the sample:
Data xauusd_h1_backtest.csv | SHA-256 9d050ca09140... | entry candles 2025-04-03 08:00:00 to 2025-12-31 21:00:00 UTC
Costs at median price 3391: spread 0.000168 x price = 0.57 USD | slippage 0.0000299 x price = 0.10 USD per fill | commission 0.07 USD/oz round trip
# Trades: 72
Equity Final [$]: 11799.91
Return [%]: 18.00
Max. Drawdown [%]: -3.82
Commissions [$]: 28.35
Profit Factor: 1.34
Signals skipped: in a position 30 | 0.01 lot over 100 USD risk 0
72 trades | mean R +0.255 | 95% interval [-0.093; +0.604] | t 1.46 | median -1.006 | total +18.38 R | winners 31/72
Exit reasons: {'sl': 41, 'tp': 30, 'end-of-data': 1}
Stop conditions (example thresholds): max drawdown 3.82% (never reached 20%) | longest losing streak 4
...72 trades, mean R +0.255, 95% interval −0.093 to +0.604, t = 1.46 (how many standard errors the mean sits from 0). The median is −1.006 because most trades lose a full 1R. The interval contains 0, so the true mean R could still be zero or negative: by the threshold written in advance there is no evidence of an edge, even though the equity curve rose 18%. The luck-or-skill post explains why 72 trades is few and how to read the interval. The 31/72 win rate is only a sanity check; always read it with mean R and the interval.
The line left out above counts days that hit the 2% daily cap (UTC days, as in the stop-conditions table); on the sample it was rare in both periods.
Trying variants. A 0.30 USD slippage or a 2 ATR SL runs on development
only. Each run appends a row to reports/trial-log.csv with the same columns
as the luck-or-skill post’s trial log. The row count is the number of tries m
that raises the t threshold. If you choose something other than v1: write it
as a new spec (specs/backtest-xau-01-v2.md, change VERSION), commit, then
open the holdout exactly once. The script counts holdout openings and warns
from the second one on.
Opening the holdout. Only at the very end, after the ledger comparison, the report and the chart below are done for development. Check the code hasn’t changed since the lock, commit the trial log, open the holdout once:
git status --porcelain -- src tests specs
git add reports\trial-log.csv
git commit -m "Trial log before opening the holdout"
.venv\Scripts\python src\bt_xau_01.py holdout
notepad reports\trial-log.csv
git add reports\trial-log.csv reports\trades-xau-01-holdout.csv
git commit -m "Open holdout xau-01-v1"On the sample:
OPENING THE HOLDOUT, time 1. From the second time on, this period is no longer unused data.
Data xauusd_h1_backtest.csv | SHA-256 9d050ca09140... | entry candles 2026-01-01 00:00:00 to 2026-10-30 09:00:00 UTC
Costs at median price 4465: spread 0.000168 x price = 0.75 USD | slippage 0.0000299 x price = 0.13 USD per fill | commission 0.07 USD/oz round trip
# Trades: 72
Equity Final [$]: 8120.02
Return [%]: -18.80
Max. Drawdown [%]: -20.65
Commissions [$]: 16.59
Profit Factor: 0.53
Signals skipped: in a position 32 | 0.01 lot over 100 USD risk 3
72 trades | mean R -0.299 | 95% interval [-0.601; +0.002] | t -1.98 | median -1.006 | total -21.53 R | winners 17/72
Exit reasons: {'sl': 55, 'tp': 17}
Stop conditions (example thresholds): max drawdown 20.65% (first hit 20% at 2026-10-21 11:00:00) | longest losing streak 13
...| On the sample | Development (2025-04-03 to 2025-12-31) | Holdout (2026-01-01 to 2026-10-30) |
|---|---|---|
| Trades | 72 | 72 |
| Mean R [95% interval] | +0.255 [−0.093; +0.604] | −0.299 [−0.601; +0.002] |
| t of mean R | 1.46 | −1.98 |
| Total R | +18.38 | −21.53 |
| Exit reasons | 41 SL, 30 TP, 1 end of data | 55 SL, 17 TP |
| Signals skipped: in a position; lot | 30; 0 | 32; 3 |
| Verdict by the written threshold | No evidence yet | No evidence yet |
The development result didn’t hold. Paper capital fell 18.80%, with a 20.65% drawdown from the peak at one point. The verdict, by the threshold written before any number: no evidence; don’t run XAU-01 v1 on demo. A longer run of the same rule, 869 trades from 2018 to late 2026 at similar costs, points the same way: mean R −0.06.
A note on honesty. While this code was being debugged, the sample’s holdout
was run more than once, on the same file, rule, costs and period; only the
printing, the log format and the opening counter changed between runs, and
every run gave the same 72 trades and −0.299. The “time 1” above comes from a
fresh log. By the definition at the top, the sample’s 2026 is no longer
unused data. On your own file, finish debugging on development before you
open the holdout, and never delete a row of reports/trial-log.csv.
Compare with a second engine: what matches, what doesn’t, no forcing
A second implementation of the same rule is the best check of the first. The reference here is a ledger of XAU-01 computed by another engine: fills on M5 candles built from BID and ASK quotes, the real spread at each moment, commission 0.07 USD/oz round trip and 0.10 USD/oz slippage per market or SL fill. This post’s Python version runs on H1 with a fixed-ratio spread. Two rulers measuring one rule: comparable, and worth comparing.
Save the reference as one CSV per year, data/ledger-xau-01-<year>.csv, with
columns signalT, side, decisionT, entryT, entry, sl, tp, exitT, exit, reason, R (side 1 or −1). src/compare_ledger.py matches on one key: the
UTC open time of candle [1] and the side. The reference ends after
2026-11-11, so backtest trades after that are left out of the comparison and
counted.
Only save the 2026 file after you’ve opened the holdout: looking at a 2026 ledger first spends the holdout.
cd C:\trading-agent-lab
Move-Item "$HOME\Downloads\ledger-xau-01-2025.csv" data\ledger-xau-01-2025.csv
notepad src\compare_ledger.py
.venv\Scripts\python src\compare_ledger.py dev
git add src\compare_ledger.py data\ledger-xau-01-2025.csv
git commit -m "Compare with reference ledger 2025"src/compare_ledger.py:
# src/compare_ledger.py: compare the backtest's trade list with a reference ledger of the same rule from another engine
# (CSV per year in data/ledger-xau-01-<year>.csv, columns signalT, side, ..., reason, R). Reads files only.
# Key: (open time of signal candle [1] in UTC, side). Run: .venv\Scripts\python src\compare_ledger.py dev
import sys
from pathlib import Path
import pandas as pd
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.bt_xau_01 import result_file
LEDGER_END = "2026-11-12 00:00:00" # the reference ledger ends after 2026-11-11; change it when the ledger is extended
def main():
period = sys.argv[1] if len(sys.argv) > 1 else "dev"
bt = pd.read_csv(result_file(period, "trades"), encoding="utf-8-sig")
eq = pd.read_csv(result_file(period, "equity"), index_col=0, parse_dates=True, encoding="utf-8-sig")
files = sorted((ROOT / "data").glob("ledger-xau-01-*.csv"))
if not files:
raise SystemExit("No data/ledger-xau-01-<year>.csv: save the reference ledger (CSV per year) there first.")
ref = pd.concat([pd.read_csv(p) for p in files], ignore_index=True)
ref["signal_utc"] = ref["signalT"].str.replace("Z", "", regex=False).str.replace("T", " ", regex=False)
bt["signal_utc"] = bt["signal_utc"].str.replace("Z", "", regex=False).str.replace("T", " ", regex=False)
ref["side"] = ref["side"].map({1: "BUY", -1: "SELL"})
lo, hi = str(eq.index[1]), str(eq.index[-1]) # first and last candle [1] the backtest considered
after = int((bt["signal_utc"] >= LEDGER_END).sum())
bt = bt[bt["signal_utc"] < LEDGER_END] # the ledger doesn't have these candles yet: not a mismatch
ref = ref[(ref["signal_utc"] >= lo) & (ref["signal_utc"] <= hi) & (ref["signal_utc"] < LEDGER_END)]
if ref.empty:
raise SystemExit(f"The ledger has no trades from {lo} to {hi} UTC: add the year file for this period.")
m = bt.merge(ref, on=["signal_utc", "side"], how="outer", indicator=True, suffixes=("", "_ref"))
both = m[m["_merge"] == "both"]
print(f"{period}: candle [1] from {lo} to {hi} UTC | backtest {len(bt)} trades | ledger {len(ref)} trades")
print(f"Left out {after} backtest trades with candle [1] from {LEDGER_END} UTC: not in the ledger yet")
print(f"Matched (same candle [1], same side): {len(both)} | backtest only: {int((m['_merge'] == 'left_only').sum())} "
f"| ledger only: {int((m['_merge'] == 'right_only').sum())}")
print(f"Of {len(both)} matched: same exit reason {int((both['reason'] == both['reason_ref']).sum())} | "
f"mean R backtest {both['r'].mean():+.3f}, ledger {both['R'].mean():+.3f}")
print(f"Whole range: mean R backtest {bt['r'].mean():+.3f} ({len(bt)} trades), ledger {ref['R'].mean():+.3f} ({len(ref)} trades)")
for _, x in m[m["_merge"] != "both"].sort_values("signal_utc").iterrows():
print(f" {x['signal_utc']} {x['side']} | {'backtest only' if x['_merge'] == 'left_only' else 'ledger only'}")
m.to_csv(ROOT / "reports" / f"compare-ledger-{period}.csv", index=False, encoding="utf-8-sig")
if __name__ == "__main__":
main()On the sample, development:
dev: candle [1] from 2025-04-03 07:00:00 to 2025-12-31 21:00:00 UTC | backtest 72 trades | ledger 72 trades
Left out 0 backtest trades with candle [1] from 2026-11-12 00:00:00 UTC: not in the ledger yet
Matched (same candle [1], same side): 72 | backtest only: 0 | ledger only: 0
Of 72 matched: same exit reason 71 | mean R backtest +0.255, ledger +0.242
Whole range: mean R backtest +0.255 (72 trades), ledger +0.242 (72 trades)All 72 match on candle [1] and side; 71 share the exit reason. The remaining one was signalled at 16:00 UTC on 2025-12-31: Python closes it when the development data ends, the ledger lets it run into 2026. Among trades with the same exit, Python’s TP exits are a mean 0.007 R lower, because this post charges slippage on exits too.
After opening the holdout, add the 2026 ledger and run the comparison, report and chart for it:
Move-Item "$HOME\Downloads\ledger-xau-01-2026.csv" data\ledger-xau-01-2026.csv
.venv\Scripts\python src\compare_ledger.py holdout
.venv\Scripts\python src\qs_report.py holdout
.venv\Scripts\python src\plot_trades.py holdout 2026-02
.venv\Scripts\python src\check_html.py reports\*.html
start reports\qs-xau-01-holdout.html
start reports\trades-xau-01-holdout-2026-02.html
git add data\ledger-xau-01-2026.csv
git commit -m "Compare with reference ledger 2026"On the sample:
holdout: candle [1] from 2025-12-31 21:00:00 to 2026-10-30 09:00:00 UTC | backtest 72 trades | ledger 70 trades
Left out 0 backtest trades with candle [1] from 2026-11-12 00:00:00 UTC: not in the ledger yet
Matched (same candle [1], same side): 68 | backtest only: 4 | ledger only: 2
Of 68 matched: same exit reason 67 | mean R backtest -0.302, ledger -0.256
Whole range: mean R backtest -0.299 (72 trades), ledger -0.277 (70 trades)
2026-02-02 13:00:00 SELL | ledger only
2026-02-25 11:00:00 BUY | backtest only
2026-02-26 09:00:00 BUY | backtest only
2026-02-26 15:00:00 BUY | backtest only
2026-03-23 15:00:00 SELL | ledger only
2026-03-24 12:00:00 SELL | backtest onlySix differences, each with a cause you can check:
| Case (candle [1], UTC) | Where | Cause | Check with |
|---|---|---|---|
| 2026-02-02 13:00 SELL | Ledger only | ATR14 122.49 USD: 0.01 lot risks 183.74 USD, over 100 | The 0.01 lot over 100 USD risk 3 line |
| 2026-02-24 17:00 BUY | Both, different exit | SL 5,127.319 vs 5,127.008; the 23:00 candle fell to 5,127.048 | The 2026-02 chart; the candle row in the CSV |
| 2026-02-25 11:00, 02-26 09:00, 02-26 15:00 BUY | Python only | Python was flat at 23:00 on 02-24; the ledger held until 13:25 on 02-27 | exit_utc and exitT |
| 2026-03-23 15:00 SELL | Ledger only | ATR14 94.69 USD: 0.01 lot risks 142.04 USD | As 02-02 |
| 2026-03-24 12:00 SELL | Python only | The ledger still held the 03-23 trade until 23:25 on 03-24 | exitT |
The ledger works in R and has no lot rule, so it keeps the two high-ATR trades Python skips. The 02-24 case is the cost model: the proportional spread plus slippage sat 0.31 USD above what the M5 engine used at that moment. The 23:00 candle, first after the break, hit Python’s SL and stopped 0.04 USD short of the ledger’s; the ledger’s trade ran to TP on 02-27 (+2.00 R) while Python’s lost −1.00 R. The Python-only trades follow from those two: flat early, Python took three more BUYs, and on 03-24 Python was free while the ledger still held the 03-23 SELL.
Don’t force a match. Narrowing the spread so 02-24 agrees would be tuning the model to the answer, on the very data under test. Write down each cause and keep the locked cost model. On your broker’s file there’ll be more differences: prices a few tens of cents apart, server time, the broker’s own spread. The reading is the same: every difference needs a cause you can check. If one has none yet, open the chart before trusting either side.
| You see | Cause | Fix |
|---|---|---|
No reports/trades-xau-01-holdout.csv |
The holdout isn’t open yet | Run dev now; holdout comes last |
No data/ledger-xau-01-<year>.csv |
Not saved yet, or a wrong name | Save it under that exact name |
Left out N backtest trades ... |
The ledger ends after 2026-11-11 | Normal: they’re not counted as differences |
| Most trades off by exactly 1 hour | Wrong time conversion | Rerun src/mt5_candles.py, fix HOUR_OFFSET or DST_RULE |
| Almost nothing matches | A ledger of another method, variant or cost scenario | Get the XAU-01, fixed SL/TP ledger |
A QuantStats report and a Plotly chart that stay offline
src/qs_report.py takes the backtest’s H1 equity, keeps the last value of
each UTC day (weekends dropped; Sunday evening counts toward Monday), and
passes daily returns to QuantStats. The benchmark is buy-and-hold gold built
from the CSV’s own close column. QuantStats accepts a ticker or a pandas
Series as benchmark; a ticker makes it download prices through yfinance, so
only a Series is passed. Trading days per year also come from the CSV (261),
not QuantStats’ default 252.
Read the report in three parts: equity against gold, drawdown (the fall from a peak), monthly returns. On the sample:
- Development: strategy +18.00%, gold buy-and-hold +38.75%; max drawdown −3.69% against −9.87%. QuantStats measures drawdown on daily closes, so it’s smaller than backtesting.py’s 3.82% on H1 closes.
- Holdout: −18.80% against −7.57%; drawdown −20.18% against −27.69%.
An annualised Sharpe (return over volatility) looks persuasive but is weak evidence over a short period, so the script also prints the t of daily returns: 1.57 over 193 days and −1.78 over 216 days, close to the t of mean R above. A few report ratios are per day, not per trade: skip them and read R.
Check that nothing calls the network, three ways:
- Run the script with the network off. With every Python network path blocked (sockets, the curl_cffi library yfinance uses, the price downloaders of yfinance and QuantStats), the report still builds.
src/check_html.pyparses the HTML and lists external resources declared in tags (script, CSS, image, icon, iframe). It can’t see what JavaScript creates at open time. QuantStats 0.0.86’s file has an icon line pointing to qtpylib.io, fetched on every open;qs_report.pyremoves it, and the count drops to 0. The quantstats.io link at the top only opens on a click.- Open the file in Chrome with Wi-Fi off; the charts must all show. Or press F12, open the Network tab, reload: no http or https rows.
Eyeball trades with src/plot_trades.py. It draws one month of H1
candles with the three EMAs; a triangle at the entry candle’s open, an X at
the exit, red dotted SL and green dotted TP. Hover a triangle for the fill,
R and exit reason. write_html(..., include_plotlyjs=True) copies plotly.js
into the file, so the 4.9 MB file opens offline; "cdn" makes it small but
fetches plotly.js from cdn.plot.ly on every open.
This post doesn’t use backtesting.py’s own bt.plot(), because its file
calls the network on every open. By default it loads BokehJS from
cdn.bokeh.org; BOKEH_RESOURCES=inline removes only that. Version 0.6.6
also injects JavaScript that creates a hidden iframe to kernc.github.io, a
hit-counter page running Google Analytics, every time the file opens online.
Check five random trades from the list: the triangle sits on the candle right after [1]; the three EMAs are stacked the right way; the exit sits on the SL or TP line. One H1 candle can touch both SL and TP, like 18:00 UTC on 2025-09-17. backtesting.py can’t know the order inside the candle and checks SL first; the M5 ledger also gives SL for that trade.
Create three files, run them for development, open the report and lock the
code. start opens a file in the default browser. Before the holdout is
open, check_html.py lists only the two development files.
cd C:\trading-agent-lab
notepad src\qs_report.py
notepad src\plot_trades.py
notepad src\check_html.py
.venv\Scripts\python src\qs_report.py dev
.venv\Scripts\python src\plot_trades.py dev 2025-06
.venv\Scripts\python src\check_html.py reports\*.html
start reports\qs-xau-01-dev.html
start reports\trades-xau-01-dev-2025-06.html
git add src\qs_report.py src\plot_trades.py src\check_html.py
git commit -m "QuantStats report and Plotly chart"src/qs_report.py:
# src/qs_report.py: QuantStats report from the backtest's equity. Benchmark: buy-and-hold gold, from the same CSV.
# The benchmark is a pandas Series, not a ticker, so QuantStats downloads no prices. Reads files only.
# Run: .venv\Scripts\python src\qs_report.py dev
import re
import sys
from pathlib import Path
import pandas as pd
import quantstats as qs
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.bt_xau_01 import DATA, result_file
from src.mt5_candles import read_mt5_candles
def daily(s):
"""Last value of each UTC day, weekends dropped: Sunday evening candles count toward Monday."""
d = s.groupby(s.index.normalize()).last()
return d[d.index.day_of_week < 5]
def main():
period = sys.argv[1] if len(sys.argv) > 1 else "dev"
eq = pd.read_csv(result_file(period, "equity"), index_col=0, parse_dates=True, encoding="utf-8-sig")
rets = daily(eq["Equity"]).pct_change().dropna().rename("XAU-01 backtest")
gold_px = daily(read_mt5_candles(DATA)["Close"])
gold = gold_px.pct_change().reindex(rets.index).fillna(0).rename("Gold buy-and-hold (CSV)")
per_year = round(len(gold_px) / ((gold_px.index[-1] - gold_px.index[0]).days / 365.25)) # trading days a year
out = ROOT / "reports" / f"qs-xau-01-{period}.html"
qs.reports.html(rets, benchmark=gold, periods_per_year=per_year, output=str(out),
title=f"XAU-01 {period}: simulation on historical data, not investment advice")
html = out.read_text(encoding="utf-8")
html = re.sub(r'<link rel="shortcut icon"[^>]*>', "", html) # icon pointing to the web: fetched on every open
out.write_text(html, encoding="utf-8")
print(f"{len(rets)} days | {per_year} trading days a year from the CSV")
print(f"Max drawdown: strategy {qs.stats.max_drawdown(rets) * 100:.2f}% | gold {qs.stats.max_drawdown(gold) * 100:.2f}%")
print(f"Return over the period: strategy {qs.stats.comp(rets) * 100:.2f}% | gold {qs.stats.comp(gold) * 100:.2f}%")
print(f"Daily Sharpe annualised ({per_year} sessions): strategy {qs.stats.sharpe(rets, periods=per_year):.2f} "
f"| gold {qs.stats.sharpe(gold, periods=per_year):.2f}")
t = rets.mean() / rets.std() * len(rets) ** 0.5
print(f"t of daily returns: {t:.2f} over {len(rets)} days")
print("Strategy monthly returns (%):")
print((qs.stats.monthly_returns(rets, eoy=False) * 100).round(2).to_string())
print(f"Wrote {out.relative_to(ROOT)}. Simulation on historical data, not investment advice.")
if __name__ == "__main__":
main()src/plot_trades.py:
# src/plot_trades.py: eyeball one month: H1 candles (BID), three EMAs, entries, exits, SL and TP of each trade.
# Writes self-contained HTML: plotly.js sits inside the file, so it opens offline. Reads files only.
# Run: .venv\Scripts\python src\plot_trades.py dev 2025-06
import sys
from pathlib import Path
import pandas as pd
import plotly.graph_objects as go
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.bt_xau_01 import DATA, add_signals, result_file
from src.mt5_candles import read_mt5_candles
def main():
period = sys.argv[1] if len(sys.argv) > 1 else "dev"
month = sys.argv[2] if len(sys.argv) > 2 else "2025-06"
trades = pd.read_csv(result_file(period, "trades"), parse_dates=["entry_utc", "exit_utc"], encoding="utf-8-sig")
df = add_signals(read_mt5_candles(DATA))
df = df[df.index.strftime("%Y-%m") == month]
if df.empty:
raise SystemExit(f"No candles in month {month}: type the month as YYYY-MM, e.g. 2025-06.")
trades = trades[trades["entry_utc"].dt.strftime("%Y-%m") == month]
fig = go.Figure(go.Candlestick(x=df.index, open=df["Open"], high=df["High"], low=df["Low"], close=df["Close"],
name="XAUUSD H1 (BID, UTC)"))
for col, colour in (("E21", "#d97706"), ("E55", "#2563eb"), ("E200", "#7c3aed")):
fig.add_trace(go.Scatter(x=df.index, y=df[col], name="EMA" + col[1:], line={"width": 1, "color": colour}))
for _, x in trades.iterrows():
buy = x["side"] == "BUY"
op = df["Open"].get(x["entry_utc"], x["entry_price"]) # mark the entry at the entry candle's BID open
label = f"{x['side']} {x['entry_utc']:%m-%d %H:%M} | fill {x['entry_price']} | R {x['r']:+.2f} | {x['reason']}"
fig.add_trace(go.Scatter(x=[x["entry_utc"]], y=[op], mode="markers", hovertext=[label], hoverinfo="text",
showlegend=False, marker={"symbol": "triangle-up" if buy else "triangle-down",
"size": 13, "color": "#16a34a" if buy else "#dc2626"}))
fig.add_trace(go.Scatter(x=[x["exit_utc"]], y=[x["exit_price"]], mode="markers", hovertext=[label],
hoverinfo="text", showlegend=False, marker={"symbol": "x", "size": 11, "color": "#111827"}))
for level, colour in ((x["sl"], "#dc2626"), (x["tp"], "#16a34a")):
fig.add_shape(type="line", x0=x["entry_utc"], x1=x["exit_utc"], y0=level, y1=level,
line={"color": colour, "dash": "dot"})
full = pd.date_range(df.index[0], df.index[-1], freq="h")
fig.update_xaxes(rangebreaks=[{"values": full.difference(df.index), "dvalue": 3_600_000}]) # hide breaks, weekends
fig.update_layout(title=f"XAU-01 {period} {month}: {len(trades)} trades (simulation on historical data)",
xaxis_rangeslider_visible=False, height=700)
out = ROOT / "reports" / f"trades-xau-01-{period}-{month}.html"
fig.write_html(out, include_plotlyjs=True) # True: plotly.js inside the file; "cdn" fetches it
print(f"{len(df)} candles, {len(trades)} trades -> {out.relative_to(ROOT)} ({out.stat().st_size / 1e6:.1f} MB)")
if __name__ == "__main__":
main()src/check_html.py:
# src/check_html.py: list external resources declared in HTML tags (script, CSS, image, icon, iframe) that a
# browser fetches BY ITSELF on open. It can't see what JavaScript creates at open time: check that in F12, Network.
# <a> links only open when clicked, so they're counted apart. Run: .venv\Scripts\python src\check_html.py reports\*.html
import glob
import re
import sys
from html.parser import HTMLParser
EXTERNAL = re.compile(r"\s*(https?:)?//", re.I)
class Scan(HTMLParser):
def __init__(self):
super().__init__()
self.auto, self.links, self.tag = [], 0, ""
def handle_starttag(self, tag, attrs):
self.tag = tag
for k, v in attrs:
if k in ("src", "href", "data") and v and EXTERNAL.match(v):
if tag == "a":
self.links += 1
else:
self.auto.append(f"<{tag} {k}={v[:80]}>")
def handle_data(self, data): # CSS in <style>: url(http...) or @import also fetch by themselves
if self.tag == "style":
self.auto += [f"css {m[:80]}" for m in re.findall(r"(?:url\(|@import)\s*['\"]?((?:https?:)?//[^'\")\s]+)", data)]
files = [p for pattern in sys.argv[1:] for p in glob.glob(pattern)]
if not files:
raise SystemExit("No HTML file matched: run from the project folder after creating a report or chart.")
for path in files:
s = Scan()
s.feed(open(path, encoding="utf-8").read())
print(f"{path}: fetches by itself {len(s.auto)} {s.auto[:5]} | links opened only on click: {s.links}")On the sample, qs_report.py for development, then for the holdout:
193 days | 261 trading days a year from the CSV
Max drawdown: strategy -3.69% | gold -9.87%
Return over the period: strategy 18.00% | gold 38.75%
Daily Sharpe annualised (261 sessions): strategy 1.82 | gold 2.19
t of daily returns: 1.57 over 193 days
Strategy monthly returns (%):
JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
2025 0 0 0 -1.77 -0.14 -0.33 3.78 5.5 1.93 2.96 1.33 3.65
Wrote reports\qs-xau-01-dev.html. Simulation on historical data, not investment advice.
216 days | 261 trading days a year from the CSV
Max drawdown: strategy -20.18% | gold -27.69%
Return over the period: strategy -18.80% | gold -7.57%
Daily Sharpe annualised (261 sessions): strategy -1.95 | gold -0.16
t of daily returns: -1.78 over 216 days
Strategy monthly returns (%):
JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
2026 -2.91 -2.01 -1.52 4.78 -3.07 6.48 -9.88 -1.56 -5.21 -4.7 0 0
Wrote reports\qs-xau-01-holdout.html. Simulation on historical data, not investment advice.plot_trades.py for 2025-06 and 2026-02, then check_html.py:
483 candles, 9 trades -> reports\trades-xau-01-dev-2025-06.html (4.9 MB)
458 candles, 5 trades -> reports\trades-xau-01-holdout-2026-02.html (4.9 MB)
reports\qs-xau-01-dev.html: fetches by itself 0 [] | links opened only on click: 1
reports\qs-xau-01-holdout.html: fetches by itself 0 [] | links opened only on click: 1
reports\trades-xau-01-dev-2025-06.html: fetches by itself 0 [] | links opened only on click: 0
reports\trades-xau-01-holdout-2026-02.html: fetches by itself 0 [] | links opened only on click: 0| HTML file | Fetches on open | Note |
|---|---|---|
reports/qs-xau-01-*.html, icon line removed |
0 | 1 link that opens only on click |
| QuantStats 0.0.86 report as written | 1: https://qtpylib.io/favicon.ico |
Calls out on every open |
reports/trades-xau-01-*.html, include_plotlyjs=True |
0 | 4.9 MB, opens offline |
A small Plotly chart with include_plotlyjs="cdn" |
1: https://cdn.plot.ly/plotly-4.1.1.min.js |
7.6 KB |
bt.plot(), default |
2: BokehJS from cdn.bokeh.org and a hidden iframe to kernc.github.io | The iframe page loads Google Analytics. Not used |
bt.plot() with BOKEH_RESOURCES=inline |
1: the hidden iframe (created by JavaScript; check_html.py can’t see it, the Network tab can) |
1.5 MB. Not used |
| You see | Cause | Fix |
|---|---|---|
| A blank chart | Written with "cdn" and no network, or with False (no plotly.js at all) |
Keep include_plotlyjs=True |
No candles in month ... |
Month not in the file, or typed as 2025-6 |
Type YYYY-MM of a month in the CSV |
| A chart with 0 trades | Month outside the trade file’s period | dev: 2025-04 to 2025-12; holdout: 2026-01 to 2026-10 |
No HTML file matched ... |
Wrong folder, or no report yet | Run from C:\trading-agent-lab after making a report |
| No gold line in the report | The gold series doesn’t share dates with the returns | Keep daily() for both series |
MT5 Strategy Tester, the stop table, and LEAN for later
The MT5 Strategy Tester is a third ruler, the closest to reality because it
runs on your broker’s own price history. It needs an EA (an MQL5 program),
so this post doesn’t run it. If you have one, written yourself or by an agent
from specs/xau-01-v1.md and then read line by line, run it only in the
Strategy Tester. The EA gets an input that disables trading by default; the
agent writing it reads no passwords or login files and sends no orders. Never
attach the EA to a chart of any account: demo orders still go through the
human-approved flow of the demo-order post.
Set the Tester up for the same measurement:
- Mode “Every tick based on real ticks”, the closest to real conditions.
- Same symbol, H1, same period; deposit 10,000 USD, leverage 1:20.
- Commission in the advanced settings.
- Delays: No Delay when comparing with Python; try Random Delay later.
- Forward: keep the last part of the period for a forward test, the same idea as the holdout.
The Tester loads extra history before the start date so indicators have enough candles.
Read its report in two steps. First compare four lines: Total Trades, Profit
Factor, Equity Drawdown Relative and Maximum consecutive losses ($), which
correspond to # Trades, Profit Factor, Max. Drawdown [%] and Python’s
longest losing streak. Then compare the first few trades by entry time
(converted to UTC) and side.
Don’t compare with Balance Drawdown Maximal. That line tracks the balance, which only moves when trades close, and picks the largest drop in money. On the sample holdout the balance fell 20.18% (2,052.96 USD) while equity (capital including open P&L) fell 20.65%.
| Strategy Tester | Python version | Note |
|---|---|---|
| Every tick based on real ticks | H1 BID candles, fixed-ratio spread | The Tester uses the broker’s real ticks and spreads |
| Deposit 10,000; Leverage 1:20 | CASH, MARGIN |
Set them equal |
| Commission in advanced settings | FEE_USD = 0.07 USD/oz round trip |
Set them equal |
| Delays: No Delay, Random Delay, Fixed Delay | Slippage added to the spread | No Delay when comparing |
| Forward | Holdout | The last part, tested once |
| Total Trades; Profit Factor | # Trades; Profit Factor |
|
| Equity Drawdown Relative | Max. Drawdown [%] |
Both the largest % fall of equity incl. open P&L; Python only measures at H1 closes |
| Maximum consecutive losses ($) | Longest losing streak | The first number is the count; Maximal consecutive loss (count) is a different quantity |
| You see | Cause | Fix |
|---|---|---|
| Far more or fewer Tester trades; trades off by exactly 1 to 3 hours | The EA uses server time for the hour window and Friday; Python uses UTC | Convert server time to UTC in the EA with the checked HOUR_OFFSET and DST_RULE (in the Tester, TimeGMT() equals server time) |
Tester drawdown differs from Max. Drawdown [%] |
Compared with Balance Drawdown Maximal | Compare with Equity Drawdown Relative |
| The first trades differ, then converge | The Tester’s EMA200 warms up on history before the start | Compare from candle 1,500 of the file |
| Same trades, entry and R a few percent off | Tester fills on real ticks; Python at the H1 open plus fixed costs | Normal; record the median gap, don’t tune |
| One trade exits differently, then later trades shift | The one-position rule, like the 02-24 case | Find the cause of the first difference |
| Overnight trades differ more than intraday ones | Python has no swap | Read swap in the symbol’s Specification; note it as a limit |
The stop table, in advance. The stop-conditions post set two example thresholds: a 2% daily loss against start-of-day equity, which only blocks new orders until the UTC day ends, and a 20% drawdown at 1% risk per trade, which creates STOP. A backtest tells you beforehand how often they’d trip:
| Example threshold | Development | Holdout |
|---|---|---|
| Drawdown from the peak | Max 3.82%, never reached 20% | Hit 20% at 11:00 UTC on 2026-10-21; max 20.65% |
| Longest losing streak | 4 | 13 |
Running v1 on demo through 2026, STOP would have fired on 2026-10-21, when paper capital was about 18% down on the year at 8,166.61 USD. A tighter 10% threshold trips earlier, from 06:00 UTC on 2026-07-29, but the stop-conditions post showed that at 1% risk a 10% threshold also stops 89.8% of sequences of a system with a small edge. Knowing that, decide before running: does your threshold suit the method, or is the method not worth running yet? Don’t decide while losing.
For a bigger engine later, LEAN from QuantConnect is open source under Apache-2.0, while its LEAN CLI tool requires a QuantConnect account in a paid organisation. Not covered here: for an H1 method like XAU-01, backtesting.py with independent references and three cross-checks is enough to decide whether to go on.
Try it: a read-only review of the backtest
Save it as prompts/review-backtest-xau-01.md and give it to an agent with
read-only access to the project:
<role>
You review backtest code you didn't write. Read files only: don't edit, don't install packages, don't run anything that uses the network, don't read .env. No price forecasts, no buy or sell advice.
</role>
<context>
Specs: specs/xau-01-v1.md and specs/backtest-xau-01-v1.md. Code: src/xau_01.py, src/mt5_candles.py, src/bt_xau_01.py and the tests folder. Data: data/xauusd_h1_backtest.csv, H1 BID candles, UTC after conversion with HOUR_OFFSET and DST_RULE. Library backtesting.py 0.6.6: the spread is a ratio of price, commission is charged on entry and on exit, there is no slippage parameter.
</context>
<task>
Find errors in five groups; give file and line for each:
1. Look-ahead: any use of a price from an unclosed candle, or of the entry candle's prices to decide (only its open time may be used).
2. Time: are the hour window and Friday taken from the entry candle, in UTC; is the server-time conversion right for the season.
3. Costs: are spread, slippage and commission charged on every trade; are a SELL's SL and TP one spread lower on the BID scale.
4. Periods: does a development run read any row from the holdout date on; does reports/trial-log.csv show any choice changed after the holdout was opened.
5. Spec: do the conditions, rounding, 1,500 warm-up candles and the rounded-down lot match specs/xau-01-v1.md.
</task>
<output>
A table: group | file:line | problem | evidence (quote the code line) | suggested fix. For a group with nothing found, write "none found". After the table, list what you couldn't check and why. Edit no file.
</output>Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.
The order to work in:
- Lock first: candle file and hash, time zone, both periods, costs and the conclusion threshold; commit.
- Check indicators against independent references (TA-Lib, pandas-ta-classic
with
talib=False) with a written tolerance. - Signals come from the spec’s functions; the backtest library only handles fills, SL, TP, costs and one position. Commit code and tests before the first run.
- Run development; read the trade list, mean R and the interval; every try adds a log row.
- Compare development with a second engine’s ledger; build the QuantStats
report and Plotly chart offline, check the HTML with
check_html.pyand the Network tab. - Commit the trial log, open the holdout exactly once; compare with the 2026 ledger, the Strategy Tester and the stop table; decide by the written threshold.
Key takeaways
- The backtest library only handles fills and costs; the entry conditions stay the spec’s functions, with tests and independent references.
- Read mean R with the trade count and the interval: an interval containing 0 is no evidence, even when paper capital rose.
- Lock data, periods, costs and the threshold before the first run, and open the holdout once; every difference from a second engine needs a cause you can check, never a tweak to make it match.
Comments