Asking an agent “should I enter?” with a chart screenshot is the easiest way to get it wrong. Paste a picture and a page of method notes, and the agent reads numbers off the image, computes EMAs in its head and guesses whether a position is already open.
This post does the opposite. It writes an 11-part spec for one gold method, exports H1 candles from an MT5 demo, codes an answer key with nine tests, lets the agent score each condition, and grades the agent field by field.
Terms used below:
- Spec (specification): a document stating the inputs, conditions, hours, output and tests of a method, tight enough that code and an agent reading it reach the same conclusion.
- Answer key: the spec written as deterministic code (same input, same result). It grades the agent and doesn’t need one itself.
- Candles [2], [1], [0]: [1] just closed, [2] closed right before it, [0] is still forming. This spec only hands over [2] and [1].
- Entry candle: the next candle in the data after [1]. Its open time is
time_utc, the reference for the hour window and for Friday. - Strict comparison: strictly greater or strictly smaller. Two numbers equal in every displayed digit don’t pass.
- Near-threshold case: a comparison that sits very close to its threshold, here under 0.10 USD. Another price source or another rounding can flip it.
- Gap: the entry candle doesn’t follow [1] directly, because of the daily break, the weekend or missing data.
- Human label: a subjective call such as “this is a key level”, written down as a fixed value with the time it was written, before the signal candle exists.
- Self-contradiction: the agent scores the conditions one way and acts another, say a false condition followed by BUY.
- Independent reference: indicator code written by someone else (TA-Lib,
pandas-ta-classic) used to check the answer key’s
emaandatr; not the same thing as the answer key that grades the agent.
What a spec is and why an agent needs one
A method written for people leaves gaps that people fill without noticing: “enter at the open of the next candle”, “skip Fridays”, “only consider 07:00–21:00 UTC”. A trader who has practised it knows which candle “next” means. An agent doesn’t. It fills gaps with guesses, and each time you ask it may guess differently.
The usual gaps: time and day (UTC or local, signal candle or entry candle), price source, how indicators are computed, rounding, and whether a position is open. A spec closes them before the agent sees data and splits the work:
- Code computes every number and holds the answer.
- The agent reads the numbers, scores each condition and writes a reason.
- You review and decide.
The morning report already let code compute the levels, and shadow mode already wrote the baseline rule in code. This goes one step further: the answer isn’t just BUY or SELL but every condition, so when the agent is wrong you know which line it got wrong.
The frame has 11 sections. If a section can’t be written as a number or a time-stamped label, the method isn’t ready to hand to an agent.
A few symbols first. BID is the price you can sell at right now; the spec
says the candles are built from BID. ddof is how a standard deviation
divides: ddof = 0 divides by n, ddof = 1 by n − 1. [07:00, 21:00) is
half-open: 07:00 is in, 21:00 is out.
| Section | Answers | XAU-01 example |
|---|---|---|
| 1. Identity | Which method, version, symbol, timeframe? | xau-01-v1, XAUUSD, H1, BID |
| 2. Inputs | Exactly which numbers does the agent see, prepared by whom? | [2]: close, ema21. [1]: close, three EMAs, atr14. Prepared by code |
| 3. Indicators | Formula, seed, ddof, rounding, warm-up, which independent reference? |
EMA factor 2/(n+1) seeded with the first close, ≥1,500 H1 candles; ATR is the mean of 14 True Ranges; no standard deviation; checked against TA-Lib and pandas-ta-classic (ATR with mamode="sma") |
| 4. Closed candles | Numbers up to which candle? | Only [2] and [1], never the forming candle |
| 5. Conditions | Each a true/false sentence; strict or inclusive? | Three EMAs stacked; [2] pulls back; [1] reclaims; strict |
| 6. Time and state | Which hours, which zone, by which candle; what if a trade is open? | [07:00, 21:00) UTC by the entry candle; no Friday UTC; at most one position |
| 7. Action and prices | Which actions; who computes entry, SL, TP, lot? | BUY, SELL, STAY_OUT; prices and lot by code |
| 8. Output | What the agent returns, how many fields, which values? | One 11-field JSON, no prices |
| 9. Chosen interpretations | Where the method is silent, what did you pick? | Time by the entry candle; half-open window |
| 10. Tests | Which tests must pass; how is the agent graded? | 9 tests; field-by-field grading on about 20 cases |
| 11. Human part | What isn’t handed to a machine? | Server time offset, approving demo trades, flags, major news |
The XAU-01 spec: from method notes to 11 sections
XAU-01, the three-layer EMA21 pullback, is a gold method on H1. Two indicators: an EMA (exponential moving average) weights recent candles more; ATR14 is the average range of 14 candles in USD per ounce, built from the True Range, a candle’s real range including any jump from the previous close.
The rules:
- EMA21, EMA55 and EMA200 stacked in order decide whether only BUY or only SELL is considered.
- Candle [2] closing on the wrong side of EMA21 is the pullback.
- Candle [1] closing back on the right side is the reclaim.
- A market order (filled at once at the market price) opens at the start of the next H1 candle, SL 1.5 × ATR14 away, TP 3 × ATR14 away.
The method is written fairly completely, so most of the spec is copying it tightly. Four places need an interpretation, and each can change the result:
- Hours and Friday go by the entry candle, in UTC. An entry candle opening at 17:00 UTC on Thursday is already Friday 00:00 on a UTC+7 clock and still counts.
- The hour window is half-open, so a candle opening at 21:00 UTC is outside.
- Comparisons are strict (equal fails), matching the method’s own “if a condition is equal, skip”.
- Code compares the rounded numbers, exactly as the agent sees them.
The first three are the interpretations chosen for XAU-01; the fourth is needed to grade an agent.
Two jobs go to code entirely. Entry, SL, TP and lot, because a language
model’s arithmetic can be wrong without saying so. And the “XAU-01 position
open” state, read from MT5 or filled in by you, because candles can’t tell
you. In the data, a BUY entered at 09:00 UTC on 2026-11-09 (fixed SL/TP) was
still open at 19:00 UTC, so the 19:00 signal that day must be STAY_OUT even
though [2] and [1] both qualify. That’s a simulation on historical data, not
investment advice.
Save the spec as specs/xau-01-v1.md and commit it before writing any code.
From here, changing one word is a new version.
cd C:\trading-agent-lab
New-Item -ItemType Directory -Force specs, prompts, data, tests
notepad specs\xau-01-v1.mdPaste, replace [DATE], Ctrl+S (choose UTF-8 if Notepad offers an Encoding
box):
# Spec xau-01-v1 | XAU-01 three-layer EMA21 pullback (H1) | written on [DATE]
Change any line and it becomes xau-01-v2, committed.
1. Identity: rule xau-01 | XAUUSD | H1 | BID prices | UTC times.
2. Inputs (prepared by code; the agent fetches nothing):
candle_2: time_utc, close, ema21
candle_1: time_utc, close, ema21, ema55, ema200, atr14
time_utc: open time of the entry candle (the next candle in the data)
data_until: close time of candle [1]
has_position: code reads the demo positions with positions_get, filtered by magic number, or you fill it in
3. Indicators: EMA on close, factor 2/(n+1). Seed: first EMA = first close (the choice made here), not the mean
of the first n closes that TA-Lib and pandas-ta-classic use by default; at least 1,500 H1 warm-up candles.
ATR14 = simple mean of the last 14 True Ranges, no Wilder smoothing. Standard deviation: not used
(a Bollinger method would state ddof = 0, dividing by n as MT5 does). Prices and EMAs rounded to 3 decimals, ATR to 5.
Independent reference (compared from candle 1,500, tolerance 0.0005 USD): talib.EMA, talib.SMA(talib.TRANGE(...), 14);
pandas-ta-classic 0.9.0 with talib=False: ema(sma=False), atr(mamode="sma"); the default atr is Wilder, not used.
Before use: compare one candle with the MT5 Data Window; a difference above 0.01 means stop and find out why.
4. Closed candles: only [2] and [1]. No row of the forming candle [0].
5. Conditions (strict comparisons; equal doesn't pass):
trend: UP if ema21 > ema55 > ema200 on [1]; DOWN if ema21 < ema55 < ema200; otherwise NONE
pullback_2: UP: close[2] < ema21[2]; DOWN: close[2] > ema21[2]
reclaim_1: UP: close[1] > ema21[1]; DOWN: close[1] < ema21[1]
6. Time and state, by the entry candle:
in_hours: open time within [07:00, 21:00) UTC
not_friday: the UTC day isn't Friday | no_position: no XAU-01 position open
7. Action: BUY if UP and the five conditions of sections 5-6 are all true; SELL if DOWN and all five are true;
otherwise STAY_OUT. Prices by code: BUY at the Ask, SELL at the Bid of the entry candle's opening quote;
SL 1.5 x atr14 from entry, TP 3 x atr14. Lot by code, rounded down to steps of 0.01;
if 0.01 lot already exceeds the risk budget, skip.
8. Agent output: one 11-field JSON as in prompts/xau-01-v1.md. Flag NEAR_THRESHOLD when a comparison is
within 0.10 USD of its threshold; GAP when the entry candle doesn't follow [1]. Flags never change the decision.
9. Interpretations chosen where the method is silent: hours and Friday by the entry candle, in UTC;
half-open hour window; strict comparisons; compare the rounded numbers. If agent and code differ: code wins, then review the case.
10. Tests: tests/test_xau_01.py passes 9/9; the agent is graded by src/grade_spec.py on cases chosen by code.
11. The human's part: measure the server time offset, read the Specification, handle flags, approve every demo proposal,
decide around major news or odd data.git add specs\xau-01-v1.md
git commit -m "Spec xau-01-v1"Git prints a line with a short commit ID and 1 file changed.
nothing to commit means the file wasn’t saved: Ctrl+S in Notepad and rerun.
Inputs: export H1, measure the time offset, closed candles only
The agent fetches no data. src/export_h1.py reads H1 candles from the open
MT5 terminal logged in to demo (the investor, read-only password is enough)
and writes data/xauusd_h1_utc.csv with five columns: time_utc, open,
high, low, close. It starts at 2026-07-01 so EMA200 gets more than
1,500 warm-up candles before the November cases; with fewer, your EMAs won’t
match the Data Window (Ctrl+D in MT5). The MetaTrader5 library is
Windows-only.
Time is where every spec goes wrong first. HOUR_OFFSET is how many hours the
file’s times run ahead of UTC. MT5 is documented to store candle open times in
UTC, but check it yourself:
- Run the script with
HOUR_OFFSET = 0. - Open the CSV in Notepad, Ctrl+F for
2026-11-09. - Find the candle that rose more than 30 USD in an hour, opening near 4,104 and closing near 4,136. (Early that day there’s another candle up almost 50 USD from near 4,055; don’t confuse them.) Your broker’s prices differ by a few tens of cents, but it’s easy to spot.
- In UTC that candle opens at 19:00. The hour on that row minus 19 is
HOUR_OFFSET: a row at 21:00 on 11-09 means 21 − 19 = 2. If the row is on 11-10, add 24 first. - Put the number into
HOUR_OFFSETand rerun.
Only the case window, 2026-11-02 to 11-10, needs to be exact; it falls after both the European (10-25) and US (11-01) switches to winter time. If your broker shifts with the seasons, warm-up candle labels from July may be an hour off; EMA and ATR don’t use labels, so they don’t change.
Closed candles means the agent’s input holds only [2] and [1]. The entry
candle is the next row in the file; its open time is time_utc, and the close
time of [1] is data_until. They usually coincide. When they don’t, code adds
the GAP flag: for example [1] is the 21:00 UTC Friday candle and the next
opens at 23:00 UTC Sunday. Gold’s daily break also makes the candle after
20:00 UTC (summer) or 21:00 UTC (winter) open an hour late.
cd C:\trading-agent-lab
notepad src\export_h1.py
.venv\Scripts\python src\export_h1.py
notepad data\xauusd_h1_utc.csvsrc/export_h1.py:
# src/export_h1.py: export H1 candles from the MT5 demo to a UTC CSV. Read only, sends no order.
# Run with the MT5 terminal open and logged in to demo (the 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's name may carry a suffix
OUT = "data/xauusd_h1_utc.csv"
HOUR_OFFSET = 0 # how many hours the file's times run ahead of UTC; measure it on the 2026-11-09 candle
FROM = datetime(2026, 7, 1, tzinfo=timezone.utc) # from July for more than 1,500 warm-up candles
TO = datetime(2026, 11, 11, tzinfo=timezone.utc)
path = os.environ.get("TL_MT5_PATH", "").strip('"') # only needed with several terminals
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 isn't logged in to a demo account.")
mt5.symbol_select(SYMBOL, True) # show the symbol in Market Watch if hidden
rates = mt5.copy_rates_range(SYMBOL, mt5.TIMEFRAME_H1, FROM, TO)
err = mt5.last_error()
finally:
mt5.shutdown()
if rates is None or len(rates) == 0:
raise SystemExit(f"Could not read {SYMBOL} candles: {err}")
rows = []
for r in rates:
t = datetime.fromtimestamp(int(r["time"]), timezone.utc) - timedelta(hours=HOUR_OFFSET)
rows.append([t.strftime("%Y-%m-%dT%H:%M:%SZ"), float(r["open"]), float(r["high"]),
float(r["low"]), float(r["close"])])
os.makedirs("data", exist_ok=True)
with open(OUT, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["time_utc", "open", "high", "low", "close"])
w.writerows(rows)
print(len(rows), "H1 candles written to", OUT, "| first", rows[0][0], "| last", rows[-1][0])You see a line like
2179 H1 candles written to data/xauusd_h1_utc.csv | first 2026-07-01T00:00:00Z | last 2026-11-10T23:00:00Z.
The count and the first and last times depend on the broker; usually over
2,000. A first candle much later than 07-01 means the terminal hasn’t
downloaded enough history: open an H1 chart of the symbol, scroll back to July
2026 and rerun. After measuring, set HOUR_OFFSET, save, rerun, and check the
30-USD candle now sits at 19:00 on 11-09.
| You see | Cause | Fix |
|---|---|---|
No module named 'MetaTrader5' |
Not in .venv |
.venv\Scripts\python -m pip install MetaTrader5 |
initialize() error |
MT5 closed or not logged in | Open MT5, log in to demo, rerun |
STOP: the terminal isn't logged in to a demo account |
A live account is open, or the script attached to the wrong terminal | Log in to demo; with several terminals set $env:TL_MT5_PATH |
Could not read XAUUSD candles |
The broker’s symbol has a suffix, or no history yet | $env:TL_SYMBOL = "the right name" and rerun in the same window; open an H1 chart and scroll back to July 2026 |
The answer key and nine tests built from real candles
src/xau_01.py is the spec in code:
emaandatrcompute the indicators exactly as section 3 says;evaluatetakes [2], [1], the entry time and the position state and returns every condition and the action, the same fields the agent must return;flagsadds flags without changing the decision;price_levelscomputes entry, SL and TP;make_casebuilds the agent’s input and the code’s answer from the same candle.
The main part chooses cases by rule, never by eye: every candle meeting all three candle conditions with an entry candle from 2026-11-02 to 11-10, plus one 10:00 UTC point per day, plus a copy that assumes a position is open.
The agent’s input also carries server_time, the entry time on a typical
UTC+2 broker clock. It’s there for humans and as a trap: a Thursday 22:00 UTC
entry is Friday 00:00 on that clock.
Before trusting the answer key, test it. tests/test_xau_01.py has nine
cases, with numbers from real H1 BID candles, and needs no CSV or MT5:
- BUY on 2026-11-09 with entry 4,104.684, SL 4,083.707, TP 4,146.637;
- the same case with a position open;
- SELL on 11-03;
- Thursday 11-05 at 17:00 UTC (Friday on a UTC+7 clock, still counts);
- Friday 11-06 at 19:00 UTC (skipped);
- outside hours at 06:00 UTC on 11-10;
- a near-threshold case on 09-02;
- a weekend gap;
- a hand-built equal case.
Why must rounding be in the spec? At 00:00 UTC on 2025-08-07, Close was 3,371.905 and EMA21 3,371.90488. Unrounded, Close is about 0.0001 higher and the candle qualifies. Rounded to 3 decimals like the Data Window, they’re equal, so it fails a strict comparison. Code and agent must compare the same number.
ema and atr also need an independent reference: TA-Lib (a Python wrapper
around a C library) and pandas-ta-classic called with talib=False so it
computes itself. Three differences matter:
- EMA seed. Both libraries seed differently from the spec by default:
TA-Lib leaves the first n − 1 candles empty and starts from the mean of n
closes; pandas-ta-classic does the same unless
sma=False. MT5’s help only gives the recursive formula, not the starting value, hence the 1,500-candle warm-up and the Data Window comparison. Measured on an H1 CSV of 10,831 candles from 2025-01-01 (Windows 11, Python 3.14.3, TA-Lib 0.8.3.post1, pandas-ta-classic 0.9.0): TA-Lib’s EMA200 disagreed withemaon the first 988 candles (199 empty, 789 off by more than 0.0005 USD and shrinking). After candle 1,500 the gap was about 0.000003 USD. Compare only after the warm-up. - ATR smoothing. Compare ATR with
talib.SMA(talib.TRANGE(...), 14)or pandas-ta-classic’satr(..., mamode="sma", talib=False).talib.ATRand pandas-ta-classic’s default (mamode="rma") both use Wilder smoothing (RMA: new ATR = (13 × old ATR + new True Range) / 14), which differs from a 14-candle mean even after warm-up (median 0.96 USD on that CSV). - Standard deviation. MT5 builds Bollinger Bands with a standard deviation
divided by n (
ddof = 0); pandasstd()divides by n − 1 (ddof = 1) by default, so its bands are 2.6% wider over 20 candles.
The next post turns the EMA and ATR comparison into tests with a tolerance,
measures the ddof effect, and runs a cost-aware backtest of exactly this
spec.
cd C:\trading-agent-lab
notepad src\xau_01.py
notepad tests\test_xau_01.py
.venv\Scripts\python -m pytest -q tests\test_xau_01.py
.venv\Scripts\python src\xau_01.pysrc/xau_01.py:
# src/xau_01.py: the spec specs/xau-01-v1.md written as code. This is the answer key used to grade the agent.
# Reads a CSV only; no network, no orders. Build the cases: .venv\Scripts\python src\xau_01.py
import csv
import json
from datetime import datetime, timedelta
from pathlib import Path
SPEC = "xau-01-v1"
DECIMALS = 3 # XAUUSD: 3 decimals as in the Data Window; EURUSD uses 5
NEAR = 0.10 # USD: any comparison closer than this to its threshold gets the NEAR_THRESHOLD flag
MIN_CANDLES = 1500 # at least 1,500 H1 candles before [1] so EMA200 has settled
FROM_DAY, TO_DAY = "2026-11-02", "2026-11-11" # cases chosen by the (UTC) day of the entry candle
SERVER_OFFSET = 2 # a typical broker server clock (UTC+2), shown to the agent as a distraction only
FMT = "%Y-%m-%dT%H:%M:%SZ"
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
ORDER = {"UP": "BUY", "DOWN": "SELL"}
ROOT = Path(__file__).resolve().parent.parent
def ema(prices, n):
"""MT5-style EMA: starts at the first price, then each candle uses the factor 2/(n+1)."""
k, out = 2 / (n + 1), [prices[0]]
for x in prices[1:]:
out.append(x * k + out[-1] * (1 - k))
return out
def atr(candles, n=14):
"""ATR14 as the method defines it: the simple mean of the last n True Ranges."""
tr = [None] + [max(x["h"], p["c"]) - min(x["l"], p["c"]) for p, x in zip(candles, candles[1:])]
return [None if i < n else sum(tr[i - n + 1:i + 1]) / n for i in range(len(candles))]
def read_csv(path):
"""Read UTC H1 candles; round to exactly the digits the agent will see, so code and agent compare the same numbers."""
with open(path, encoding="utf-8-sig") as f:
c = [{"t": datetime.fromisoformat(r["time_utc"]), "o": float(r["open"]), "h": float(r["high"]),
"l": float(r["low"]), "c": float(r["close"])} for r in csv.DictReader(f)]
closes = [x["c"] for x in c]
for name, series, dec in (("ema21", ema(closes, 21), DECIMALS), ("ema55", ema(closes, 55), DECIMALS),
("ema200", ema(closes, 200), DECIMALS), ("atr14", atr(c), 5)):
for x, v in zip(c, series):
x[name] = None if v is None else round(v, dec)
for x in c:
x["c"] = round(x["c"], DECIMALS)
return c
def evaluate(c2, c1, entry_time, has_position):
"""Sections 5-7 of the spec. c2, c1: closed candles [2], [1]. entry_time: open time of the entry candle, UTC."""
if c1["ema21"] > c1["ema55"] > c1["ema200"]:
trend, pullback, reclaim = "UP", c2["c"] < c2["ema21"], c1["c"] > c1["ema21"]
elif c1["ema21"] < c1["ema55"] < c1["ema200"]:
trend, pullback, reclaim = "DOWN", c2["c"] > c2["ema21"], c1["c"] < c1["ema21"]
else:
trend, pullback, reclaim = "NONE", False, False
out = {"trend": trend, "pullback_2": pullback, "reclaim_1": reclaim,
"in_hours": 7 <= entry_time.hour < 21, # [07:00, 21:00) UTC
"not_friday": entry_time.weekday() != 4, # Friday by UTC
"no_position": not has_position}
ok = trend != "NONE" and all(out[k] for k in ("pullback_2", "reclaim_1", "in_hours", "not_friday", "no_position"))
out["action"] = ORDER[trend] if ok else "STAY_OUT"
return out
def flags(c2, c1, entry_time):
"""Flags for the human reviewer; a flag never changes the decision."""
f = []
gaps = (c1["ema21"] - c1["ema55"], c1["ema55"] - c1["ema200"], c2["c"] - c2["ema21"], c1["c"] - c1["ema21"])
if min(abs(x) for x in gaps) < NEAR:
f.append("NEAR_THRESHOLD")
if entry_time != c1["t"] + timedelta(hours=1):
f.append("GAP") # the entry candle doesn't follow [1]: daily break, weekend, missing candles
return f
def price_levels(action, bid, ask, atr14):
"""Entry, SL, TP computed by code, never by the agent: BUY at the Ask, SELL at the Bid."""
if action == "BUY":
return round(ask, DECIMALS), round(ask - 1.5 * atr14, DECIMALS), round(ask + 3 * atr14, DECIMALS)
if action == "SELL":
return round(bid, DECIMALS), round(bid + 1.5 * atr14, DECIMALS), round(bid - 3 * atr14, DECIMALS)
return None, None, None
def make_case(c, i, has_position=False):
"""The agent's input when candle [1] = c[i] has just closed, plus the code's answer."""
c2, c1, entry = c[i - 1], c[i], c[i + 1]
server = entry["t"] + timedelta(hours=SERVER_OFFSET)
given = {"spec": SPEC, "time_utc": entry["t"].strftime(FMT), "weekday_utc": DAYS[entry["t"].weekday()],
"server_time": server.strftime("%Y-%m-%d %H:%M ") + DAYS[server.weekday()],
"data_until": (c1["t"] + timedelta(hours=1)).strftime(FMT),
"candle_2": {"time_utc": c2["t"].strftime(FMT), "close": c2["c"], "ema21": c2["ema21"]},
"candle_1": {"time_utc": c1["t"].strftime(FMT), "close": c1["c"], "ema21": c1["ema21"],
"ema55": c1["ema55"], "ema200": c1["ema200"], "atr14": c1["atr14"]},
"has_position": has_position}
answer = {"time_utc": given["time_utc"], **evaluate(c2, c1, entry["t"], has_position),
"flags": flags(c2, c1, entry["t"])}
return given, answer
def save(name, given, answer):
for folder, content in (("input", given), ("answer", answer)):
p = ROOT / "cases" / SPEC / folder
p.mkdir(parents=True, exist_ok=True)
(p / f"{name}.json").write_text(json.dumps(content, indent=1), encoding="utf-8")
def main():
c = read_csv(ROOT / "data" / "xauusd_h1_utc.csv")
n, last_order = 0, None
for i in range(MIN_CANDLES, len(c) - 1):
if not FROM_DAY <= c[i + 1]["t"].strftime("%Y-%m-%d") < TO_DAY:
continue
given, answer = make_case(c, i)
signal = answer["pullback_2"] and answer["reclaim_1"] # all three candle conditions, hours not yet checked
if not (signal or c[i + 1]["t"].hour == 10): # plus one 10:00 UTC point each day
continue
save(c[i + 1]["t"].strftime("%Y-%m-%dT%H-%MZ"), given, answer)
n += 1
if answer["action"] != "STAY_OUT":
last_order = i
if last_order is None:
raise SystemExit("No case with an order: check the CSV has candles from 2026-07-01 to 2026-11-11.")
given, answer = make_case(c, last_order, has_position=True) # a copy assuming a position is open
save(c[last_order + 1]["t"].strftime("%Y-%m-%dT%H-%MZ") + "_open-position", given, answer)
print(n + 1, "cases written to cases/" + SPEC + " (input/ for the agent, answer/ for grading)")
if __name__ == "__main__":
main()tests/test_xau_01.py:
from datetime import datetime
from src.xau_01 import evaluate, flags, price_levels
# Numbers read from H1 BID candles, UTC. Your broker's prices differ by a few tens of cents.
def candle(t, close, e21, e55=None, e200=None):
return {"t": datetime.fromisoformat(t), "c": close, "ema21": e21, "ema55": e55, "ema200": e200}
C2_1109 = candle("2026-11-09T17:00:00Z", 4101.978, 4102.988)
C1_1109 = candle("2026-11-09T18:00:00Z", 4104.327, 4103.110, 4085.582, 4046.458)
ENTRY_1109 = datetime.fromisoformat("2026-11-09T19:00:00Z")
def test_1_buy_1109_and_price_levels():
r = evaluate(C2_1109, C1_1109, ENTRY_1109, has_position=False)
assert r["trend"] == "UP" and r["action"] == "BUY"
assert flags(C2_1109, C1_1109, ENTRY_1109) == []
# Ask = opening Bid 4104.277 + spread 0.407; ATR14 = 13.98436
assert price_levels("BUY", 4104.277, 4104.684, 13.98436) == (4104.684, 4083.707, 4146.637)
def test_2_open_position_means_stay_out():
r = evaluate(C2_1109, C1_1109, ENTRY_1109, has_position=True)
assert r["no_position"] is False and r["action"] == "STAY_OUT"
def test_3_sell_1103():
c2 = candle("2026-11-03T15:00:00Z", 3936.096, 3929.087)
c1 = candle("2026-11-03T16:00:00Z", 3927.576, 3928.950, 3939.939, 4001.156)
assert evaluate(c2, c1, datetime.fromisoformat("2026-11-03T17:00:00Z"), False)["action"] == "SELL"
assert price_levels("SELL", 3927.665, 3928.130, 17.63879) == (3927.665, 3954.123, 3874.749)
def test_4_thursday_utc_counts_even_when_a_utc_plus_7_clock_says_friday():
c2 = candle("2026-11-05T15:00:00Z", 4084.345, 4100.187)
c1 = candle("2026-11-05T16:00:00Z", 4127.205, 4102.643, 4051.191, 4021.363)
assert evaluate(c2, c1, datetime.fromisoformat("2026-11-05T17:00:00Z"), False)["action"] == "BUY"
def test_5_friday_utc_stays_out():
c2 = candle("2026-11-06T17:00:00Z", 4059.958, 4066.021)
c1 = candle("2026-11-06T18:00:00Z", 4077.355, 4067.051, 4060.232, 4031.761)
r = evaluate(c2, c1, datetime.fromisoformat("2026-11-06T19:00:00Z"), False)
assert r["not_friday"] is False and r["action"] == "STAY_OUT"
def test_6_outside_hours_0600_utc():
c2 = candle("2026-11-10T04:00:00Z", 4114.595, 4115.382)
c1 = candle("2026-11-10T05:00:00Z", 4123.385, 4116.109, 4097.818, 4054.065)
r = evaluate(c2, c1, datetime.fromisoformat("2026-11-10T06:00:00Z"), False)
assert r["in_hours"] is False and r["action"] == "STAY_OUT"
def test_7_near_threshold_still_follows_the_rule_but_is_flagged():
c2 = candle("2026-09-02T11:00:00Z", 4332.105, 4331.146)
c1 = candle("2026-09-02T12:00:00Z", 4331.135, 4331.145, 4383.491, 4472.008)
entry = datetime.fromisoformat("2026-09-02T13:00:00Z")
assert evaluate(c2, c1, entry, False)["action"] == "SELL"
assert flags(c2, c1, entry) == ["NEAR_THRESHOLD"]
def test_8_weekend_gap():
c2 = candle("2026-11-06T20:00:00Z", 4065.685, 4066.619)
c1 = candle("2026-11-06T21:00:00Z", 4069.545, 4066.885, 4060.855, 4032.779)
entry = datetime.fromisoformat("2026-11-08T23:00:00Z")
assert evaluate(c2, c1, entry, False)["action"] == "STAY_OUT"
assert flags(c2, c1, entry) == ["GAP"]
def test_9_equal_is_not_a_pass():
c1 = candle("2026-11-09T18:00:00Z", 4103.110, 4103.110, 4085.582, 4046.458)
r = evaluate(C2_1109, c1, ENTRY_1109, False)
assert r["reclaim_1"] is False and r["action"] == "STAY_OUT"pytest’s last line reads 9 passed.
On the real H1 BID data, src/xau_01.py prints
20 cases written to cases/xau-01-v1: 5 cases where code has an order (SELL
11-03 at 17:00 and 19:00 UTC, BUY 11-05 at 17:00, BUY 11-09 at 09:00 and
19:00) and 15 that stay out, 8 of which test the hour or Friday rule. Every
case assumes no open position except the copy of 11-09 19:00, the real
situation above. In practice the 19:00 SELL on 11-03 must also stay out,
because the 17:00 SELL that day was still open. Your broker’s data may shift
a case or two.
Then do section 3’s comparison: open cases\xau-01-v1\input\2026-11-09T19-00Z.json
and compare close, ema21, ema55, ema200, atr14 of candle_1 with the
Data Window on the 18:00 UTC candle of 11-09 (on your MT5 chart, 18:00 plus
HOUR_OFFSET). More than 0.01 off: stop and find out why.
Common errors: No module named pytest: .venv\Scripts\python -m pip install -U pytest.
No module named 'src': cd C:\trading-agent-lab and rerun; create an empty
src\__init__.py if missing. A test FAILED: compare your file with the one
above; never edit a test to pass.
Running the answer key over all the H1 BID data shows how much the time rule weighs. Counting closed [1] candles from 2024-04-01 to 2026-11-10:
| Count | Times | Note |
|---|---|---|
| Closed [1] candles evaluated | 15,494 | Every closed candle is one evaluation |
| All three candle conditions: trend, pullback on [2], reclaim on [1] | 663 | 396 up, 267 down |
| Entry candle within [07:00, 21:00) UTC | 434 | 229 removed by the hours |
| Not Friday UTC | 349 | 85 more removed; 215 BUY and 134 SELL, before the one-position rule |
Of those 349, flagged NEAR_THRESHOLD |
20 | A comparison within 0.10 USD of its threshold |
Nearly half the times all three candle conditions hold, the signal is dropped only for the hour or Friday, so an agent that misreads time is wrong on a lot of cases. These are signal counts by the spec, not profit or loss; the one-position rule removes more, and that number only exists in a simulation with orders and costs.
JSON output, running the agent, grading each field
The agent returns exactly one JSON object with 11 fields, as in the prompt at
the end: spec, time_utc; trend (UP, DOWN or NONE); five true/false
conditions pullback_2, reclaim_1, in_hours, not_friday,
no_position; action (BUY, SELL or STAY_OUT); flags and short_reason.
No price or lot fields. When a demo proposal is needed in the level-2 flow,
code builds the 10-field proposal from the code’s action and price_levels,
never from the agent’s reply.
To be clear: for a fully measurable method like XAU-01, code is enough to decide. The agent doesn’t decide better. Running it on the cases does two things: you learn how strictly it applies a rule before giving it harder work, and you get an explanation for the journal.
Grading each field shows where it goes wrong: a wrong not_friday usually
means it took the day from a local clock; a wrong trend means it misread an
EMA; a self-contradiction means it scored right and concluded wrong.
The two flags are only for the reader: NEAR_THRESHOLD when a comparison is
within 0.10 USD of its threshold, GAP when the entry candle doesn’t follow
[1]. The 0.10 USD comes from the 11-09 case itself: Close − EMA21 computed on
two different price sources differed by 0.045 USD on [1] and 0.073 USD on [2].
On a flagged case, open the Data Window on your broker before trusting either
side.
| Step | Who | What |
|---|---|---|
| 1 | Code | src/xau_01.py builds the agent’s input and the answer from the same candle |
| 2 | Agent | src/run_cases.py calls claude -p, pinned model, --tools ""; returns the 11-field JSON |
| 3 | Code | src/grade_spec.py prints four totals and reports/grade-xau-01-v1.csv |
| 4 | You | Read the worst error first: an order where code stays out |
| 5 | You | Open each differing case; code wins; a prompt fix is saved as v2 and tested on cases not used for the fix |
- Run
src/run_cases.py. It sends each case throughclaude -pwith the pinnedclaude-sonnet-5-5, every tool off and auto memory off.--tools ""turns off all built-in tools and--disallowedTools "mcp__*"drops MCP tools, so the agent can’t read any file, the answer files included. Besides the prompt and one case it only sees what Claude Code loads by itself, such as the project’sCLAUDE.md. Run it only in your own folder: a-prun still runs hooks and connects MCP servers declared in the project. Twenty calls count against your plan’s allowance (see/usage). - Run
src/grade_spec.py. It compares each reply with the answer and prints four totals. Read “Agent ordered where code stays out” first: an extra order does direct harm, worse than a missed one. - Read the results by the spec: if agent and code differ, code wins; then open that case.
- If you fix the prompt, save it as
prompts/xau-01-v2.md, changespecin the code and prompt, and test on cases not used for the fix. For example, changeTOinsrc/export_h1.pyto export another week, then moveFROM_DAYandTO_DAYto that week. That’s how out-of-sample data stays out of sample.
prompts/xau-01-v1.md is the prompt at the end of this post; keep the
[DATA] slot, which run_cases.py fills per case.
cd C:\trading-agent-lab
notepad prompts\xau-01-v1.md
notepad src\run_cases.py
notepad src\grade_spec.pysrc/run_cases.py:
# src/run_cases.py: send each case to the agent and save the raw reply. The agent has no tools and places no order.
# Run: .venv\Scripts\python src\run_cases.py xau-01-v1
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
MODEL = "claude-sonnet-5-5" # full pinned name
CLAUDE = shutil.which("claude")
ENV = {**os.environ, "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1"} # auto memory off
def main():
spec = sys.argv[1] if len(sys.argv) > 1 else "xau-01-v1"
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.")
template = (ROOT / "prompts" / f"{spec}.md").read_text(encoding="utf-8-sig")
out_dir = ROOT / "cases" / spec / "reply"
out_dir.mkdir(exist_ok=True)
for given in sorted((ROOT / "cases" / spec / "input").glob("*.json")):
out = out_dir / given.name
if out.exists():
continue # already answered: rerunning is safe
text = template.replace("[DATA]", given.read_text(encoding="utf-8"))
try: # --tools "": no tools, the agent can't read files or go online
r = subprocess.run([CLAUDE, "-p", "Follow the instructions in the attached content exactly. Return only one JSON object.",
"--model", MODEL, "--output-format", "json", "--tools", "",
"--disallowedTools", "mcp__*"],
input=text, capture_output=True, text=True, encoding="utf-8",
timeout=600, cwd=ROOT, env=ENV)
except subprocess.TimeoutExpired:
sys.exit(f"No answer after 600 seconds on case {given.stem}: check the network, then rerun.")
try:
raw = json.loads(r.stdout)
except json.JSONDecodeError:
raw = {}
if r.returncode != 0 or raw.get("is_error") or "result" not in raw:
print("Technical error on case", given.stem, "- stopping, no retry loop:")
print(str(raw.get("result") or r.stderr or r.stdout)[:400])
sys.exit(1)
out.write_text(json.dumps({"result": raw["result"], "model": list(raw.get("modelUsage") or {}),
"est_cost_usd": raw.get("total_cost_usd")}), encoding="utf-8")
print(given.stem, "-> saved")
print("Done. Grade with: .venv\\Scripts\\python src\\grade_spec.py", spec)
if __name__ == "__main__":
main()src/grade_spec.py:
# src/grade_spec.py: grade the agent's replies against the code's answers, field by field.
# Run: .venv\Scripts\python src\grade_spec.py xau-01-v1
import csv
import json
import sys
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CONDITIONS = ["pullback_2", "reclaim_1", "in_hours", "not_friday", "no_position"] # spec sections 5-6
ORDER = {"UP": "BUY", "DOWN": "SELL"}
def read_reply(p):
"""Take the result of claude -p. Never fix it for the agent: text or ``` outside the JSON is a format error."""
try:
return json.loads(json.loads(p.read_text(encoding="utf-8"))["result"].strip()), []
except (json.JSONDecodeError, KeyError, TypeError, AttributeError):
return None, ["not a plain JSON object"]
def check_format(reply, answer, spec):
if not isinstance(reply, dict):
return ["not a JSON object"]
errors, need = [], set(answer) | {"spec", "short_reason"}
if set(reply) != need:
errors.append(f"missing {sorted(need - set(reply))} extra {sorted(set(reply) - need)}")
errors += [f"{k} wrong type" for k, v in answer.items() if k in reply and type(reply[k]) is not type(v)]
if reply.get("spec") != spec:
errors.append("wrong spec version")
if not isinstance(reply.get("short_reason"), str) or len(reply["short_reason"]) > 200:
errors.append("short_reason must be text, at most 200 characters")
return errors
def self_contradiction(reply):
"""The agent scores the conditions one way and acts another. Case-insensitive."""
trend = str(reply.get("trend")).upper()
ok = trend in ORDER and all(reply.get(k) is True for k in CONDITIONS)
return str(reply.get("action")).upper() != (ORDER[trend] if ok else "STAY_OUT")
def main():
spec = sys.argv[1] if len(sys.argv) > 1 else "xau-01-v1"
folder = ROOT / "cases" / spec
table, diffs, n_format, n_contra = [], Counter(), 0, 0
for p in sorted((folder / "reply").glob("*.json")):
answer = json.loads((folder / "answer" / p.name).read_text(encoding="utf-8"))
reply, errors = read_reply(p)
errors = errors or check_format(reply, answer, spec)
if errors:
n_format += 1
table.append({"case": p.stem, "answer": answer["action"], "agent": "", "format_error": "; ".join(errors)})
print(p.stem, "| FORMAT ERROR:", "; ".join(errors))
continue
wrong = [k for k in answer if k != "flags" and str(reply[k]).upper() != str(answer[k]).upper()]
diffs.update(wrong)
contra = self_contradiction(reply)
n_contra += contra
flag_diff = sorted(set(reply["flags"]) ^ set(answer["flags"]))
table.append({"case": p.stem, "answer": answer["action"], "agent": reply["action"].upper(),
"fields_wrong": " ".join(wrong), "self_contradiction": contra, "flags_differ": " ".join(flag_diff),
"short_reason": reply["short_reason"]})
note = (" | self-contradiction" if contra else "") + (" | flags differ: " + " ".join(flag_diff) if flag_diff else "")
print(f"{p.stem} | agent {reply['action']}, answer {answer['action']} | wrong: {' '.join(wrong) or 'none'}{note}")
if not table:
raise SystemExit(f"No replies in cases/{spec}/reply yet: run src/run_cases.py first.")
orders = [b for b in table if b["answer"] != "STAY_OUT"]
extra = [b for b in table if b["answer"] == "STAY_OUT" and b["agent"] in ("BUY", "SELL")]
print(f"\n{len(table)} cases | format errors {n_format} | self-contradictions {n_contra}")
print(f"Cases where code has an order: {len(orders)}, agent gave the right order in {sum(b['agent'] == b['answer'] for b in orders)}")
print(f"Agent ordered where code stays out: {len(extra)} {[b['case'] for b in extra]}")
print("Wrong by field:", dict(diffs) or "none")
(ROOT / "reports").mkdir(exist_ok=True)
with open(ROOT / "reports" / f"grade-{spec}.csv", "w", newline="", encoding="utf-8-sig") as f:
w = csv.DictWriter(f, fieldnames=["case", "answer", "agent", "fields_wrong", "self_contradiction",
"flags_differ", "format_error", "short_reason"])
w.writeheader()
w.writerows(table)
print(f"Details: reports/grade-{spec}.csv. Simulation on historical data, not investment advice.")
if __name__ == "__main__":
main()The first line must print False; if it prints True, remove the variable
before going on:
Test-Path Env:ANTHROPIC_API_KEY
.venv\Scripts\python src\run_cases.py xau-01-v1
.venv\Scripts\python src\grade_spec.py xau-01-v1run_cases.py prints one -> saved line per case; each call takes a while,
so don’t close the window. Rerunning skips cases already answered.
grade_spec.py prints one line per case, four totals and the path of the CSV.
Here is what the grader printed in a test run where a stand-in for claude
answered synthetic candles, after two replies were deliberately broken (one
wrapped in backticks, one turned into a SELL on a Friday it scored as “not
Friday”):
2026-11-02T10-00Z | agent STAY_OUT, answer STAY_OUT | wrong: none
2026-11-02T17-00Z | agent SELL, answer SELL | wrong: none
2026-11-02T22-00Z | agent STAY_OUT, answer STAY_OUT | wrong: none
2026-11-03T09-00Z | agent SELL, answer SELL | wrong: none
2026-11-03T10-00Z | agent STAY_OUT, answer STAY_OUT | wrong: none
2026-11-03T13-00Z | agent SELL, answer SELL | wrong: none
2026-11-03T20-00Z | agent SELL, answer SELL | wrong: none
2026-11-03T20-00Z_open-position | agent STAY_OUT, answer STAY_OUT | wrong: none
2026-11-04T04-00Z | agent STAY_OUT, answer STAY_OUT | wrong: none
2026-11-04T10-00Z | agent STAY_OUT, answer STAY_OUT | wrong: none
2026-11-05T10-00Z | agent STAY_OUT, answer STAY_OUT | wrong: none
2026-11-06T10-00Z | agent SELL, answer STAY_OUT | wrong: trend not_friday action | self-contradiction
2026-11-09T10-00Z | agent STAY_OUT, answer STAY_OUT | wrong: none
2026-11-10T10-00Z | FORMAT ERROR: not a plain JSON object
14 cases | format errors 1 | self-contradictions 1
Cases where code has an order: 4, agent gave the right order in 4
Agent ordered where code stays out: 1 ['2026-11-06T10-00Z']
Wrong by field: {'trend': 1, 'not_friday': 1, 'action': 1}
Details: reports/grade-xau-01-v1.csv. Simulation on historical data, not investment advice.| Total | Meaning | What to do |
|---|---|---|
| format errors | Not plain JSON, missing or extra fields, wrong types | Don’t fix it for the agent; count it in the conclusion |
| self-contradictions | The conditions it scored don’t lead to its action | Read short_reason in the CSV; the case is unusable |
| right order in … | Of the cases where code has an order, how many it matched | For misses, look at the wrong fields |
| ordered where code stays out | BUY or SELL where the rule says stay out | The worst error: open each case, fix in v2 |
| 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, fix PATH |
ANTHROPIC_API_KEY is set |
The variable lives in this window; claude -p would bill the API |
Remove it, open a new window, check with Test-Path |
Technical error on case … mentioning login or limits |
Not logged in, or the plan’s allowance is used up | Run claude once to log in, or wait for the allowance; rerun the same command |
FORMAT ERROR: not a plain JSON object on many cases |
The agent adds text or backticks around the JSON | Don’t edit replies or the prompt mid-batch; note it, fix in v2 |
Price Action: what the machine measures, what you label, what you decide
For a more subjective method, split the work three ways. Take “D1 pin bar at a key level, filtered by market state”. It has six conditions. A pin bar is a candle with one long wick rejecting price.
For each condition ask three questions: is there a number yet, on which candle is it measured, who answers it. Three parts have no number: “a clear trend or range”, “key level”, and “the five self-check questions”.
The spec doesn’t invent numbers for them. It turns them into labels you write in advance, with the time written, and code only uses labels written before 00:00 UTC on the signal day. The method itself says a level identified only after the pin appears is void; the timestamp turns that sentence into a check.
| Who | Does |
|---|---|
| Code | Measures pin bar geometry on closed D1 candles; computes EMA8, EMA21, slope, swing highs and lows; lists level candidates with at least 2 turns; computes R and the distance to the opposite level |
| You | Label the market state before the signal day; choose levels and write them to data/key-levels.csv with written_utc; answer the five self-check questions; decide |
| Agent | Describes the context only from numbers code gives; checks for labels missing or written too late; challenges your labels with numbers; action is only AWAIT_HUMAN or STAY_OUT |
Geometry is what the machine does well. is_pin below, run on XAUUSD D1
candles by UTC day from 2024-06-02 to 2026-11-10 (763 candles), found 78
candles with pin bar geometry: 46 lower wicks, 32 upper wicks, fewer than 3 a
month. 18 of them were short Sunday candles that only exist when the day is
split by UTC; the median range of a Sunday candle is about 17 USD against 57
USD on weekdays. A quantified variant that replaces the key level with an
EMA21 condition leaves 14 candles; its backtest tests a different method, not
the full subjective reading.
How you split the day changes even the geometry. The 2026-11-05 candle is an upper-wick pin if the day is UTC, but fails if the day starts at 22:00 UTC (a UTC+2 server):
| Day starts at | Open, High, Low, Close | Upper wick / range | Machine says |
|---|---|---|---|
| 00:00 UTC | 4,065.335, 4,146.785, 4,061.045, 4,087.470 | 59.315 / 85.740 = 69.2% | Upper-wick pin |
| 22:00 UTC (server UTC+2) | 4,063.155, 4,146.785, 4,057.497, 4,087.305 | 59.480 / 89.288 = 66.6% | Fails, about 0.05 points short of 2/3 |
| 21:00 UTC (server UTC+3) | 4,063.725, 4,146.785, 4,057.497, 4,098.765 | 48.020 / 89.288 = 53.8% | Fails |
That candle also fails the quantified variant: an upper-wick pin there needs a close below EMA21, and the close 4,087.470 is above EMA21 4,048.042. So section 1 of the spec must say which clock defines the day, and the MT5 chart you look at must split days the same way as the data code uses.
The agent here doesn’t choose levels, doesn’t label, and never says BUY or SELL. It does three things: describe the context only from numbers code gives, without predicting; flag labels that are missing or written after the cutoff; and challenge your labels with numbers, for example you wrote RANGE while EMA8 sat below EMA21 for 15 sessions.
Your part needs testing too:
- Label the market state on 20 past days picked by a calendar rule, then put it away.
- A week later, label them again without looking at the first set.
- Compare the two against a threshold set in advance, say at least 16 of 20 matching. Below it, the label definitions aren’t clear enough to grade an agent or to backtest.
| Method condition | The machine can | You must |
|---|---|---|
| 1. Classify state by highs, lows and the slope of EMA 8/21 D1; trade only a clear trend or range | Compute EMA8, EMA21, slope, confirmed swing highs and lows, range width in ATR; give the numbers | Label TREND_UP, TREND_DOWN, RANGE or CHOP before the signal day; “clear” is a judgement |
| 2. A key level confirmed before the signal day (price turned at least once, ideally twice) | List candidates: swing highs and lows with at least 2 turns in a window you choose | Choose the level, write it to data/key-levels.csv with written_utc and a reason |
| 3. Closed pin bar: wick at least 2/3 of the candle, tip touching or piercing the level, body closing inside | Measure geometry on closed D1; once a level exists, check the touch and the close side | Choose the day split, whether Sunday candles count, the tolerance for “touch” |
| 4. At least 2R to the opposite level | Compute R (entry to SL) and the distance to the opposite level | Choose the opposite level |
| 5. No FOMC, CPI or NFP within 24 hours unless the plan allows holding through news | Check against a news calendar with UTC times and a source you supply (FOMC: US rate meeting; CPI: consumer prices; NFP: non-farm payrolls) | Update the calendar, confirm the source; never let the agent recall dates |
| 6. Answer the five self-check questions; no trading after two losses in a row that day | Count losses from the journal; show the five questions | Answer them and decide |
The machine’s part, for closed D1 candles (c has keys o, h, l, c):
def is_pin(c):
"""Pin bar geometry on a closed D1 candle: wick at least 2/3 of the range, body at most 1/3."""
rng = c["h"] - c["l"]
if rng <= 0:
return "NONE"
body = abs(c["c"] - c["o"])
if body <= rng / 3 and min(c["o"], c["c"]) - c["l"] >= 2 * rng / 3:
return "LOWER_WICK" # long lower wick: buy candidate
if body <= rng / 3 and c["h"] - max(c["o"], c["c"]) >= 2 * rng / 3:
return "UPPER_WICK" # long upper wick: sell candidate
return "NONE"A short spec, saved as specs/pa-pin-d1-v1.md with the brackets filled in:
# Spec pa-pin-d1-v1 | D1 pin bar at a key level (Price Action) | written on [DATE]
1. Identity: XAUUSD | D1 | BID | the day is defined by [UTC or server time, say which] | short Sunday candles: not considered
2. Inputs from code: the just-closed D1 candle (open, high, low, close), ema8, ema21, atr14; a news calendar with UTC times and a source
3. Inputs from you, each row with written_utc; only rows written before 00:00 UTC on the signal day count:
data/key-levels.csv (level, kind, written_utc, reason)
data/market-state.csv (day_utc, label, written_utc): TREND_UP, TREND_DOWN, RANGE, CHOP
4. Measured by machine: is_pin; wick tip pierces the level or is within [0.1] x atr14 of it (your tolerance);
close inside the level; at least 2R to the opposite level; no major news in the next 24 hours
5. Decided by you: label other than CHOP, a valid level, the five self-check questions, stop after two losses in a day
6. Agent: description, missing_labels, challenge; action only AWAIT_HUMAN or STAY_OUT; never chooses a level or labels
7. Tests: test is_pin on real candles; check the consistency of your own labels;
never call the quantified variant's results this method's resultsdata/key-levels.csv, one level per row. Never fill in made-up levels; write
the levels you actually draw, when you draw them:
level,kind,written_utc,reason
[LEVEL],RESISTANCE,[TIME WRITTEN, e.g. 2026-11-04T23:30:00Z],"[THE TIMES PRICE TURNED AT THIS LEVEL]"| Field the agent returns (pa-pin-d1-v1) | Value | Checked by |
|---|---|---|
spec, day_utc |
"pa-pin-d1-v1", the D1 candle’s day |
Code |
description |
At most 300 characters, only numbers from the data, no prediction | You: is any number not in the data? |
missing_labels |
Array of labels missing or written after 00:00 UTC on the signal day | Code, against the label files |
challenge |
At most 300 characters: which numbers contradict your labels; "" if none |
You read it and decide |
action |
AWAIT_HUMAN or STAY_OUT, never BUY or SELL |
Code |
The same frame across 13 gold methods
Apply the 11-section frame to thirteen gold methods and every one of them states its decision conditions in numbers, even the ones that look subjective like range sweeps, FVGs (fair value gaps: the price gap between candles A and C of a three-candle cluster) or structure breaks. Where they were still ambiguous, an interpretation was chosen; the middle column records it. So the decision part is fully machine-checkable.
The hard parts move to four places:
- Time: UTC, New York time that shifts with the seasons, which clock defines the day.
- Data source: D1 by UTC day or by server day, the source’s spread.
- Order state across candles: pending orders, cancellation, one position, holding for days.
- Broker specs in the MT5 Specification: stops level (minimum distance from price to SL, TP or a pending order), point (smallest price step), contract size (ounces per lot).
The division of labour stays the same in all thirteen: code computes the numbers and holds the answer and the state; the agent scores conditions from the numbers given, explains and flags; a human approves on demo. The more state a method carries (XAU-12, XAU-13), the more code should do, with the agent only explaining cases code reports.
For New York time (XAU-08, XAU-09) never add or subtract hours yourself; use
the America/New_York zone from Python’s zoneinfo. Windows has no built-in
IANA time-zone database, so install the tzdata package:
.venv\Scripts\python -m pip install tzdata.
| Method | Machine checks from numbers | The spec must state (interpretation chosen) | Human part |
|---|---|---|---|
| XAU-01 three-layer EMA21 pullback (H1) | Three EMAs on [1]; close vs EMA21 on [2] and [1] | Hours [07:00, 21:00) and Friday by the entry candle, UTC; strict comparisons | Server time offset; one-position state; near-threshold cases |
| XAU-02 MACD cross with EMA200 (H4) | Main vs Signal on [2] and [1]; close and EMA50 vs EMA200 | MT5’s Signal is a 9-candle SMA of Main; H4 candles on UTC, so orders only open at 08:00, 12:00, 16:00 UTC | Check the broker’s H4 boundaries against UTC |
| XAU-03 Bollinger wick reversion (H1) | Wick touches the band, close back inside, RSI14 below 35 or above 65 | Standard deviation divided by n (ddof = 0) as in MT5, not pandas’ default ddof = 1; TP is the middle band at entry; if the middle band isn’t on the profit side, TP 5.00; the SL-move trigger measured at the exit price |
Decide in advance whether SL moves |
| XAU-04 Daily pivot + Stochastic (M15) | Pivots from the closed D1; %K crosses %D; at most 1.50 from S or R | UTC D1 includes a short Sunday candle, so Monday’s pivots are narrow; distance measured with Bid for BUY, Ask for SELL | Choose the D1 source; exit rule when the lot can’t be split |
| XAU-05 Asian box breakout with pending orders (M15) | Box 00:00–07:00 UTC with all 28 candles, at least 1.50 wide; Buy Stop and Sell Stop levels | Cancel the remaining order at 12:00 UTC; combined risk if both sides fill | Approve pending orders; confirm the other side is cancelled |
| XAU-06 London box close breakout (M15) | 7-candle box 09:15–10:45 UTC; close beyond the edge ± 0.05 | SL and TP distances need the broker’s stops level, spread and point; close anything still open at 17:00 UTC | Read the Specification before each session |
| XAU-07 Candle-colour stop (M15) | Colour of [1]; stop at its high or low; SL and TP 0.20 away | No hour window given; a 0.20 target is smaller than one M5 candle’s range, so it’s often unknown whether SL or TP hit first | Check costs; skip when the spread is wide |
| XAU-08 New York open range sweep + FVG (M5) | Box 09:30–10:00 New York time; the sweep; FVG at least 0.06 wide; limit order | New York time via America/New_York; a candle beyond both edges voids the day; one case per day |
Check time-change dates and US-open news |
| XAU-09 Asian range sweep in London + FVG (M5) | Box 20:00–02:00 New York time; window 02:00–05:00; FVG | The box needs all 72 M5 candles; SL at the London extreme seen when candle C closes | As XAU-08 |
| XAU-10 EMA9 pullback with the daily trend (M15 + D1) | D1 vs EMA50; EMA9 vs EMA21; wick touches EMA9; candle colour | Spread cap 0.40 measured at the entry quote; no Friday rule in this one | Measure the real spread; the source’s median spread was about 0.58 in 2025 and 0.66 in 2026 |
| XAU-11 Stochastic with the daily trend (M15 + D1) | %K and %D on [2], [1] with thresholds 20/30 and 80/70 | As XAU-10; if K[1] has already left the zone, skip | As XAU-10 |
| XAU-12 Donchian 55/20 (D1) | Close breaks the high or low of the previous 55 candles; exit when close breaks the 20-candle channel | State flat, BUY, SELL across days; UTC D1 has Sunday candles, so 55 candles are fewer than 55 full trading days; swap not counted | Track multi-day positions, swap, breaks |
| XAU-13 Structure break + Fibonacci + FVG (M15 + D1) | Swings with 3 candles each side, strict; break by close; leg at least 1 ATR; zone 61.8–78.6%; FVG within 8 candles | Cancel after 12 candles or on an opposite break; exit after 96 candles; each event considered once | Let code do all of it; the agent only explains cases code reports |
When you write your own spec, copy the middle column into section 9, or say
you chose differently. For another method: copy src/xau_01.py to a new file
and rewrite evaluate, make_case and the tests; reuse src/run_cases.py
unchanged; in src/grade_spec.py change only CONDITIONS and
self_contradiction to match the new method’s action rule. XAU-10 is a good
next exercise.
Try it: the xau-01-v1 prompt
Save it as prompts/xau-01-v1.md. run_cases.py replaces [DATA] with each
case:
<role>
You apply spec xau-01-v1 (XAU-01 three-layer EMA21 pullback, XAUUSD, H1) exactly to the data given. You don't predict prices, don't use knowledge of prices at other times, and don't compute entry, SL, TP or lot. You place no order; your answer is only logged for code to grade and a human to read.
</role>
<spec>
1. Every number was computed by code from closed H1 candles, BID prices, UTC times. Use exactly those numbers; don't recompute them.
2. trend: UP when ema21 > ema55 > ema200 on candle_1; DOWN when ema21 < ema55 < ema200 on candle_1; anything else is NONE.
3. pullback_2: for UP, close < ema21 on candle_2; for DOWN, close > ema21 on candle_2; for NONE, false.
4. reclaim_1: for UP, close > ema21 on candle_1; for DOWN, close < ema21 on candle_1; for NONE, false.
5. Every comparison is strict: equal numbers don't pass.
6. in_hours: the hour of time_utc is from 07:00 up to but not including 21:00.
7. not_friday: weekday_utc is not Friday. Day and hour come from UTC only; server_time is for humans only.
8. no_position: has_position is false.
9. action: BUY when trend is UP and the five fields pullback_2, reclaim_1, in_hours, not_friday, no_position are all true; SELL when trend is DOWN and those five are all true; otherwise STAY_OUT.
10. flags: add "NEAR_THRESHOLD" if any of the four gaps |ema21 - ema55| and |ema55 - ema200| on candle_1, |close - ema21| on candle_2, |close - ema21| on candle_1 is below 0.10; add "GAP" if time_utc differs from data_until. No flags: [].
11. A missing field or an invalid number means action STAY_OUT, with the reason in short_reason.
</spec>
<data>
[DATA]
</data>
<self_check>
Before answering, check silently, writing nothing outside the JSON: (1) reread the three EMAs of candle_1 before choosing trend; (2) compare close with ema21 of the right candle; (3) take the weekday and hour from weekday_utc and time_utc, never from server_time; (4) action must match the fields you just scored.
</self_check>
<output>
ONLY one JSON object, no text outside it, not wrapped in ```. Exactly 11 fields:
- spec: "xau-01-v1"
- time_utc: copied from data
- trend: "UP" or "DOWN" or "NONE"
- pullback_2, reclaim_1, in_hours, not_friday, no_position: true or false (booleans, no quotes)
- action: "BUY" or "SELL" or "STAY_OUT"
- flags: an array containing only "NEAR_THRESHOLD", "GAP"
- short_reason: a string of at most 200 characters naming the numbers compared
</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:
- Read the method and underline every word without a number, a candle or an hour.
- Write the 11-section spec with your chosen interpretations; commit before any code.
- Write the answer key and tests from real candles, including the method’s own worked example; no agent until the tests pass.
- Code prepares the input from closed candles, position state included; the agent has no tools and fetches nothing.
- The agent returns JSON scoring each condition; code grades each field and counts format errors, self-contradictions and extra orders.
- Subjective parts become time-stamped labels you write in advance; the agent only describes, flags gaps and challenges with numbers.
- Decisions follow code and your approval, on demo only; lot computed by code and rounded down to 0.01.
- A changed spec or prompt is a new version: rerun the tests and a fresh set of cases.
Key takeaways
- Code computes every number and holds the answer; the agent only scores conditions; code grades the agent field by field; decisions follow code and your approval.
- An agent ordering where code stays out is the worst error: keep code’s decision, fix the prompt as a new version, and test it on fresh cases.
- For Price Action, split what the machine measures, what you label in advance and what you decide; the agent never replaces your judgement.
Comments