Do not take the venue on trust — check a fill against the ticks, a stop against the bid, the money against the arithmetic and a run against its repeat, in twenty lines; then run the sixteen-check battery from a program or a terminal.
An agent learns whatever its environment rewards. If the environment fills an order at a price that was never available, or lets a stop pass unseen, the agent learns that — and nothing it learned will hold on a live market. So before a long training run, check the engine on your own data, with your own eyes. Everything needed is readable from a program.
01Four checks in twenty lines
The program opens one position with a stop on a fresh practice workbench, lets the recording run until the stop is met, and then checks what the venue booked against the raw ticks.
import hashlib
import json
import tempfile
from bentrix import _native
from bentrix.local import Local
symbol = "XAUUSD"
def session():
"""A fresh practice workbench, a scripted hour of trading, and what the venue booked."""
workspace, store = _native.make_tape(tempfile.mkdtemp(prefix="bentrix-practice-"))
engine = Local(workspace=workspace, store=store)
bench = engine.call("get_state")["laboratories"][0]["benches"][0]["uri"]
engine.arm(bench)
home, owner, _, name = bench.removeprefix("bentrix://").split("/")
where = dict(home=home, owner=owner, bench=name)
engine.next_close(bench, "H1", [symbol])
sent_at = engine.state(bench)["cursor_ms"]
quote = engine.read("data_quotes", **where)["items"][0]
stop = round(quote["bid"] - 3.0, 2)
engine.call("order_market", bench=bench, symbol=symbol, side="buy", volume=0.10, sl=stop)
engine.run_until(bench, "H1", 20, [symbol])
deals = engine.read("trade_deals", **where)["items"]
ticks = engine.read("data_ticks", **where, symbol=symbol, day="2024-03-04")
engine.close()
return sent_at, stop, deals, ticks
sent_at, stop, deals, ticks = session()
columns = ticks["columns"]
rows = [dict(zip(columns, row)) for row in ticks["rows"]]
entry, exit_ = deals[0], deals[-1]
# 1. The buy filled on the first tick after the one it was sent on - never on a price already gone.
first_after = next(t for t in rows if t["time_ms"] > sent_at)
print("sent at", sent_at, "| filled at", entry["time_ms"], "| the first tick after the order:", first_after["time_ms"])
assert entry["time_ms"] == first_after["time_ms"]
# 2. A long's stop is met by the bid: the exit is at the first tick whose bid is at or under the stop,
# at that tick's bid - which may be worse than the stop, never better.
through = next(t for t in rows if t["time_ms"] > entry["time_ms"] and t["bid"] <= stop)
print("stop", stop, "| the first bid at or under it:", round(through["bid"], 3), "at", through["time_ms"])
print("the exit deal:", round(exit_["price"], 3), "at", exit_["time_ms"])
assert through["time_ms"] == exit_["time_ms"] and abs(through["bid"] - exit_["price"]) < 1e-9
# 3. The money adds up: profit = (exit - entry) x lots x contract size.
by_hand = (exit_["price"] - entry["price"]) * 0.10 * 100
print("profit by hand:", round(by_hand, 2), "| the venue's:", exit_["profit"])
assert abs(by_hand - exit_["profit"]) < 0.01
# 4. The same script again, on a fresh workbench: the same deals, to the last digit.
digest = lambda ds: hashlib.sha256(json.dumps(ds, sort_keys=True).encode()).hexdigest()[:16]
_, _, again, _ = session()
print("run 1:", digest(deals), "| run 2:", digest(again), "| equal:", digest(deals) == digest(again))
sent at 1709514000000 | filled at 1709514015000 | the first tick after the order: 1709514015000
stop 2099.27 | the first bid at or under it: 2099.266 at 1709546190000
the exit deal: 2099.266 at 1709546190000
profit by hand: -32.52 | the venue's: -32.52
run 1: 3101fd3465143baf | run 2: 3101fd3465143baf | equal: True
What each check shows:
- A market order fills on the first tick after the one it was sent on. It was sent at the hourly close and filled fifteen seconds later, at the next tick. No order is ever filled at a price the program had already seen.
- A long's stop is met by the bid, at the first tick at or through it, at that tick's bid. The stop was 2099.27; the first bid at or under it was 2099.266, and that is the exit's price. A stop can fill worse than its level, never better — as at a broker.
- The money is the arithmetic. The exit price less the entry price, times the lots, times the contract size, is the profit the venue booked.
- The same orders give the same deals. A second run on a fresh workbench produces the same deal list to the last digit; the two fingerprints are equal.
The four assert lines make it a test: put it in your own test suite and it fails loudly the day any of them stops being true.
02What to read, and where
| To check | Read |
|---|---|
| The raw ticks of a day, up to the clock | the data_ticks resource: time_ms, bid, ask, last, volume, flags |
| The newest bid and ask of each market | the data_quotes resource |
| Every fill | the trade_deals resource: time_ms, price, volume, entry (in/out), position, commission, swap, profit |
| What an order would cost, before sending it | order_preview: fill price, margin, commissions, spread cost, nightly swap, the triple-swap day |
| A market's contract | symbol_info: contract size, point, volume limits and step, swap |
| The account | the trade_account resource: balance, equity, margin, free margin, margin level, stop-out level |
| The same lists as files | export_deals and export_ticks write CSV files into Bentrix's export folder and answer their paths |
03The sixteen-check battery
Bentrix carries a larger set of checks and runs it on any recording: the verification battery. It makes workbenches alike yours, runs a reference strategy and scripted orders on them, and answers a verdict per check. From a program:
import tempfile
from bentrix import _native
from bentrix.local import Local
workspace, store = _native.make_tape(tempfile.mkdtemp(prefix="bentrix-practice-"))
with Local(workspace=workspace, store=store) as engine:
bench = engine.call("get_state")["laboratories"][0]["benches"][0]["uri"]
engine.call("battery_run", bench=bench)
while True:
result = engine.call("battery_get")
if result.get("checks") is not None:
break
engine.settle(50) # let the battery's workbenches run
for check in result["checks"]:
print(f"{check['id']:>2} {check['verdict']:<8} {check['name']}: {check['said']}")
1 pass reference parity: 9 entries, each at the candle after the reference's cross
2 pass cost audit: 8 closed positions, each one entry and one exit, a commission on each side once, no swap within a day
3 pass buy and hold: profit -12.39; price move × lots × money per unit -12.39; filled at the ask, closed at the bid
4 pass long/short mirror: the buy's and the sell's profits add to -0.36; the two spreads paid are -0.36
5 pass determinism: 17 acts on each, the same
6 pass trigger fills: 2 fills: the stop at the first ask through it, the limit at its price or better
7 pass future perturbation: 0 trades closed before the half's last day, the same over the half as over the whole
8 pass timeframe alignment: 118 hours, 0 opening off the hour
9 measured tick versus bar: 8 trades netting -66.30 on the bench's ticks; 8 netting -66.30 on one-minute OHLC
10 measured spread sensitivity: -66.30 on the recorded spread, -68.23 on twice it
11 measured random entry: the run's percentile among random entries: 0.005
12 measured Monte Carlo: reshuffled drawdown, skipped trades and degraded fills, each from one fixed seed
13 measured multiple testing: over 5 trials in the ledger: probabilistic Sharpe 0.000, after the Harvey–Liu haircut —
14 pass second-engine hash: the trade list's sha256 81f2b06f0d89ac039cbe77b0a81a69af32ef88af1bb7a0aa3035ce0e4997f003; another engine's list of the same run is compared to it with run_parity
15 not_run live/paper reconciliation: no account's fills are measured this session: a REAL account's *Measure my fills…* measures them
16 pass silent stop: the run acted on 118 closed candles; the days hold 118
Each verdict is pass, fail, measured (a figure with no threshold of its own) or not_run with its reason. On the practice tape ten pass, five are measured and one — the comparison with a real account's fills — is not run, since no account is connected.
Several of them answer questions an agent builder asks most:
- Determinism (5): a run and its repeat book the same acts.
- Trigger fills (6): a stop at the first price through it, a limit at its price or better.
- Future perturbation (7): a run over the first half of the days trades exactly as the whole run did in that half. If anything read ahead, the two would differ.
- Timeframe alignment (8): every hourly candle opens on the hour.
- Tick versus bar (9) and spread sensitivity (10): the same strategy on another tick model and on twice the spread.
The same from a terminal, for a CI job — exit code 0 when no check fails, 1 when one does, 2 when it could not run:
python -m bentrix tape practice
python -m bentrix battery --workspace practice/ws --store practice/store
04Against another platform
To compare with MetaTrader's tester or any other backtester, compare trade lists. run_parity takes a finished strategy run and the other engine's list — a CSV or JSON of closed trades — puts both in one canonical form and answers whether they are the same list, and the first trade where they part: against another engine.
For an agent's own trades, read trade_deals and compare in your own code: pair each in deal with its out deals by position, and you have entry time, entry price, exit time, exit price, commission, swap and profit per trade — the columns any other platform's report has.
05Good to know
- Check on the data you will train on. The practice tape proves the mechanics; your own recording has its own spreads, gaps and sessions.
- A check that passes on real ticks should be repeated on the tick model you train with — tick models — since a modelled tick is not a recorded one.
- How one step works describes the order of events inside a step of the ready-made environment.