Your agent’s XAU-06 signals don’t match the backtest ledger. Is the agent wrong, or are the data and the clock?
This post locks the criteria first, loads the ledger as CSV, measures the broker’s server-time offset day by day, and checks a code version of the rule against the ledger. Only then does the agent run, and you count matches, misses and extras with a cause for each. The easy mistake: measuring the offset once for the whole period, then seeing mismatches, editing the prompt and rerunning on the same ten days.
Terms used below:
- Ledger: the list of simulated trades the backtest actually filled: signal candle time, side, entry time, entry price, exit time, exit reason. Signals that were skipped, missed or expired are only counted; they get no row.
- Match, miss, extra: a match is the same signal candle and side in both the ledger and the agent’s log. A miss: the ledger has it, the agent doesn’t. An extra: the agent has it, the ledger doesn’t.
- Comparison key: the pair (OPEN time of the signal candle in UTC, side). Both sides must use exactly this key, or the counts mean nothing.
- Server time: the broker server’s clock, usually a few hours ahead of UTC. MT5 stamps candles with this clock.
- DST: daylight saving time, the seasonal clock change. In 2026 Europe went back to winter time on 2026-10-25 and the US on 2026-11-01.
- Closed candle: a candle whose time frame is over, so its close no longer changes. In MT5, position 0 is the candle still forming.
- Code replica: the rule written as code and run on your broker’s data. It separates errors from data and time from errors made by the agent.
- Position state: the backtest holds at most one trade; a signal that arrives while a trade is open is dropped. The shadow holds no trades, so it has no position state.
- Distance: how far the close has gone past the nearest line, in USD/oz: positive means beyond the box, negative means still inside.
- Forward shadow: running in real time on new candles; the agent only logs decisions and places no orders.
What the ledger records, and why XAU-06
The reference here is a backtest ledger of XAU-06, built from M5 BID and ASK quotes from 2018 to 2026-11-11, for one variant and one cost scenario, exported as CSV. Each result of that backtest is a triple: method, variant, cost scenario.
Each ledger row holds three groups of fields:
| Group | Fields |
|---|---|
| Time | Open time of signal candle [1] (the one that just closed) in UTC, decision time, entry time, exit time |
| Order | Side (1 buy, −1 sell), price at decision, entry price, SL, TP |
| Result | Result in R (P&L divided by the distance from entry to the initial SL), exit reason |
What matters most: the ledger only has filled trades. Some signals were dropped because they came outside hours, on a Friday, or while another trade was open. Some pending orders were missed, expired or cancelled. Those cases only show up in the report’s counts: candidates = filled + dropped + missed + expired + cancelled.
So the ledger is the trades the backtest actually took, not every signal. An agent running in shadow holds no trades, so it sees every signal. An agent’s extra can still follow the rule; the backtest was simply holding another trade at that moment.
For a method that enters with a market order (filled at once at the current price), every ledger row is one signal candle, so you can count directly. Methods that use pending orders (XAU-05, 07, 08, 09, 13) leave no row on days the order wasn’t filled, so you also have to compare the order levels day by day.
This post uses XAU-06 for three reasons:
- The rule only needs OHLC prices, no indicators, so there’s no question of how each platform computes an EMA or an ATR.
- Entries are market orders, so you can count directly.
- Each day has 23 M15 candles to decide on, the candles opening 11:00 to 16:30 UTC. That’s enough decision points for a repeated error to show.
The XAU-06 rule as a reminder: the box is the 7 M15 candles opening 09:15 to 10:45 UTC. The buy line is the box high plus 0.05 USD/oz; the sell line is the box low minus 0.05. A close strictly beyond a line is a signal; a close equal to the line waits.
Where each of the 13 gold methods tends to drift from a ledger:
| Method | Timeframe, order | Compare by | Where it drifts from the ledger |
|---|---|---|---|
| XAU-01 EMA21 pullback, three layers | H1, market | H1 candle [1] open time and side | EMA200 needs many warm-up candles; the ATR14 in MT5 and in the backtest is a plain mean of 14 true ranges, while the shadow-mode post’s src/candles.py uses Wilder’s; entries in [07:00, 21:00) UTC, no Fridays |
| XAU-02 MACD cross with EMA200 | H4, market | H4 candle open time and side | Backtest H4 candles start at 00, 04, 08… UTC; with a server 2 hours ahead, the broker’s H4 candles start at 22, 02, 06… UTC, so rebuild them from M15 in UTC; MT5’s Signal line is a plain 9-candle mean |
| XAU-03 Bollinger wick reversion | H1, market | H1 candle open time and side | Bollinger uses the population standard deviation, RSI is Wilder’s; TP is the middle band recorded at entry |
| XAU-04 Daily pivot plus Stochastic | M15, market | M15 candle open time and side | Pivots come from D1 candles by UTC day, including a short Sunday candle, so Monday’s pivot is very narrow; a broker’s D1 in server time differs; the 1.50 distance to S1, S2, R1, R2 is measured at the next candle’s first quote |
| XAU-05 Asian box breakout with pending orders | M15, Buy Stop and Sell Stop | Each day: box high, box low and both order levels | The ledger only has the side that filled; unfilled days have no row; the two orders cancel each other (OCO) |
| XAU-06 London box close-breakout | M15, market | M15 candle open time and side | The box is in UTC, so a time offset moves the whole box; signals are dropped while a trade is open; the SL/TP distance depends on the spread at entry |
| XAU-07 Candle-colour stop | M15, stop order | Each candle: side and order level | Every non-doji candle is a candidate; the pending order only lives to the end of the next candle; the ledger only has fills |
| XAU-08 New York opening range sweep plus FVG | M5, limit order | One case per day: candle C, side, limit level | New York time shifts with DST: the 09:30–10:00 New York box is 13:30–14:00 UTC until 2026-10-30 and 14:30–15:00 UTC from 2026-11-02 |
| XAU-09 Asian range sweep at the London open plus FVG | M5, limit order | One case per day | The 02:00–05:00 New York window is 06:00–09:00 UTC until 2026-10-30 and 07:00–10:00 UTC from 2026-11-02; days follow the New York calendar |
| XAU-10 EMA9 pullback with the daily trend | M15 + D1, market | M15 candle open time and side | D1 by UTC day; the 0.40 USD/oz spread filter blocks most trades on a source with a median spread of 0.58 in 2025 and 0.66 in 2026; to compare signals, use the no-spread-filter variant |
| XAU-11 Stochastic with the daily trend | M15 + D1, market | M15 candle open time and side | As XAU-10; Stochastic 5, 3, 3, Low/High |
| XAU-12 Donchian 55/20 | D1, market | Day and side | D1 by UTC day has a short Sunday candle, so 55 candles aren’t the broker’s 55 days; two weeks usually have too few trades to count |
| XAU-13 Structure break plus Fibonacci plus FVG | M15 + D1, limit order | Break event, side, limit level | Swings compare strictly; the pending order is cancelled after 12 candles; the ledger only has fills |
Lock the period, the ledger and the criteria before any run
The comparison period is 10 trading days, Monday 2026-10-26 to Friday 2026-11-06. Three reasons:
- It falls after the June 2026 training cutoff of current models, the last date of data the model learned from.
- It’s inside the ledger, which ends on 2026-11-11.
- It crosses both seasonal clock changes, and many brokers move their server clock on one of them, so this is where mismatches are born.
The two changes: Europe went back to winter time at 01:00 UTC on Sunday 2026-10-25. The US went back at 02:00 local time on Sunday 2026-11-01, which is 06:00 UTC in New York. So in the first week London had changed and New York hadn’t; in the second week both had.
Load the ledger in three steps:
- Open XAU-06 in the backtest you use as reference.
- Pick the variant “fixed SL/TP, close at 17:00” (the default) and the standard cost scenario.
- Export the ledger as CSV.
Picking the right variant is part of the comparison. The “first signal of the day only” variant, for example, has one trade a day; compared with it, almost every signal after the first becomes an extra.
The cost scenario changes the ledger too: entry price, SL, TP and each trade’s result. The spread (the gap between the buy and sell price) is also in XAU-06’s SL/TP formula, so it can move the exit time, which is when the backtest is free to take the next trade. In these 10 days the three cost scenarios happen to have the same 145 (signal candle, side) pairs. Prices and results still differ, so lock exactly one scenario. These numbers are simulations on historical data, not investment advice.
Record the ledger file’s SHA-256 hash in the criteria. A hash is a fingerprint of the file: change one character and it changes. If a later download has a different hash, the backtest was rerun; start the comparison over and don’t mix the two files.
Write the criteria before running any code, then commit them so they carry a
timestamp, as in the shadow-mode post. No criterion is about P&L: this post
only measures whether the agent applies the rule correctly on the right data.
The data/ folder isn’t in the setup post’s .gitignore, so the ledger can
be committed; it holds no account number or personal details.
Create the criteria file (Win + X, Terminal or Windows PowerShell, not the Admin entry; one line at a time, Enter after each; if Notepad asks to create a new file, choose Yes):
cd C:\trading-agent-lab
notepad reports\criteria-compare-xau-06.mdPaste this frame, replace the [BRACKETS] with your own values, press Ctrl + S. Numbers in brackets are examples.
# XAU-06 comparison criteria · written [DATE], not edited after the run
Ledger: XAU-06 · fixed SL/TP, close at 17:00 · standard costs · SHA-256 [PASTE HASH]
Historical period: 2026-10-26 to 2026-11-06 · Data the agent reads: XAUUSD M15 from an MT5 demo, converted to UTC day by day
Prompt: prompts/xau-06-v1.md · Model: claude-sonnet-5-5 · Agent tools: all off · Auto memory: off
Data layer (code vs ledger): every mismatch has a cause; no "see chart" case left without opening the chart.
Agent layer (agent vs code, same data):
1. 0 cases of the agent saying BUY or SELL while the code sees the close inside the box.
2. Agent misses at most [2] of all candles where the code finds a signal.
3. Schema violations at most [3] of [230] points, and 0 in the last [20] points.
Two-week shadow: the same three criteria; the script never creates STOP because of the data or the agent.
No criterion on profit and loss or win rate.Save the ledger and print its hash (move the CSV you exported from Downloads
into data/):
Move-Item "$HOME\Downloads\[EXPORTED FILE NAME].csv" data\ledger-xau-06.csv
Get-FileHash data\ledger-xau-06.csv
notepad data\ledger-xau-06.csvWhat you see: Get-FileHash prints Algorithm, Hash and Path; the default
algorithm is SHA256. Copy the Hash column into the Ledger line of the
criteria file. In Notepad the first line holds the column names. The script
in the next section recognises signalT, side, decisionT or entryT,
quote or entry, exitT; if your file uses other names, add them to
COLUMNS in src/ledger.py. Only look, don’t save: Excel in particular can
change date and number formats.
Your backtest shows the trades but has no export button? Build the file in
Notepad: the first line is signal_utc,side,entry_utc,entry_price,exit_utc,
then one row per trade with a signal time from 2026-10-26 to 2026-11-06 (about
145 rows), times written like 2026-10-26T12:15:00Z, side BUY or SELL.
Lock it with git:
git add reports\criteria-compare-xau-06.md data\ledger-xau-06.csv
git commit -m "Lock XAU-06 comparison criteria and ledger"What you see: one line with a short commit id and 2 files changed. nothing to commit means the file wasn’t saved: go back to Notepad and press Ctrl + S.
Broker candles in server time, and the offset measured day by day
MT5 stamps candles with the broker’s server clock. Many brokers run it 2 or 3 hours ahead of UTC and move it with the seasons. The Python package treats the times it returns as UTC, but the MT5-reading post showed you have to measure the offset yourself.
The commonest way to cause mismatches is to measure the offset once, today, and use it for the whole period. The XAU-06 box is in UTC; one hour off and the box is drawn from different candles, and every signal of that day moves.
So the work is split in two: export candles in server time, then measure the offset and convert. Three scripts do it:
| Step | Script | What it does |
|---|---|---|
| 1 | src/export_m15_server.py |
Exports M15 candles from 2026-10-23 to now, keeps server time, drops the forming candle |
| 2 | src/ledger.py |
Reads the ledger, detects column names |
| 3 | src/measure_offset.py |
For each trade: takes the entry time in UTC, tries adding 0, 1, 2, 3 hours, finds the broker M15 candle that opens then, and compares its open with the ledger’s entry price |
With the right offset the two prices differ by a few tens of cents plus the spread, because they’re the same moment. With an offset one hour wrong they differ by several dollars, because gold moves further than that in an hour. The script takes the median (the middle value when sorted) of the day’s gaps, picks the offset with the smallest median, and converts the candle file to UTC with each day’s own offset.
The sure column says yes when the day has at least 3 trades and the best
offset stands well clear of the next one. Brokers only move their server
clock on weekends, when the market is closed, so within one week every day
must show the same number; if not, the script warns.
The market’s own rhythm shows the clock change too. On historical XAUUSD candles, gold’s daily 60-minute break is 21:00–22:00 UTC up to Friday 2026-10-30 and 22:00–23:00 UTC from Monday 2026-11-02; both are 17:00–18:00 in New York. A rule written in UTC is still exposed to DST, because the broker’s clock and the market’s hours move with the seasons.
Create the three files and run them (MT5 demo open and logged in; the investor password is enough):
cd C:\trading-agent-lab
notepad src\export_m15_server.py
notepad src\ledger.py
notepad src\measure_offset.py
.venv\Scripts\python src\export_m15_server.py
.venv\Scripts\python src\measure_offset.pyWhat you see: export_m15_server.py prints the candle count (a thousand or
more), the first candle (around 2026-10-23) and the last, in server time.
measure_offset.py prints one line per day: day, offset, trades used, median
gap at the best offset, gap at the next best, sure or not. Then a line with
the number of candles converted to UTC. The right offset usually has a gap
under 1 USD; the next best, several dollars.
| The offset table looks like this | It means |
|---|---|
| +3h for 10-26 to 10-30, +2h from 11-02 | The server clock follows the US change (11-01) |
| +2h for both weeks | The server clock followed the European change (10-25), before this period, or stays at +2 all year |
| +0h for every day | The server runs on UTC |
Two numbers in one week, or many NOT SURE days |
Wrong symbol, candle file missing days, or the ledger isn’t XAU-06: check before going on |
src/export_m15_server.py:
# src/export_m15_server.py: export M15 candles from an MT5 demo, KEEPING server time (not converted to UTC yet).
# Read only, sends no orders. Run while the MT5 terminal is open and logged in to a demo (investor password is enough).
import csv
import os
from datetime import datetime, timedelta, timezone
import MetaTrader5 as mt5
SYMBOL = os.environ.get("TL_SYMBOL", "XAUUSD") # the broker may add a suffix
START = datetime(2026, 10, 23, tzinfo=timezone.utc) # a few days before 2026-10-26
END = datetime.now(timezone.utc) + timedelta(days=1) # up to now: also serves the two shadow weeks later
OUT = "data/xau_m15_server.csv"
path = os.environ.get("TL_MT5_PATH", "").strip('"') # only needed with several terminals on one machine
if not (mt5.initialize(path) if path else mt5.initialize()):
raise SystemExit(f"initialize() error: {mt5.last_error()}")
try:
acc = mt5.account_info()
if acc is None or acc.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO:
raise SystemExit("STOP: the terminal is not logged in to a demo account.")
mt5.symbol_select(SYMBOL, True)
rates = mt5.copy_rates_range(SYMBOL, mt5.TIMEFRAME_M15, START, END)
err = mt5.last_error()
tick = mt5.symbol_info_tick(SYMBOL)
finally:
mt5.shutdown()
if rates is None or len(rates) == 0:
raise SystemExit(f"Could not get {SYMBOL} candles: {err}")
if tick is not None: # drop the forming candle: keep candles closed by the server clock
rates = [r for r in rates if int(r["time"]) + 900 <= tick.time]
if len(rates) == 0:
raise SystemExit("No closed candle in this range yet.")
os.makedirs("data", exist_ok=True)
with open(OUT, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["time_server", "open", "high", "low", "close"])
for r in rates: # MT5's seconds, read as the server clock
t = datetime.fromtimestamp(int(r["time"]), timezone.utc).strftime("%Y-%m-%d %H:%M")
w.writerow([t, float(r["open"]), float(r["high"]), float(r["low"]), float(r["close"])])
first = datetime.fromtimestamp(int(rates[0]["time"]), timezone.utc)
last = datetime.fromtimestamp(int(rates[-1]["time"]), timezone.utc)
print(len(rates), "M15 candles ->", OUT, f"| first {first:%Y-%m-%d %H:%M} | last {last:%Y-%m-%d %H:%M} (server time)")src/ledger.py:
# src/ledger.py: read the XAU-06 ledger CSV exported from the reference backtest. Detects common column names.
# Reads the file only: no network, no orders.
import csv
import sys
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
LEDGER = ROOT / "data" / "ledger-xau-06.csv"
COLUMNS = { # column names you may meet; if your file differs, add the name here
"signal": ("signalT", "signal_utc"), # OPEN time of signal candle [1]
"side": ("side",),
"entry": ("decisionT", "entryT", "entry_utc"), # decision time or fill time
"entry_price": ("quote", "entry", "entry_price"),
"exit": ("exitT", "exit_utc"),
}
def _time(v):
"""A ledger time: Unix seconds or milliseconds (UTC), or an ISO string. Returns a naive UTC datetime."""
v = str(v).strip()
try:
n = float(v)
except ValueError:
d = datetime.fromisoformat(v.replace("Z", "+00:00"))
return d.astimezone(timezone.utc).replace(tzinfo=None) if d.tzinfo else d
return datetime.fromtimestamp(n / 1000 if n > 1e11 else n, timezone.utc).replace(tzinfo=None)
def _side(v):
v = str(v).strip().upper()
if v in ("1", "1.0", "BUY", "LONG"):
return "BUY"
if v in ("-1", "-1.0", "SELL", "SHORT"):
return "SELL"
raise SystemExit(f"Unknown side value: {v}")
def read_ledger(path=LEDGER):
"""XAU-06 trades in the ledger: signal, side, entry, entry_price, exit (times are naive UTC datetimes)."""
with open(path, encoding="utf-8-sig") as f:
rows = csv.DictReader(f)
header = rows.fieldnames or []
col = {name: next((c for c in options if c in header), None) for name, options in COLUMNS.items()}
if not col["signal"] or not col["side"]:
sys.exit(f"Ledger has no signal-time or side column. File header: {header}. Add the name to COLUMNS.")
out = []
for r in rows:
if r.get("rule") and r["rule"].lower() != "xau-06":
continue # a file with several methods: keep XAU-06 only
v = {k: r.get(c) if c else None for k, c in col.items()}
out.append({"signal": _time(v["signal"]), "side": _side(v["side"]),
"entry": _time(v["entry"]) if v["entry"] else None,
"entry_price": float(v["entry_price"]) if v["entry_price"] else None,
"exit": _time(v["exit"]) if v["exit"] else None})
for name in ("variant", "cost"):
if name in header:
with open(path, encoding="utf-8-sig") as f:
values = {r[name] for r in csv.DictReader(f)}
if len(values) > 1:
sys.exit(f"Ledger mixes several {name} values: {values}. Download one variant and one cost scenario.")
return outsrc/measure_offset.py:
# src/measure_offset.py: measure how many hours the broker's server clock runs ahead of UTC, DAY BY DAY, by comparing
# the broker's M15 open prices with the ledger's entry prices; then convert the candle file to UTC.
# Reads and writes files in data/ only. Calls no agent, sends no orders.
import argparse
import csv
import statistics
import sys
from collections import defaultdict
from datetime import datetime, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT)) # so src.* imports work when run as python src/...
from src.ledger import read_ledger
TF = "%Y-%m-%d %H:%M"
IN = ROOT / "data" / "xau_m15_server.csv"
OUT = ROOT / "data" / "xau_m15_utc.csv"
TABLE = ROOT / "data" / "offset-by-day.csv"
TRY = range(0, 4) # try server ahead of UTC by 0, 1, 2, 3 hours
ap = argparse.ArgumentParser()
ap.add_argument("--force-offset", type=int, help="EXPERIMENT: force one offset for every day, as if measured once")
ap.add_argument("--new-days", type=int, help="offset for days the ledger doesn't cover (forward shadow)")
a = ap.parse_args()
with open(IN, encoding="utf-8-sig") as f:
candles = list(csv.DictReader(f))
opens = {r["time_server"]: float(r["open"]) for r in candles}
diffs = defaultdict(lambda: defaultdict(list)) # UTC day -> hours tried -> price gap per trade
for t in read_ledger():
if t["entry"] is None or t["entry_price"] is None:
sys.exit("Ledger has no entry-time or entry-price column: can't measure the offset this way.")
m15 = t["entry"].replace(second=0, microsecond=0) - timedelta(minutes=t["entry"].minute % 15) # M15 candle holding the entry
for k in TRY:
p = opens.get((m15 + timedelta(hours=k)).strftime(TF))
if p is not None:
diffs[m15.date()][k].append(abs(p - t["entry_price"]))
table = []
for day in sorted(diffs):
ranked = sorted((statistics.median(v), k, len(v)) for k, v in diffs[day].items() if v)
(best, k, n), nxt = ranked[0], (ranked[1][0] if len(ranked) > 1 else None)
sure = n >= 3 and nxt is not None and nxt >= 2 * best + 0.5 # the best must stand well clear of the next
table.append({"day": day.isoformat(), "offset_h": k, "trades": n, "median_gap": round(best, 3),
"next_gap": None if nxt is None else round(nxt, 3), "sure": "yes" if sure else "NOT SURE"})
if not table:
sys.exit("No trade matched a broker candle: check the two files cover the same dates and the symbol.")
with open(TABLE, "w", newline="", encoding="utf-8-sig") as f:
w = csv.DictWriter(f, fieldnames=list(table[0]))
w.writeheader()
w.writerows(table)
print("day offset trades gap(USD) next gap sure")
for b in table:
print(f"{b['day']} +{b['offset_h']}h {b['trades']:>6} {b['median_gap']:>8} {b['next_gap']!s:>8} {b['sure']}")
offset = {b["day"]: b["offset_h"] for b in table}
if a.force_offset is not None:
print(f"EXPERIMENT: forcing +{a.force_offset}h on every day. When done, rerun without this flag.")
weeks = defaultdict(set)
for day, k in offset.items():
weeks[datetime.fromisoformat(day).isocalendar()[:2]].add(k)
for (year, week), ks in sorted(weeks.items()):
if len(ks) > 1:
print(f"WARNING: week {week}/{year} has several offsets {sorted(ks)}. Brokers only change on weekends: check.")
written = skipped = 0
with open(OUT, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["time_utc", "open", "high", "low", "close"])
for r in candles:
t = datetime.strptime(r["time_server"], TF)
k = a.force_offset if a.force_offset is not None else offset.get(t.date().isoformat(), a.new_days)
if k is None:
skipped += 1 # a day with no trade to measure and no --new-days: don't guess
continue
w.writerow([(t - timedelta(hours=k)).strftime(TF), r["open"], r["high"], r["low"], r["close"]])
written += 1
print(written, "candles converted to UTC ->", OUT.relative_to(ROOT).as_posix(), "| skipped", skipped,
"candles of days with no measured offset")| You see | Cause | Fix |
|---|---|---|
Could not get XAUUSD candles |
The broker’s symbol has a suffix, or history isn’t downloaded | $env:TL_SYMBOL = "the right name" and rerun in the same window; open an M15 chart and scroll back to 2026-10-23 |
| First candle much later than 10-23 | The terminal hasn’t loaded enough history | Open the symbol’s M15 chart, scroll back to October 2026, rerun |
initialize() error or STOP: the terminal is not logged in to a demo account |
MT5 not open, not logged in, or on a live account | Open MT5, log in to the demo; with several terminals set $env:TL_MT5_PATH as in the MT5-reading post |
Ledger has no signal-time or side column |
The file uses other column names | Read the header the script prints, add the names to COLUMNS in src/ledger.py |
No trade matched a broker candle |
The two files cover different dates, or the ledger is empty | Open both in Notepad, compare dates in the first and last rows |
Ledger mixes several variant (or cost) values |
You exported a file that merges several results | Export one variant and one cost scenario |
WARNING: week ... has several offsets |
Missing data, wrong symbol, or a day with too few trades | Look at trades and sure; a day with only 1–2 trades isn’t measured reliably |
When it’s done: git add src data, then git commit -m "Broker candles and daily offset".
The rule as code: compare code with the ledger before any AI
The code replica is the XAU-06 rule rewritten in src/xau_06.py and run on
the broker candles converted to UTC. It doesn’t track positions, so every
candle whose close goes past a line is a signal.
The point is to separate layers. Code against the ledger shows the part of the mismatch that comes from data, time and position state, with no AI involved. Then agent against code, on the same data, leaves only the agent’s part. Without that split, every mismatch looks like the agent’s fault.
src/compare_xau_06.py joins three sources (ledger, code, agent) on the key
(signal candle open time, side). Run before there’s an agent log, it prints
line 2) Code vs ledger and one line per week. The suggested causes come from a
few simple rules:
- Near threshold: a close within 0.50 USD/oz of a line. Two price sources a few tens of cents apart are enough to flip the result. On 2026-11-11, two price sources compared on the box levels and the close differed by 0.106 to 0.343 USD/oz, and the signals still matched.
- Position state: the code has a signal the ledger didn’t take, while the ledger was holding another trade.
Position state depends on the spread. In short: a wider spread means a wider SL/TP distance, trades last longer, and an open trade blocks more signals. The detail, for anyone checking the numbers:
- The XAU-06 SL/TP distance is max(stops level + spread + 30 points, 30 pips)
- spread: take the larger of the two values in brackets, then add the spread. Stops level is the minimum distance the broker requires between price and SL/TP (the backtest assumes 0). A point is 0.001 and a pip is 0.01 USD/oz.
- In these 10 days the median spread at the M5 candle open was 0.534 USD/oz over 2,735 M5 candles, so the SL/TP distance was about 1.1 USD, more than three times the 0.34 you get with a 0.040 spread.
- From 2018 to 2026-11-11 the backtest’s open trades therefore blocked 643 of 31,445 signals. At a 0.040 spread it would be 85.
- These 10 days are different: 144 of 145 trades hit SL or TP inside the entry M5 candle, at most 10 minutes, so no signal was blocked. Running the rule without position tracking on the backtest’s own data gives exactly the ledger’s 145 pairs.
So in this period the position-state label is rare. When you see it, open the ledger and check the entry and exit times of the trade spanning that point. The other cases carry a data or time label: look at the chart. These numbers are simulations on historical data, not investment advice.
The goal of this layer isn’t a 100% match; it’s a cause for every mismatch. One week matching almost everything while the other drops sharply points to a time offset, not to a wrong rule.
Try it on purpose, in two steps:
- Run
measure_offset.py --force-offsetwith the second week’s number, as if you’d measured once today. Then runcompare_xau_06.pyand look at the two Week lines. If your broker follows the US change, Week 44 drops sharply and Week 45 barely moves. - Then run
measure_offset.pywithout the flag to put the data back.
Create the two files and run them:
cd C:\trading-agent-lab
notepad src\xau_06.py
notepad src\compare_xau_06.py
.venv\Scripts\python src\xau_06.py 2026-11-02
.venv\Scripts\python src\compare_xau_06.pyWhat you see: xau_06.py prints 23 lines for 2026-11-02, one per signal
candle: UTC time, the code’s decision, close, both lines and distance
(positive beyond, negative inside). compare_xau_06.py prints four things:
the Period line, line 2) Code vs ledger with each group of causes, the two
Week lines, and the path of the detail file.
The deliberate test (replace 2 with the number the offset table shows for 2026-11-02 to 11-06):
.venv\Scripts\python src\measure_offset.py --force-offset 2
.venv\Scripts\python src\compare_xau_06.py
.venv\Scripts\python src\measure_offset.pyThe last command puts each day’s own offset back. If your broker keeps one server clock across both weeks, the test changes nothing: that’s a result too, write it down.
What the forced offset does, on made-up candles built with a +3h server clock before 2026-11-01 and +2h after, and a made-up ledger with one planted miss and one planted extra (to test the script, not a result):
EXPERIMENT: forcing +2h on every day. When done, rerun without this flag.
1012 candles converted to UTC -> data/xau_m15_utc.csv | skipped 0 candles of days with no measured offset
Period 2026-10-26 -> 2026-11-06 | points the code checked: 230 | trades in the ledger: 114
2) Code vs ledger (no AI): match 89/114, missed 25, extra 17
extra - 1-hour shift: suspect DST: 6
extra - data or time off: see chart: 9
extra - near threshold: different price source: 2
missed - 1-hour shift: suspect DST: 5
missed - data or time off: see chart: 15
missed - near threshold: different price source: 5
Week 44: code matches 36/60 ledger trades
Week 45: code matches 53/54 ledger tradesWith each day’s own offset, the same files give match 113/114, missed 1, extra 1, the two planted cases, and Week 44 at 60/60.
| Printed line | How to read it |
|---|---|
2) Code vs ledger (no AI): match a/b, missed c, extra d |
b is the number of ledger trades in the period. Missed: in the ledger, not in the code. Extra: in the code, not in the ledger |
extra - ledger holding another trade (position state) |
Not an error: the backtest dropped the signal because a trade was open |
missed or extra - near threshold: different price source |
Close within 0.50 USD/oz of a line: two price sources can flip it. Note it, fix nothing |
1-hour shift: suspect DST |
A miss and an extra on the same side exactly 60 minutes apart: check the offset table |
1-candle shift: suspect an unclosed candle or a bad cut |
A pair exactly 15 minutes apart: check how closed candles are read |
data or time off: see chart |
No cause yet: open the chart at that candle before writing a conclusion |
Week 44, Week 45: code matches ... |
One week matching almost all and the other dropping: suspect the time offset before anything else |
src/xau_06.py:
# src/xau_06.py: the XAU-06 rule (London box close-breakout) written as code, with NO position tracking.
# Reads files only: no network, no agent, no orders.
import csv
import sys
from datetime import datetime, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
TF = "%Y-%m-%d %H:%M"
BUFFER = 0.05 # 5 pips = 0.05 USD/oz around the box
BOX = ["09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "10:45"] # 7 M15 box candles, OPEN times, UTC
SIGNAL = [f"{h:02d}:{m:02d}" for h in range(11, 17) for m in (0, 15, 30, 45)][:23] # signal candles open 11:00 to 16:30
def read_candles(path):
"""UTC M15 candles: {'YYYY-MM-DD HH:MM': {'open','high','low','close'}}."""
with open(path, encoding="utf-8-sig") as f:
return {r["time_utc"]: {k: float(r[k]) for k in ("open", "high", "low", "close")}
for r in csv.DictReader(f)}
def day_decisions(candles, day):
"""Every decision of day 'YYYY-MM-DD'. A box with a missing candle returns an empty list."""
box = [candles.get(f"{day} {t}") for t in BOX]
if None in box:
return []
high, low = max(x["high"] for x in box), min(x["low"] for x in box)
buy_line, sell_line = round(high + BUFFER, 3), round(low - BUFFER, 3)
out = []
for t in SIGNAL:
x = candles.get(f"{day} {t}")
if x is None:
continue # missing candle: no decision at this point
c = x["close"]
action = "BUY" if c > buy_line else "SELL" if c < sell_line else "STAY_OUT" # on the line: wait
dist = c - buy_line if action == "BUY" else sell_line - c if action == "SELL" else -min(buy_line - c, c - sell_line)
opened = datetime.strptime(f"{day} {t}", TF)
out.append({"signal_utc": f"{day} {t}", "point_utc": (opened + timedelta(minutes=15)).strftime(TF),
"box_high": high, "box_low": low, "buy_line": buy_line, "sell_line": sell_line,
"close": c, "action": action, "distance": round(dist, 3)})
return out
if __name__ == "__main__": # print the code's decisions for one day: python src/xau_06.py 2026-11-02
candles = read_candles(ROOT / "data" / "xau_m15_utc.csv")
for q in day_decisions(candles, sys.argv[1]):
print(q["signal_utc"], q["action"], "close", q["close"], "lines", q["sell_line"], q["buy_line"],
"distance", q["distance"])src/compare_xau_06.py:
# src/compare_xau_06.py: count matches, misses and extras between the backtest ledger, the rule written as code
# and the agent, then suggest a cause for each mismatch. Reads data/ and logs/, writes reports/. No agent, no orders.
import argparse
import csv
import sys
from collections import Counter
from datetime import date, datetime, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.ledger import read_ledger
from src.xau_06 import TF, day_decisions, read_candles
NEAR = 0.50 # close within 0.50 USD of a line: a few tens of cents between price sources can flip it
SEE_CHART = "data or time off: see chart"
ap = argparse.ArgumentParser()
ap.add_argument("--start", default="2026-10-26")
ap.add_argument("--end", default="2026-11-06")
ap.add_argument("--mode", default="historical", help="historical or live")
ap.add_argument("--version", default="xau-06-v1")
a = ap.parse_args()
START, END = date.fromisoformat(a.start), date.fromisoformat(a.end)
candles = read_candles(ROOT / "data" / "xau_m15_utc.csv")
code, day = {}, START
while day <= END:
for q in day_decisions(candles, day.isoformat()):
code[q["signal_utc"]] = q
day += timedelta(days=1)
trades = [t for t in read_ledger() if START <= t["signal"].date() <= END]
ledger = {(t["signal"].strftime(TF), t["side"]) for t in trades}
held = [(t["entry"], t["exit"]) for t in trades if t["entry"] and t["exit"]]
agent = {}
log = ROOT / "logs" / "agent-signals.csv"
if log.exists():
with open(log, encoding="utf-8-sig") as f:
for r in csv.DictReader(f):
if r["mode"] == a.mode and r["prompt_version"] == a.version and START <= date.fromisoformat(r["point_utc"][:10]) <= END:
agent[r["signal_utc"]] = r
def signals(d):
return {(t, x["action"]) for t, x in d.items() if x["action"] in ("BUY", "SELL")}
ag, cd = signals(agent), signals(code)
rows = []
for t, side in sorted(ledger | ag | cd):
point = datetime.strptime(t, TF) + timedelta(minutes=15)
in_ledger, in_agent, in_code = (t, side) in ledger, (t, side) in ag, (t, side) in cd
dist = code[t]["distance"] if t in code else None
holding = any(e < point <= x for e, x in held) # a ledger trade from an EARLIER candle is still open at this point
data_cause = ("broker data missing the candle or the box" if dist is None
else "near threshold: different price source" if abs(dist) <= NEAR else SEE_CHART)
code_ledger, why_code = ("match", "") if in_ledger and in_code else ("ledger_only", data_cause) if in_ledger else ("", "")
if in_code and not in_ledger:
code_ledger, why_code = "code_only", "ledger holding another trade (position state)" if holding else data_cause
agent_ledger, why_agent = "", ""
if agent and (in_ledger or in_agent):
if in_ledger and in_agent:
agent_ledger = "match"
elif in_ledger:
agent_ledger = "missed"
why_agent = ("no valid agent decision at this point" if t not in agent or agent[t]["action"] == "VIOLATION"
else "agent missed it: code on the same data sees a signal" if in_code else why_code)
else:
agent_ledger = "extra"
why_agent = "agent's own: code sees the close inside the lines" if not in_code else why_code
rows.append({"signal_utc": t, "side": side, "ledger": int(in_ledger), "code": int(in_code), "agent": int(in_agent),
"code_ledger": code_ledger, "why_code_ledger": why_code, "agent_ledger": agent_ledger,
"why_agent_ledger": why_agent, "distance": dist, "agent_reason": agent.get(t, {}).get("short_reason", "")})
for b in rows: # same-side mismatch pairs exactly 1 candle or 1 hour apart
if b["why_code_ledger"] != SEE_CHART:
continue
t = datetime.strptime(b["signal_utc"], TF)
for minutes, name in ((15, "1-candle shift: suspect an unclosed candle or a bad cut"), (60, "1-hour shift: suspect DST")):
pair = {((t + timedelta(minutes=d)).strftime(TF), b["side"]) for d in (-minutes, minutes)}
if any((x["signal_utc"], x["side"]) in pair and x["code_ledger"] in ("ledger_only", "code_only")
and x["code_ledger"] != b["code_ledger"] for x in rows):
b["why_code_ledger"] = name
if b["agent_ledger"] in ("missed", "extra") and b["why_agent_ledger"] == SEE_CHART:
b["why_agent_ledger"] = name
if a.mode == "live": # the close the agent saw differs from the final close: unclosed candle
for t, r in agent.items():
if t in candles and r["close_seen"] and abs(float(r["close_seen"]) - candles[t]["close"]) > 0.001:
print("Unclosed candle or edited data at", t, ": agent saw", r["close_seen"], "| final close", candles[t]["close"])
(ROOT / "reports").mkdir(exist_ok=True)
out = ROOT / "reports" / f"compare-xau-06-{a.mode}.csv"
with open(out, "w", newline="", encoding="utf-8-sig") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]) if rows else ["signal_utc"])
w.writeheader()
w.writerows(rows)
print(f"Period {START} -> {END} | points the code checked: {len(code)} | trades in the ledger: {len(ledger)}")
if agent:
violations = sum(r["action"] == "VIOLATION" for r in agent.values())
same = sum(code[t]["action"] == r["action"] for t, r in agent.items() if t in code)
cd_ag = {(t, s) for t, s in cd if t in agent} # only points the agent has run
print(f"1) Agent vs code: {len(agent)} points, violations {violations}, same as code {same}/{len(agent)}"
f" | code signals {len(cd_ag)}, agent missed {len(cd_ag - ag)}, agent extra {len(ag - cd)}")
pending = sum(t not in agent for t in code)
if pending:
print(f" Agent has no decision yet at {pending} points the code checked: not counted as missed.")
for n, col, name in ((2, "code_ledger", "Code vs ledger (no AI)"), (3, "agent_ledger", "Agent vs ledger")):
if not ledger or (col == "agent_ledger" and not agent):
continue
count = Counter(b[col] for b in rows)
miss, extra = ("ledger_only", "code_only") if col == "code_ledger" else ("missed", "extra")
print(f"{n}) {name}: match {count['match']}/{len(ledger)}, missed {count[miss]}, extra {count[extra]}")
for (kind, why), k in sorted(Counter((b[col], b["why_" + col]) for b in rows if b[col] in (miss, extra)).items()):
print(f" {'missed' if kind == miss else 'extra'} - {why}: {k}")
if ledger:
for wk in sorted({datetime.strptime(b["signal_utc"], TF).isocalendar()[1] for b in rows}):
week = [b for b in rows if datetime.strptime(b["signal_utc"], TF).isocalendar()[1] == wk]
print(f" Week {wk}: code matches {sum(b['code_ledger'] == 'match' for b in week)}/{sum(b['ledger'] for b in week)} ledger trades")
else:
print("The ledger doesn't cover this period yet: comparing the agent with the code only.")
print("Details:", out.relative_to(ROOT).as_posix(), "| Simulation on historical data, not investment advice.")When run with --mode live (the shadow section), the script also compares the
close the agent saw with the candle’s final close. If they differ, it prints
an Unclosed candle or edited data line.
Six tests for the rule and for the checks on the agent’s answer
(tests/test_xau_06.py; run with .venv\Scripts\python -m pytest -q tests):
"""6 tests for src/xau_06.py and the agent checks in src/run_agent_xau_06.py. Made-up candles; no MT5, no agent."""
import json
from src.run_agent_xau_06 import candle_block, check_signal
from src.xau_06 import BOX, SIGNAL, day_decisions
DAY = "2026-11-02"
def make_day(signal_closes=None):
"""Box candles 4000-4010; every signal candle closes at 4005 unless signal_closes overrides it."""
c = {f"{DAY} {t}": {"open": 4005.0, "high": 4010.0, "low": 4000.0, "close": 4005.0} for t in BOX}
for t in SIGNAL:
close = (signal_closes or {}).get(t, 4005.0)
c[f"{DAY} {t}"] = {"open": 4005.0, "high": max(close, 4005.0) + 1, "low": min(close, 4005.0) - 1, "close": close}
return c
def by_time(candles):
return {q["signal_utc"][-5:]: q for q in day_decisions(candles, DAY)}
def test_1_close_on_the_line_waits_strictly_beyond_signals():
q = by_time(make_day({"11:00": 4010.05, "11:15": 4010.051, "11:30": 3999.95, "11:45": 3999.949}))
assert [q[t]["action"] for t in ("11:00", "11:15", "11:30", "11:45")] == ["STAY_OUT", "BUY", "STAY_OUT", "SELL"]
assert q["11:15"]["distance"] == 0.001 and q["11:45"]["distance"] == 0.001
def test_2_wick_beyond_the_line_is_not_a_signal_and_distance_is_negative_inside():
c = make_day()
c[f"{DAY} 12:00"] = {"open": 4005.0, "high": 4015.0, "low": 3995.0, "close": 4009.0}
q = by_time(c)["12:00"]
assert q["action"] == "STAY_OUT" and q["distance"] == -1.05
def test_3_23_points_per_day_and_missing_box_candle_gives_none():
c = make_day()
q = day_decisions(c, DAY)
assert len(q) == 23 and q[0]["point_utc"] == f"{DAY} 11:15" and q[-1]["point_utc"] == f"{DAY} 16:45"
del c[f"{DAY} 10:45"]
assert day_decisions(c, DAY) == []
def test_4_candle_block_holds_only_candles_closed_by_the_point():
lines = candle_block(make_day(), DAY, f"{DAY} 11:30").splitlines()
assert lines[1].startswith(f"{DAY} 09:15") and lines[-1].startswith(f"{DAY} 11:15")
assert len(lines) == 1 + 7 + 2 # header, 7 box candles, 11:00 and 11:15
EXPECTED = {"point_utc": f"{DAY} 11:30", "method": "XAU-06", "signal_utc": f"{DAY} 11:15", "prompt_version": "xau-06-v1"}
def answer(**kw):
d = {**EXPECTED, "action": "BUY", "box_high": 4010.0, "box_low": 4000.0, "last_close": 4010.06, "short_reason": "ok"}
d.update(kw)
return json.dumps(d)
def test_5_valid_answer_and_self_contradiction():
assert check_signal(answer(), EXPECTED)[1] == []
_, v = check_signal(answer(last_close=4010.05), EXPECTED) # on the line by its own numbers: should be STAY_OUT
assert v == ["self-contradiction: by the agent's own numbers it should be STAY_OUT"]
def test_6_text_around_json_extra_field_and_wrong_point_are_violations():
assert check_signal("Sure: " + answer(), EXPECTED) == (None, ["not bare JSON"])
d = json.loads(answer())
d["lot"] = 0.01
assert check_signal(json.dumps(d), EXPECTED)[1][0].startswith("wrong field list")
assert check_signal(answer(point_utc=f"{DAY} 11:45"), EXPECTED)[1] == [f"point_utc must be {DAY} 11:30"]Let the agent look for signals on the same ten days
src/run_agent_xau_06.py calls the agent at every decision point of the 10
days: 23 points a day, from 11:15 to 16:45 UTC, about 230 calls. At each point
the agent gets only two things: the day’s closed M15 candles from the 09:15
UTC candle to the signal candle, and the rule in words from
prompts/xau-06-v1.md (the template is at the end of this post).
The call is the same as in the shadow-mode post: claude -p (one Claude Code
turn with no typing, then exit) with the pinned model claude-sonnet-5-5:
| Setting | Why |
|---|---|
--tools "" |
Turns off every built-in tool, so the agent can’t open the file holding candles after the point, or go online |
--disallowedTools "mcp__*" |
Drops MCP tools (tools added from outside) for the same reason |
CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 |
Turns off auto memory, which lives outside git |
--no-session-persistence |
Doesn’t save the session |
--max-budget-usd 0.20 |
A cap on the estimated cost of one call. The actual cost can go a little past it, so leave room |
The agent returns exactly 9 JSON fields, including the box high, box low and close it read. Code checks them as in the shadow-mode post, plus one more check: from the agent’s own three numbers, it recomputes the decision. If the agent writes those numbers but reaches a different conclusion, that’s a self-contradiction and counts as a violation.
The agent doesn’t compute lot, SL or TP, because those depend on the spread at entry, and this post doesn’t need them. At level 2, the check layer from the demo-order post computes the lot and rounds it down to a 0.01 step.
Each log row also records the code’s decision and distance at the same point,
the close the agent was shown, the day’s offset, the actual model, the
estimated cost and the seconds taken. Each call takes a while; the seconds
column has the real number. On a subscription plan the runs count against the
plan’s usage limits; /usage shows where you are.
You can split the work into two sessions, one week each: the script skips points already in the log. On a technical error the script stops instead of retrying in a loop.
Don’t edit the prompt mid-batch. When the agent is wrong at a point, write it
down. To change the prompt, create prompts/xau-06-v2.md and test it on a
different period, because these 10 days have already been used to look at the
errors.
Save the prompt, create the script, run it:
cd C:\trading-agent-lab
notepad prompts\xau-06-v1.md
notepad src\run_agent_xau_06.py
Test-Path Env:ANTHROPIC_API_KEY
.venv\Scripts\python src\run_agent_xau_06.pyFor prompts/xau-06-v1.md, copy the template from the end of this post
exactly. Keep the [DAY], [POINT_UTC], [SIGNAL_CANDLE_UTC], [VERSION]
and [CANDLES_CSV] slots; the script fills them at each point. If Notepad
shows an Encoding box, pick UTF-8. Test-Path printing False is what you
want.
What you see: one line per point, like
2026-10-26 12:30 agent BUY | code BUY | valid, or agent VIOLATION with
the reason. Don’t close the window while
it runs. The last line reminds you the result is a simulation on historical
data, not investment advice.
src/run_agent_xau_06.py:
# src/run_agent_xau_06.py: the agent looks for XAU-06 signals at each closed M15 candle of the comparison period.
# The agent only reads the data in the prompt and returns JSON; it places NO order. Safe to rerun: logged points are skipped.
import csv
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
from datetime import date, datetime, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.xau_06 import TF, day_decisions, read_candles
PROMPT = ROOT / "prompts" / "xau-06-v1.md"
VERSION = "xau-06-v1"
MODEL = "claude-sonnet-5-5" # full pinned name, as in the shadow-mode post
DATA = ROOT / "data" / "xau_m15_utc.csv"
OFFSETS = ROOT / "data" / "offset-by-day.csv"
LOG = ROOT / "logs" / "agent-signals.csv"
START, END = date(2026, 10, 26), date(2026, 11, 6) # comparison period, both ends included
COLS = ["point_utc", "signal_utc", "mode", "action", "code_action", "code_distance", "close_seen",
"box_high", "box_low", "last_close", "short_reason", "violation", "prompt_version", "prompt_hash",
"model_pinned", "model_actual", "offset_h", "est_cost_usd", "seconds", "raw_file"]
SCHEMA = ["point_utc", "method", "signal_utc", "action", "box_high", "box_low", "last_close",
"short_reason", "prompt_version"]
CLAUDE = shutil.which("claude")
ENV = {**os.environ, "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1"} # auto memory lives outside git: turn it off
def candle_block(candles, day, point):
"""CSV of the day's CLOSED candles, from the 09:15 UTC candle to the one that closes exactly at point."""
lines, t, end = ["time_utc,open,high,low,close"], datetime.strptime(f"{day} 09:15", TF), datetime.strptime(point, TF)
while t + timedelta(minutes=15) <= end: # only candles whose CLOSE is no later than the point
x = candles.get(t.strftime(TF))
if x:
lines.append(f"{t.strftime(TF)},{x['open']},{x['high']},{x['low']},{x['close']}")
t += timedelta(minutes=15)
return "\n".join(lines)
def check_signal(text, expected):
"""Check the answer with deterministic code. Returns (decision or None, list of violations; empty means valid)."""
try:
d = json.loads(text.strip())
except (json.JSONDecodeError, AttributeError):
return None, ["not bare JSON"]
if not isinstance(d, dict):
return None, ["JSON is not an object"]
v = [] if sorted(d) == sorted(SCHEMA) else [f"wrong field list: {sorted(d)}"]
v += [f"{k} must be {x}" for k, x in expected.items() if d.get(k) != x]
action, nums = d.get("action"), [d.get(k) for k in ("box_high", "box_low", "last_close")]
if action not in ("BUY", "SELL", "STAY_OUT"):
v.append(f"unknown action: {action}")
elif not all(isinstance(n, (int, float)) and not isinstance(n, bool) for n in nums):
v.append("box_high, box_low, last_close must be numbers")
elif nums[0] <= nums[1]:
v.append("box_high must be above box_low")
else:
right = "BUY" if nums[2] > round(nums[0] + 0.05, 3) else "SELL" if nums[2] < round(nums[1] - 0.05, 3) else "STAY_OUT"
if action != right:
v.append(f"self-contradiction: by the agent's own numbers it should be {right}")
if not isinstance(d.get("short_reason"), str) or len(d["short_reason"]) > 200:
v.append("short_reason must be text, at most 200 characters")
return d, v
def call_agent(text):
"""One claude -p turn: all tools off, pinned model. A technical error stops the run; no retry loop."""
cmd = [CLAUDE, "-p", "Follow the instructions in the attached content exactly. Return only one JSON object.",
"--model", MODEL, "--output-format", "json", "--tools", "", "--disallowedTools", "mcp__*",
"--no-session-persistence", "--max-budget-usd", "0.20"]
start = time.time()
try:
res = subprocess.run(cmd, input=text, capture_output=True, text=True, encoding="utf-8",
timeout=600, cwd=ROOT, env=ENV)
except subprocess.TimeoutExpired:
sys.exit("No answer after 600 seconds: stop, check the network, then rerun the same command.")
try:
out = json.loads(res.stdout)
except json.JSONDecodeError:
out = {}
if res.returncode != 0 or out.get("is_error") or "result" not in out:
print("Technical error - stopping, no retry loop.")
sys.exit(str(out.get("result") or res.stderr or res.stdout)[:400])
return out, round(time.time() - start, 1), res.stdout
def done_points(mode):
if not LOG.exists():
return set()
with open(LOG, encoding="utf-8-sig") as f:
return {(r["point_utc"], r["prompt_version"]) for r in csv.DictReader(f) if r["mode"] == mode}
def run_point(candles, day, q, mode, offset_h):
"""Call the agent at one point, check it, log one row. q is the code's decision at the same point."""
template = PROMPT.read_text(encoding="utf-8-sig")
text = template
for k, v in {"[DAY]": day, "[SIGNAL_CANDLE_UTC]": q["signal_utc"], "[POINT_UTC]": q["point_utc"],
"[VERSION]": VERSION, "[CANDLES_CSV]": candle_block(candles, day, q["point_utc"])}.items():
text = text.replace(k, v)
out, secs, raw_text = call_agent(text)
raw = ROOT / "logs" / "raw" / f"{mode}_{q['point_utc'].replace(':', '-').replace(' ', '_')}.json"
raw.parent.mkdir(parents=True, exist_ok=True)
raw.write_text(raw_text, encoding="utf-8")
d, v = check_signal(out["result"], {"point_utc": q["point_utc"], "method": "XAU-06",
"signal_utc": q["signal_utc"], "prompt_version": VERSION})
ok = d if (d and not v) else {}
row = {"point_utc": q["point_utc"], "signal_utc": q["signal_utc"], "mode": mode,
"action": ok.get("action", "VIOLATION"), "code_action": q["action"],
"code_distance": q["distance"], "close_seen": q["close"], "box_high": ok.get("box_high"),
"box_low": ok.get("box_low"), "last_close": ok.get("last_close"), "short_reason": ok.get("short_reason", ""),
"violation": "; ".join(v), "prompt_version": VERSION,
"prompt_hash": hashlib.sha256(template.encode("utf-8")).hexdigest()[:8], "model_pinned": MODEL,
"model_actual": ",".join(out.get("modelUsage") or {}) or "unknown", "offset_h": offset_h,
"est_cost_usd": out.get("total_cost_usd", ""), "seconds": secs,
"raw_file": raw.relative_to(ROOT).as_posix()}
new = not LOG.exists()
LOG.parent.mkdir(exist_ok=True)
with open(LOG, "a", newline="", encoding="utf-8-sig") as f:
w = csv.DictWriter(f, fieldnames=COLS)
if new:
w.writeheader()
w.writerow(row)
return row
def main():
if os.environ.get("ANTHROPIC_API_KEY"):
sys.exit("ANTHROPIC_API_KEY is set: claude -p would use it and bill the API. Remove the variable first.")
if CLAUDE is None:
sys.exit("claude command not found. Open a new terminal; if it persists, fix PATH.")
candles = read_candles(DATA)
with open(OFFSETS, encoding="utf-8-sig") as f:
offsets = {r["day"]: r["offset_h"] for r in csv.DictReader(f)}
done = done_points("historical")
day = START
while day <= END:
ds = day_decisions(candles, day.isoformat())
if day.weekday() < 5 and not ds:
print("Skipping", day, "- box missing a candle, or no data for this day")
for q in ds:
if (q["point_utc"], VERSION) in done:
continue
r = run_point(candles, day.isoformat(), q, "historical", offsets.get(day.isoformat(), ""))
print(q["point_utc"], "agent", r["action"], "| code", q["action"], "|", r["violation"] or "valid")
day += timedelta(days=1)
print("Done. Log in logs/agent-signals.csv. Simulation on historical data, not investment advice.")
if __name__ == "__main__":
main()| You see | Cause | Fix |
|---|---|---|
claude command not found |
This PowerShell window doesn’t have Claude Code’s PATH | Open a new window; if it persists, add the install folder to PATH as in the install post |
ANTHROPIC_API_KEY is set ... |
The variable is still in this window | Remove it as in the install post, open a new window, rerun Test-Path Env:ANTHROPIC_API_KEY until it prints False |
FileNotFoundError for offset-by-day.csv or xau_m15_utc.csv |
The offset section wasn’t run | Run export_m15_server.py, then measure_offset.py |
Skipping 2026-... - box missing a candle |
One of the 7 box candles is missing | Note it in the conclusion; don’t swap in another day |
Technical error - stopping, with a line about login or limits |
Claude Code isn’t logged in, or the plan’s limit is reached | Run claude once to log in, or wait for the limit to reset; then rerun the same command |
Many VIOLATION: not bare JSON |
The agent adds text or ``` around the JSON | Don’t edit the log or the prompt mid-batch; note it, fix it in v2 |
VIOLATION: self-contradiction |
The agent wrote a high, low and close and concluded the opposite of its own numbers | Open the point’s file in logs/raw; count it as an agent error |
Count matches, misses and extras in three layers, with a cause
Run src/compare_xau_06.py again once the agent has finished. This time the
report has all three lines; read them in this order:
- Agent vs code. Both use the same broker data, so every difference here is the agent’s: violations, misses, extras.
- Code vs ledger. The data, time and position-state part, from the previous section.
- Agent vs ledger. The overall number people ask about, with a cause for each group of misses and extras.
Why read by layer? An agent that matches the ledger 95% of the time but twice called a trade with the close still inside the box is applying the rule wrongly. An agent matching only 85% because the first week’s clock was off may have done nothing wrong.
Don’t compare two overall match rates. A match rate only looks at the ledger side: with 145 trades, each miss moves it about 0.7 percentage points, while extras, including a trade called inside the box, don’t move it at all. Mismatches here also come in clusters rather than as independent noise: a whole week with the clock off, or a run of near-threshold cases from a different price source. So don’t put a confidence interval on this match rate; the interval in the luck-or-skill post is for a mean R and assumes independent trades. The measure here is the count of cases per cause, as in the locked criteria. The luck-or-skill post explains why one overall number on a small sample can look good or bad by luck alone.
An unclosed candle is one read by a script or an agent while it’s still forming, so its close isn’t final yet. On the historical candles of 2026-11-11, the 11:15 UTC candle traded up to 4055.957, above the buy line at 4055.917, then closed at 4053.527. Anyone reading that candle mid-way, while price sat above the line, would have seen BUY, though the rule had no signal.
| Cause | What it looks like in the report | How to check | What to do |
|---|---|---|---|
| Unclosed candle | A miss and an extra on the same side exactly 15 minutes apart; in a live shadow, an Unclosed candle or edited data line |
Shadow: open the point’s file in logs/snap; the last candle’s open time must equal signal_utc. Historical: compare last_close in the log with that candle’s close in the candle file |
Only take candles from position 1 (position 0 is forming); wait for the candle to close, plus a few seconds |
| DST | One whole week drops; pairs 60 minutes apart | data/offset-by-day.csv, the sure column |
Measure each day again with measure_offset.py; don’t touch the prompt |
| Different price source | Near threshold: close within 0.50 USD/oz of a line | Compare the broker’s close with the ledger’s entry price at the same time | Record it separately, don’t count it as an agent error, don’t tune the threshold to match |
| Position state | extra - ledger holding another trade |
The entry and exit times of the ledger trade span that point | Not an error; the shadow holds no trades so it always sees the signal |
| Variant or code convention | A burst of extras after the day’s first signal; extras on the 16:45 candle | Check which variant you exported; reread the rule: the candle opening 16:45 isn’t a signal candle | Export the right variant; fix the code to the letter of the rule, rerun the code-vs-ledger step |
| Agent misread | Line 1) has misses or extras; label agent's own; self-contradiction violations |
Open the point’s file in logs/raw; compare the box_high, box_low, last_close the agent wrote with the candle file |
Count it as an agent error; to fix, write prompt v2 and test it on a new period |
Column of reports/compare-xau-06-historical.csv |
Meaning |
|---|---|
signal_utc |
Signal candle open time, UTC |
side |
BUY or SELL |
ledger, code, agent |
1 if that source has this signal, 0 if not |
code_ledger, why_code_ledger |
match, ledger_only or code_only, with the suggested cause |
agent_ledger, why_agent_ledger |
match, missed or extra for the agent against the ledger, with the suggested cause |
distance |
How far the close went past the nearest line, USD/oz, on broker data; positive beyond, negative inside |
agent_reason |
The short reason the agent wrote at that point |
For a case labelled “see chart”, open the real chart before writing a cause: take the candle’s UTC time from the detail file, add that day’s offset to get the time on the MT5 chart, and look at that candle with both lines.
When you’ve looked at the cases, write reports/conclusion-compare-xau-06.md:
each criterion met or not, with the count and the denominator. Don’t compute
the win rate or the mean R of the matched trades: this post measures how the
rule is applied, not profit and loss. The conclusion rests on simulated
numbers from historical data, not investment advice.
Run the three-layer comparison:
cd C:\trading-agent-lab
.venv\Scripts\python src\compare_xau_06.py
notepad reports\compare-xau-06-historical.csv
notepad reports\conclusion-compare-xau-06.mdWhat you see: line 1) Agent vs code with points, violations, points equal to the code, misses and extras (plus a line counting points with no decision yet if the agent hasn’t finished); line 2) as before; line 3) Agent vs ledger with each group of causes; two Week lines. Read the CSV in Notepad; in Excel, only look and don’t save.
On the made-up files from the previous section, with a fake agent log that has two planted violations and one planted miss:
1) Agent vs code: 207 points, violations 2, same as code 204/207 | code signals 114, agent missed 1, agent extra 0
2) Code vs ledger (no AI): match 113/114, missed 1, extra 1
extra - data or time off: see chart: 1
missed - data or time off: see chart: 1
3) Agent vs ledger: match 112/114, missed 2, extra 1
extra - data or time off: see chart: 1
missed - agent missed it: code on the same data sees a signal: 1
missed - data or time off: see chart: 1See the cases on the candles
Draw the cases once for the whole period. src/plot_compare.py reads
data/xau_m15_utc.csv and reports/compare-xau-06-historical.csv and draws
M15 candles with Plotly (a charting library for Python, MIT licence). Each
day’s buy and sell lines come from day_decisions in src/xau_06.py.
Each signal candle gets a marker: a filled dot is a match, an open circle a
miss (ledger has it, agent doesn’t), an X an extra (agent has it, ledger
doesn’t). Hover a marker to see UTC time, side, distance and suggested cause;
drag on the chart to zoom into one day. Add --layer code_ledger to see code
against the ledger.
The HTML must open with no network. include_plotlyjs=True (the default)
copies the whole plotly.js library into the file for offline use; plotly
7.1.0 ships plotly.js 4.1.1, about 4.8 MB, so every file is about 4.8 MB even
with a few hundred candles. That’s normal. The value 'cdn' would leave only
a script tag that loads the library from the network when the file is
opened. The script sets include_plotlyjs=True explicitly, reads the file
back, and stops if any script tag has a src (loading from outside).
A note for the two-week shadow (next section): both ledger layers need a
ledger covering that period, so they can’t be drawn until it does. The script
stops and says the ledger only covers up to its last day; the measure then is
line 1) Agent vs code. Once a re-downloaded ledger covers both weeks, rerun
compare_xau_06.py --mode live with --start and --end for both weeks
(each nightly run only writes one day’s table), then draw with --mode live
and the same dates.
Draw the cases (if you did the backtest post, plotly==7.1.0 is already in
requirements-backtest.txt; skip the install line):
cd C:\trading-agent-lab
.venv\Scripts\python -m pip install plotly==7.1.0
notepad src\plot_compare.py
.venv\Scripts\python src\plot_compare.py
.venv\Scripts\python src\plot_compare.py --layer code_ledger
start reports\compare-agent_ledger-2026-10-26_2026-11-06.htmlWhat you see: each draw prints one Wrote line with the file size, candle
count and match, miss, extra counts; start opens the file in your default
browser. The default period is 2026-10-26 to 2026-11-06; change it with
--start and --end.
src/plot_compare.py:
# src/plot_compare.py: draw the src/compare_xau_06.py table on M15 candles with Plotly: match, missed, extra
# (agent or code vs the ledger), plus each day's XAU-06 buy and sell lines.
# Writes one self-contained HTML file: include_plotlyjs=True embeds plotly.js, so it opens with no network.
# Reads data/ and reports/ only, writes reports/ only. Calls no agent, sends no orders.
# Run: .venv\Scripts\python src\plot_compare.py --start 2026-10-27 --end 2026-10-28
import argparse
import csv
import re
import sys
from collections import Counter
from datetime import date, timedelta
from pathlib import Path
import plotly.graph_objects as go
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.ledger import read_ledger
from src.xau_06 import day_decisions, read_candles
GROUPS = { # table column -> value: (label, marker symbol, colour)
"agent_ledger": {"match": ("match", "circle", "#2563eb"), "missed": ("missed: ledger has it, agent not", "circle-open", "#d97706"),
"extra": ("extra: agent has it, ledger not", "x", "#dc2626")},
"code_ledger": {"match": ("match", "circle", "#2563eb"), "ledger_only": ("missed: ledger has it, code not", "circle-open", "#d97706"),
"code_only": ("extra: code has it, ledger not", "x", "#dc2626")},
}
ap = argparse.ArgumentParser()
ap.add_argument("--start", default="2026-10-26")
ap.add_argument("--end", default="2026-11-06")
ap.add_argument("--mode", default="historical", help="historical or live")
ap.add_argument("--layer", default="agent_ledger", choices=list(GROUPS), help="agent_ledger or code_ledger")
a = ap.parse_args()
START, END = date.fromisoformat(a.start), date.fromisoformat(a.end)
inside = lambda t: START <= date.fromisoformat(t[:10]) <= END
last = max((t["signal"].date() for t in read_ledger()), default=None) # last day with a ledger trade
if last is None or END > last:
sys.exit(f"The ledger only covers up to {last}: can't draw the ledger layers for {START} to {END}. "
"In the shadow, read line 1) Agent vs code; draw once a re-downloaded ledger covers the whole period.")
candles = {t: x for t, x in read_candles(ROOT / "data" / "xau_m15_utc.csv").items() if inside(t)}
if not candles:
sys.exit(f"No candle from {START} to {END} in data/xau_m15_utc.csv.")
times = sorted(candles)
with open(ROOT / "reports" / f"compare-xau-06-{a.mode}.csv", encoding="utf-8-sig") as f:
everything = [r for r in csv.DictReader(f) if inside(r["signal_utc"])]
if everything and not any(r["ledger"] == "1" for r in everything):
sys.exit("The ledger doesn't cover this period: can't draw the ledger layers. Read line 1) of compare_xau_06.py.")
in_table = {r["signal_utc"][:10] for r in everything}
missing_days = sorted(d for d in {t[:10] for t in candles} - in_table
if any(q["action"] != "STAY_OUT" for q in day_decisions(candles, d)))
if missing_days: # table built for another period, e.g. the nightly run covers one day
sys.exit(f"The comparison table lacks {len(missing_days)} days with signals ({missing_days[0]} ... {missing_days[-1]}): "
"rerun compare_xau_06.py with the same --mode, --start, --end, then draw again.")
table = [r for r in everything if r[a.layer] in GROUPS[a.layer]]
fig = go.Figure(go.Candlestick(x=times, open=[candles[t]["open"] for t in times], high=[candles[t]["high"] for t in times],
low=[candles[t]["low"] for t in times], close=[candles[t]["close"] for t in times],
name="XAUUSD M15 (UTC)"))
for name, col, colour in (("buy line = box high + 0.05", "buy_line", "#16a34a"), ("sell line = box low - 0.05", "sell_line", "#dc2626")):
x, y, day = [], [], START
while day <= END: # one flat segment per day over the 11:00-16:30 UTC signal candles
q = day_decisions(candles, day.isoformat())
if q:
x += [q[0]["signal_utc"], q[-1]["signal_utc"], None]
y += [q[0][col], q[-1][col], None]
day += timedelta(days=1)
fig.add_trace(go.Scatter(x=x, y=y, mode="lines", name=name, line={"color": colour, "dash": "dot", "width": 1}))
count = Counter(r[a.layer] for r in table)
for value, (label, symbol, colour) in GROUPS[a.layer].items():
rows = [r for r in table if r[a.layer] == value and r["signal_utc"] in candles]
fig.add_trace(go.Scatter(
x=[r["signal_utc"] for r in rows], y=[candles[r["signal_utc"]]["close"] for r in rows],
mode="markers", name=f"{label} ({len(rows)})",
marker={"symbol": symbol, "size": 11, "color": colour, "line": {"width": 2, "color": colour}},
hovertext=[f"{r['signal_utc']} UTC · {r['side']} · distance {r['distance']} · {r['why_' + a.layer] or label}"
for r in rows], hoverinfo="text"))
summary = ", ".join(f"{v[0].split(':')[0]} {count[k]}" for k, v in GROUPS[a.layer].items())
fig.update_layout(title=f"XAU-06 · {a.layer.replace('_ledger', '')} vs ledger · {START} to {END} · {summary}",
xaxis_title="signal candle open time, UTC", yaxis_title="USD/oz",
xaxis_rangeslider_visible=False, height=650)
out = ROOT / "reports" / f"compare-{a.layer}-{START}_{END}.html"
fig.write_html(out, include_plotlyjs=True, full_html=True) # True embeds plotly.js; "cdn" would need the network
remote = re.findall(r"<script[^>]*\ssrc=", out.read_text(encoding="utf-8"))
if remote:
sys.exit(f"STOP: the HTML file has {len(remote)} script tags loading from outside: check include_plotlyjs.")
print(f"Wrote {out.relative_to(ROOT).as_posix()} | {out.stat().st_size / 1e6:.1f} MB | {len(times)} M15 candles | "
f"{summary} | no external script tags | Simulation on historical data, not investment advice.")Sample output (made-up candles, ledger and agent log, to test the script):
.venv\Scripts\python src\plot_compare.py --start 2026-10-27 --end 2026-10-28
Wrote reports/compare-agent_ledger-2026-10-27_2026-10-28.html | 4.8 MB | 184 M15 candles | match 26, missed 1, extra 0 | no external script tags | Simulation on historical data, not investment advice.| You see | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'plotly' |
.venv doesn’t have Plotly |
Run the pip install plotly==7.1.0 line above |
FileNotFoundError for reports\compare-xau-06-historical.csv |
compare_xau_06.py hasn’t run, or ran with another --mode |
Run it first, with the same --mode |
FileNotFoundError for data\xau_m15_utc.csv |
The offset section wasn’t run | Run export_m15_server.py, then measure_offset.py |
No candle from ... to ... |
--start, --end outside the candle file’s dates |
Check the first and last dates of the file; export again if needed |
The ledger only covers up to ... or doesn't cover this period |
You’re in the shadow weeks, or --end is after the ledger’s last day |
Read line 1) Agent vs code; draw only once a re-downloaded ledger covers the period and compare_xau_06.py has been rerun |
The comparison table lacks ... days with signals |
The table was built for another period, e.g. the nightly one-day run | Rerun compare_xau_06.py with the same --mode, --start, --end, then draw again |
| Legend counts smaller than the title’s | Some cases have no signal candle in the broker file (why_code_ledger says broker data missing), or the candle file changed after the comparison |
Filter those rows in the CSV; scroll the MT5 M15 chart to that day and export again; if the broker still has no candle, record it as missing data, not an agent error |
STOP: the HTML file has ... script tags loading from outside |
include_plotlyjs was changed to "cdn" or a path |
Set it back to True |
When you’re done: add a reports/*.html line at the end of .gitignore
(drawings can be regenerated and each is 4.8 MB), then git add .gitignore src logs tests reports\compare-xau-06-historical.csv reports\conclusion-compare-xau-06.md and git commit -m "Compare XAU-06 with the backtest ledger".
Two weeks of forward shadow, and when to stop
The historical comparison tells you how the agent applies the rule to data that already exists. A forward shadow (real time, no orders) also tests what only happens live: unclosed candles, late prices, a slow network, plan usage limits, a model change.
src/shadow_xau_06.py runs each trading day. Start it before 11:15 UTC and
leave the window open until it stops by itself after the 16:45 UTC point. At
each point from 11:15 to 16:45 UTC it takes five steps:
- Waits for the candle to close, plus 20 seconds.
- Reads 40 closed candles starting at position 1 (position 0 is the candle still forming).
- Measures the offset by comparing the last price’s time with the PC clock.
- Saves a snapshot of the candles it just read.
- Lets the code and the agent decide, then logs both. No order is sent.
The ledger ends on 2026-11-11, so it doesn’t cover these two weeks. The
measure in the shadow is the code replica, which the previous sections already
checked against the ledger. When a newer ledger covers your two weeks,
download it again and run compare_xau_06.py for exactly those two weeks.
The stop conditions live in code, not in instructions. The script creates the
STOP file (the kill switch from the demo-order post) and exits when it hits
one of them:
| Gate | When | Condition | Script does | You do |
|---|---|---|---|---|
| 1 | Before the agent | The last candle isn’t the expected one after 3 reads | Prints a no-decision line, no agent call at that point | Could be a holiday, an early close or a lost connection; e.g. US Thanksgiving on 2026-11-26, when a broker may close early |
| 2 | Before the agent | The live offset differs from the locked OFFSET_H |
Creates STOP, exits | Measure again as in the offset section; change OFFSET_H, commit, delete STOP |
| 3 | After the agent | Agent says BUY or SELL while the code sees the close more than 0.30 USD inside the box | Creates STOP, exits | Open the point’s files in logs/raw and logs/snap; record the incident; no more runs that day |
| 4 | After the agent | 3 violations in a row | Creates STOP, exits | Read the reasons in the log; if it was the network or the usage limit, fix it and rerun |
| 5 | After the agent | The actual model differs from the pinned one (Haiku running in the background excepted) | Creates STOP, exits | Treat it as model drift, as in the cost-and-drift post; check again as in the shadow-mode post before going on |
| 6 | After the agent | The day’s estimated cost reaches the cap | Stops until the next day | Look at est_cost_usd; don’t raise the cap mid-batch |
| - | Start of day | Today’s box is missing a candle | No decision all day | Note it in the journal; not an agent error |
If there’s a STOP file: read the reason, fix the cause, delete the file, then run again.
Before the first day, three steps:
- Set
OFFSET_Hin the script to the number the offset table shows for the latest week. - Add up
est_cost_usdfor one 23-point day from the historical run. If the total is near or above 1.50, setDAILY_BUDGETa little above it. - Commit. From here on, don’t change those two numbers mid-batch.
cd C:\trading-agent-lab
notepad src\shadow_xau_06.py
git add src\shadow_xau_06.py
git commit -m "Shadow XAU-06: lock offset"Each trading day, before 11:15 UTC, with the MT5 demo open:
.venv\Scripts\python src\shadow_xau_06.pyWhat you see: nothing until the first point, then one line every 15 minutes,
like 2026-11-16 11:15 agent STAY_OUT | code STAY_OUT | snapshot 3f2a9c1b | valid. At the end, one summary line with points, points equal to the code and
the estimated cost. Started late, points more than 10 minutes old are skipped
with no catch-up decision.
Each evening after the last point, replace 2 with OFFSET_H and the date with
the day you just ran:
.venv\Scripts\python src\export_m15_server.py
.venv\Scripts\python src\measure_offset.py --new-days 2
.venv\Scripts\python src\compare_xau_06.py --mode live --start 2026-11-16 --end 2026-11-16
git add logs reports data
git commit -m "Shadow XAU-06 2026-11-16"On the last day, rerun compare_xau_06.py with --start the first day and
--end the last day of the two weeks, and copy the result into
reports/conclusion-compare-xau-06.md.
src/shadow_xau_06.py:
# src/shadow_xau_06.py: forward shadow for XAU-06. At each M15 close from 11:15 to 16:45 UTC: read CLOSED candles
# from the MT5 demo, the code decides, the agent decides, both are logged. NO order is ever sent.
# Run each trading day before 11:15 UTC and leave the window open until the script stops on its own.
import csv
import hashlib
import os
import sys
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
import MetaTrader5 as mt5
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.xau_06 import TF, day_decisions
from src.run_agent_xau_06 import LOG, MODEL, VERSION, run_point
SYMBOL = os.environ.get("TL_SYMBOL", "XAUUSD")
OFFSET_H = 2 # what measure_offset.py found for the latest week; a different live reading stops the run
DAILY_BUDGET = 1.50 # cap on the day's estimated cost, USD
STOP = ROOT / "STOP" # the kill switch from the demo-order post
def stop(reason):
STOP.write_text(f"{datetime.now(timezone.utc):%Y-%m-%d %H:%M} UTC {reason}\n", encoding="utf-8")
sys.exit("STOP FILE CREATED: " + reason)
def read_mt5():
"""Returns (measured offset in hours, closed candles keyed by UTC open time). Read only."""
path = os.environ.get("TL_MT5_PATH", "").strip('"')
if not (mt5.initialize(path) if path else mt5.initialize()):
sys.exit(f"initialize() error: {mt5.last_error()}")
try:
acc = mt5.account_info()
if acc is None or acc.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO:
stop("the terminal is not logged in to a demo account")
mt5.symbol_select(SYMBOL, True)
tick = mt5.symbol_info_tick(SYMBOL)
rates = mt5.copy_rates_from_pos(SYMBOL, mt5.TIMEFRAME_M15, 1, 40) # position 0 is the forming candle: skip it
finally:
mt5.shutdown()
if tick is None or rates is None or len(rates) == 0:
return None, {}
secs = tick.time - time.time()
offset = round(secs / 3600)
if abs(secs - offset * 3600) > 600: # last price older than 10 minutes: can't measure yet
return None, {}
candles = {}
for r in rates:
t = datetime.fromtimestamp(int(r["time"]) - offset * 3600, timezone.utc).strftime(TF)
candles[t] = {"open": float(r["open"]), "high": float(r["high"]), "low": float(r["low"]), "close": float(r["close"])}
return offset, candles
def main():
if os.environ.get("ANTHROPIC_API_KEY"):
sys.exit("ANTHROPIC_API_KEY is set: claude -p would use it and bill the API. Remove the variable first.")
today = datetime.now(timezone.utc).date().isoformat()
if datetime.now(timezone.utc).weekday() >= 5:
sys.exit("It's the weekend in UTC: no XAU-06 points today.")
points = [f"{today} {h:02d}:{m:02d}" for h in range(11, 17) for m in (0, 15, 30, 45)][1:24] # 11:15 to 16:45
in_a_row, cost = 0, 0.0
if LOG.exists(): # restarted mid-day: carry on the logged cost, skip logged points
with open(LOG, encoding="utf-8-sig") as f:
old = [r for r in csv.DictReader(f) if r["mode"] == "live" and r["point_utc"].startswith(today)
and r["prompt_version"] == VERSION]
cost = sum(float(r["est_cost_usd"] or 0) for r in old)
points = [p for p in points if p not in {r["point_utc"] for r in old}]
for point in points:
t_point = datetime.strptime(point, TF).replace(tzinfo=timezone.utc)
wait = (t_point - datetime.now(timezone.utc)).total_seconds() + 20
if wait < -600:
continue # point passed more than 10 minutes ago: no catch-up decision
if wait > 0:
time.sleep(wait) # wait for the candle to close, plus 20 seconds
if STOP.exists():
sys.exit("STOP file present: stopping, no agent call. Read the reason in the STOP file.")
signal = (t_point - timedelta(minutes=15)).strftime(TF)
for _ in range(3): # the new candle has no first price yet: wait a little more
offset, candles = read_mt5()
if candles and max(candles) == signal:
break
time.sleep(30)
if offset is None or not candles or max(candles) != signal:
print(point, "no decision: last candle isn't the expected one, or no fresh price")
continue
if offset != OFFSET_H:
stop(f"measured server offset +{offset}h differs from +{OFFSET_H}h: check DST, then measure again")
q = next((x for x in day_decisions(candles, today) if x["point_utc"] == point), None)
if q is None:
sys.exit("Today's box is missing a candle: no decision today. Note it in the journal.")
snap = ROOT / "logs" / "snap" / f"{point.replace(':', '-').replace(' ', '_')}.csv"
snap.parent.mkdir(parents=True, exist_ok=True)
snap.write_text("time_utc,open,high,low,close\n" + "\n".join(
f"{t},{x['open']},{x['high']},{x['low']},{x['close']}" for t, x in sorted(candles.items())), encoding="utf-8")
r = run_point(candles, today, q, "live", offset)
cost += float(r["est_cost_usd"] or 0)
in_a_row = in_a_row + 1 if r["action"] == "VIOLATION" else 0
print(point, "agent", r["action"], "| code", q["action"], "| snapshot",
hashlib.sha256(snap.read_bytes()).hexdigest()[:8], "|", r["violation"] or "valid")
if r["action"] in ("BUY", "SELL") and q["action"] == "STAY_OUT" and q["distance"] < -0.30:
stop(f"{point}: agent {r['action']} while the code sees the close inside the box ({q['distance']} USD)")
if in_a_row >= 3:
stop("3 violations in a row: read logs/raw before running again")
other = [m for m in r["model_actual"].split(",") if m and m != MODEL and "haiku" not in m]
if other:
stop(f"actual model {other} differs from the pinned model: model drift")
if cost >= DAILY_BUDGET:
sys.exit(f"Day's estimated cost cap reached ({cost:.2f} USD): stopping until tomorrow.")
if not LOG.exists():
sys.exit(f"End of {today}: no point logged.")
with open(LOG, encoding="utf-8-sig") as f:
day = [r for r in csv.DictReader(f) if r["mode"] == "live" and r["point_utc"].startswith(today)
and r["prompt_version"] == VERSION]
same = sum(r["action"] == r["code_action"] for r in day)
print(f"End of {today}: {len(day)} points, same as code {same}, estimated cost {cost:.2f} USD."
" Simulation, not investment advice.")
if __name__ == "__main__":
main()Tested on a fake MT5 and a fake clock for 2026-11-16 (made-up candles, a stand-in agent): a normal day logged 23 points; a rerun skipped all of them; a server clock one hour off created STOP at 11:15; a stand-in agent calling BUY 0.398 inside the box created STOP at that point.
At the end of the two weeks, decide by the locked criteria, not by P&L. The shadow’s hypothetical trades adding up to a profit isn’t a reason to go on; adding up to a loss isn’t a reason to stop. The reasons to stop are three: the agent doesn’t apply the rule correctly, the data can’t be trusted, or the agent adds nothing over the code. Meeting every criterion only says the agent applies the rule correctly. It doesn’t say the rule is worth trading.
The backtest numbers make that plain. With the default variant and standard costs, XAU-06 has a mean R of −0.851 over 30,802 trades from January 2018 to 2026-11-11: on average each trade loses about 0.85 times the money at risk. In 6,925 trades a single M5 candle touched both SL and TP, so it’s unknown which came first; the backtest counts SL first. Counting TP first, the mean R is still −0.374. This is a simulation on historical data, not investment advice.
| Result after two weeks, by the locked criteria | Decision |
|---|---|
| Every line met, in both the historical comparison and the shadow | You may move the agent to level 2 for XAU-06, on demo only and to practise the process: the agent proposes, code checks, you approve each order as in the demo-order post. Meeting the criteria doesn’t mean XAU-06 makes money after costs (see the backtest numbers above) |
| Not met because of the data layer: clock offset, missing candles | Fix the data and the offset measurement, run a new shadow |
| Not met because of the agent: extras with the close inside the box, misses over the threshold | Stop giving signal-finding to the agent: code finds, the agent only journals and explains; or write prompt v2 and run a new batch |
| Met, but the code did everything right and the agent added nothing you can verify | Stopping is a reasonable conclusion too: keep the rule in code, one less source of errors and cost |
Any order connection, at level 2, uses a demo account only, with a person approving each order first.
Try it: the XAU-06 signal prompt (save as prompts/xau-06-v1.md)
<role>
You apply exactly one trading rule to the data given. You don't forecast prices, don't use knowledge outside the data and don't place orders. Your answer is only logged for comparison.
</role>
<rule name="XAU-06 London box close-breakout" symbol="XAUUSD" timeframe="M15" timezone="UTC">
1. The box of [DAY] is the 7 candles opening at 09:15, 09:30, 09:45, 10:00, 10:15, 10:30, 10:45. box_high = the highest high of those 7 candles; box_low = the lowest low of those 7 candles.
2. buy_line = box_high + 0.05. sell_line = box_low - 0.05.
3. Look only at the last candle in the data: the candle that just closed, opening at [SIGNAL_CANDLE_UTC].
4. BUY when the last candle's close is strictly above buy_line. SELL when the last candle's close is strictly below sell_line. A close equal to a line, or between the two lines, is STAY_OUT. A wick (high or low) beyond a line with the close not beyond it is still STAY_OUT.
5. Don't compute lot, SL or TP. Code does that.
</rule>
<data until="[POINT_UTC]">
[CANDLES_CSV]
</data>
<constraints>
The time_utc column is the candle's OPEN time in UTC. Every row in data is a closed candle; the last one closes exactly at [POINT_UTC].
Use only the numbers in data, copied exactly as written, not rounded. Don't infer anything that happens after [POINT_UTC].
</constraints>
<self_check>
Before answering, check and don't write the check outside the JSON: (1) all 7 box candles are present; (2) box_high and box_low come from those 7 candles; (3) compare the last candle's close with the two lines as in rule 4.
</self_check>
<output>
ONLY one JSON object, no text outside the JSON, not wrapped in ```. Exactly 9 fields as in the template; box_high, box_low, last_close are numbers:
{"point_utc": "[POINT_UTC]", "method": "XAU-06", "signal_utc": "[SIGNAL_CANDLE_UTC]", "action": "BUY or SELL or STAY_OUT", "box_high": 0, "box_low": 0, "last_close": 0, "short_reason": "at most 200 characters, name the close and the line compared", "prompt_version": "[VERSION]"}
</output>The parts in [brackets] are filled by the script at each point. 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: period, variant, cost scenario, ledger hash and criteria, committed to git before the first run.
- Data and clock next: export candles in server time, measure the offset day by day from ledger prices, convert to UTC.
- Code before AI: compare the code replica with the ledger; every mismatch needs a cause you can check.
- Agent after: same data, closed candles only, no tools, pinned model; code checks every answer.
- Count in three layers: agent vs code, code vs ledger, agent vs ledger; one cause per mismatch.
- Two-week forward shadow with the stop conditions in code; demo only, no order sent.
- Conclude by the locked criteria, not by P&L; a changed prompt is a new version, tested on a new period.
Key takeaways
- The ledger only holds filled trades and carries position state: while a trade is open, new signals are dropped.
- One whole week out of line is usually a DST clock change: fix the data, not the prompt.
- Change the prompt only when the agent differs from the code on the same data; test the new version on an unused period, then run a two-week shadow.
Comments