bentrix.data and bentrix.vector — a workbench's candles as NumPy columns, a check of how each day is held, triple-barrier labels, walk-forward and purged splits, a vectorised first pass over a signal, and its reconciliation with the engine.
Two Python modules turn a workbench into arrays. bentrix.data reads candles into NumPy columns and prepares them for supervised learning. bentrix.vector runs a signal over those columns in one sweep — fast enough to try thousands of variants — and then tells you how far that shortcut is from the engine's own fills.
Both run on the engine in your own program. They need NumPy: pip install "bentrix[engine]".
01The whole flow
import tempfile
import numpy as np
from bentrix import _native, data, vector
from bentrix.backtest import Strategy, run
from bentrix.local import Local
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)
origin = engine.snapshot(bench) # the untouched workbench, to come back to
symbol = "XAUUSD"
spec = engine.call("symbol_info", bench=bench, symbol=symbol)
# What the store holds for these days, before standing a study on them.
report = data.quality(engine, bench, symbol)
print("traded days:", len(report["traded"]), "| modelled from candles:", len(report["modelled"]), "| days with holes:", len(report["holes"]))
print("runs of whole-tick days:", data.segments(report), "| allowing modelled days:", data.segments(report, allow_modelled=True))
# A dataset is what the workbench has seen: advance it, then read.
engine.advance(bench, engine.state(bench)["bounds"]["to_ms"])
bars = data.bars(engine, bench, symbol, "M15")
print("M15 candles:", len(bars["close"]), "| columns:", ", ".join(bars))
labels, ambiguous = data.triple_barrier(bars, point=spec["point"], target_points=300, stop_points=200, horizon=16)
print("labels +1:", int((labels == 1).sum()), " -1:", int((labels == -1).sum()), " 0:", int((labels == 0).sum()), "| ambiguous:", int(ambiguous.sum()))
for train, test in data.walk_forward(len(labels), train=200, test=80):
print("walk-forward: train", train[0], "to", train[-1], "| test", test[0], "to", test[-1])
for train, test in data.purged_kfold(len(labels), k=3, horizon=16, embargo=4):
print("purged fold: test", test[0], "to", test[-1], "| train rows kept:", len(train))
# A first pass in one sweep of the columns: long while the close is under its 20-candle mean.
close = bars["close"]
mean = np.convolve(close, np.ones(20) / 20, mode="full")[: len(close)]
signals = np.where(np.arange(len(close)) >= 20, np.where(close < mean, 1, 0), 0)
fast = vector.from_signals(bars, signals, point=spec["point"], contract_size=spec["contract_size"], lots=0.10)
print("vectorised pass:", len(fast), "trades, gross", round(sum(t.gross for t in fast), 2))
# The same signals through the venue - the workbench brought back to its start - and the two side by side.
class Replay(Strategy):
def on_start(self, ctx):
self.i, self.held = 0, 0
def on_bar(self, bar, ctx):
want = int(signals[self.i]) if self.i < len(signals) else 0
self.i += 1
if want != self.held:
if self.held:
ctx.close_all()
if want:
ctx.buy(0.10)
self.held = want
engine.restore(bench, origin)
run(Replay(), bench, interval="M15", local=engine)
home, owner, _, name = bench.removeprefix("bentrix://").split("/")
deals = engine.read("trade_deals", home=home, owner=owner, bench=name)["items"]
r = vector.reconcile(fast, deals, point=spec["point"])
print("engine trades:", r.engine_trades, "| bid side worst gap:", round(r.bid_worst_points, 1), "points | ask side mean gap:", round(r.ask_mean_points, 1), "points")
print("gross: vectorised", round(r.vector_gross, 2), "| engine", round(r.engine_gross, 2), "| engine's costs", round(r.engine_costs, 2), "| within tolerance:", r.within)
engine.close()
traded days: 5 | modelled from candles: 5 | days with holes: 0
runs of whole-tick days: [] | allowing modelled days: [('2024-03-04', '2024-03-08')]
M15 candles: 472 | columns: time_ms, open, high, low, close, tick_volume, spread_points
labels +1: 184 -1: 284 0: 4 | ambiguous: 0
walk-forward: train 0 to 199 | test 200 to 279
walk-forward: train 80 to 279 | test 280 to 359
walk-forward: train 160 to 359 | test 360 to 439
purged fold: test 0 to 156 | train rows kept: 311
purged fold: test 157 to 313 | train rows kept: 295
purged fold: test 314 to 471 | train rows kept: 298
vectorised pass: 20 trades, gross -300.75
engine trades: 20 | bid side worst gap: 5.0 points | ask side mean gap: 11.0 points
gross: vectorised -300.75 | engine -329.65 | engine's costs -46.13 | within tolerance: True
The sections below take it one step at a time.
02How each day is held: quality and segments
Not every day of a recording is equally good ground. A day may be held as real ticks; or only as candles, with its ticks modelled from them; or as a tick file with hours missing. A study that needs real ticks should know which days it stands on.
data.quality(engine, bench, symbol)answers the store's own report:traded(every day it holds candles for),modelled(traded days with no tick file),holes(days whose tick file has hours missing, as{"day", "hours"}) andper_year(each year's counts).data.segments(report, allow_modelled=False, allow_holes=False)answers the runs of consecutive days you can stand on, as(first, last)dates. A weekend does not break a run; a modelled or holed day does, unless you allow that kind.
The practice tape is built from candles, so all five days are modelled: no run of whole-tick days, and one run of five when modelled days are allowed. The thresholds are yours — the report gives you the counts to set them from.
03Candles as columns: bars
data.bars(engine, bench, symbol, interval) answers a dict of NumPy arrays, oldest first: time_ms, open, high, low, close, tick_volume, spread_points.
- It reads up to the workbench's clock and never past it. A dataset is what the workbench has seen. That is why the program first advances the clock to the end of the days. The candle still forming at the clock is left out.
- The prices are the bid's. The ask is the bid plus the candle's own spread:
spread_points× the market's point. strict=Truerefuses, naming the days, when a candle stands on a modelled or holed day — unlessallow_modelledorallow_holespermits that kind.data.to_arrow(columns)makes an Arrow table of them (pip install pyarrow).data.indicator(engine, bench, symbol, interval, "custom:<id>", inputs)reads one of your own indicators' values over the same candles, one column per line.
04Labels: triple_barrier
For supervised learning you need, for each candle, what happened next. The triple-barrier label asks: had a position been opened at the next candle's open, with a target target_points away and a stop stop_points away, which was met first within horizon candles?
labels, ambiguous = data.triple_barrier(columns, point, target_points, stop_points, horizon, side=1)
+1the target first,-1the stop first,0neither within the horizon.- The entry and the barriers use the right side of the market: a long enters at the ask and its barriers are met by the bid; a short the reverse (
side=-1). - A candle that touches both barriers is counted as the stop, and flagged in
ambiguous. Inside one candle the order of its high and low is unknown, and the reading that does not flatter is the honest one.
05Splits that do not leak
A model tested on rows it was trained on — or on rows whose labels overlap the training rows — reports a skill it does not have.
data.walk_forward(n, train, test, anchored=False)yields(train_rows, test_rows): a training stretch, then the test stretch right after it, rolling forward. Every test comes after its training.anchored=Truekeeps the training's start fixed.data.purged_kfold(n, k, horizon, embargo=0)yieldskfolds. From each fold's training rows it removes the rows whose label reaches into the test fold (horizonrows before it) and anembargoof rows after it.
In the output above, the three purged folds keep 311, 295 and 298 training rows of 472: the difference is the rows purged and embargoed around each test fold.
06A first pass in one sweep: vector.from_signals
vector.from_signals(columns, signals, point, contract_size, lots) turns a signal per candle — +1 long, -1 short, 0 flat — into a list of trades in one pass. A change of signal at candle i acts at candle i + 1's open: a long enters at the ask and leaves at the bid, a short the reverse. Each Trade has side, entry_ms, entry, exit_ms, exit and gross.
It is fast because it is simple. It is not the engine: no commission, no swap, no margin, no stop met inside a candle, and the candle's recorded spread instead of the venue's.
07How far the shortcut is from the engine: reconcile
So measure the difference. The program runs the same signals through the venue with a strategy written in Python, then sets the two trade lists side by side:
r = vector.reconcile(fast_trades, engine_deals, point)
| Field | Meaning |
|---|---|
trades, engine_trades | The two counts. |
bid_worst_points | The largest gap on the bid side — a long's exit, a short's entry. |
ask_worst_points, ask_mean_points | The gap on the ask side: the venue's spread against the candle's recorded one. Reported, never assumed away. |
vector_gross, engine_gross | Each side's gross result. |
engine_costs | The commission and swap the venue booked and the shortcut left out. |
within | The counts are equal and every bid-side gap is within vector.PRICE_TOLERANCE_POINTS (5 points, measured on the practice tape). |
Above: twenty trades on both sides, bid-side gaps of at most 5 points, an ask side 11 points apart on average, and 46.13 of costs the shortcut never saw. The shortcut ranked a rule quickly; the engine's figure is the one to believe.
08Good to know
- The same labels can be written to a CSV file without Python: the
extract_datasettool, shown in a labelled dataset. - For windows of several timeframes at every close, as a model's input, see
extract_windowsand several timeframes without look-ahead. - Every variant you try is a trial. Testing many and reporting the best is the commonest way to fool yourself: the trial ledger and statistics against chance.