Bentrix Docs
HomePricingDashboard

The engine in your own program

Bentrix's replay clock and venue inside your own Python process — no window, no server — opened with bentrix.local.Local, stepped a candle at a time, traded and read with the same tools an agent calls.

Every other page of this section talks to a Bentrix that is open on your screen. This page is the other way to work: the engine inside your own Python process. Your program opens a workspace, moves a workbench's clock, sends orders to its venue and reads the book — at the speed your program runs, with nothing drawn.

It is the same engine. An order is filled by the same venue, at the bid or the ask, with the same commission, swap, margin and stops rules as in the window; the clock still cannot be read past. What changes is who drives it.

01When to use it

You wantUse
To watch what your program does, on chartsConnect to the open application
A paper or a real workbench, on the market's own clockThe open application (on a live market)
Thousands of episodes, a backtest, a dataset, a test in CIThe engine in your program — this page

The engine in your program reaches laboratory and paper workbenches. It never reaches a real account.

02What you need

  • Python 3.9 or later and the package: pip install "bentrix[gym]" (NumPy and Gymnasium come with it).
  • Bentrix installed on the same computer. The engine is a library that comes with the application — libbentrix — and the package finds it in Bentrix's own folder. To point it at another copy, set BENTRIX_FFI to the file or BENTRIX_FFI_DIR to its folder.
  • A computer signed in to Bentrix with Plus or Pro. With Free, a program works through the open application instead.
  • A workspace that is free. One workspace has one writer: while the Bentrix window is open on your workspace, Local() on that same workspace is refused, and the refusal names the process that holds it. Close the window, or give the program a workspace of its own, as below.

03A practice recording

To try anything on this page without touching your own workspace, make the practice tape: a small recording of one market over five days, built from a formula. It is the same bytes on every computer, so your numbers will match the ones printed here. It is nobody's prices — it says nothing about any market.

From a terminal:

python -m bentrix tape practice

That writes a folder practice holding a workspace (practice/ws) and its recordings (practice/store), and prints the two paths. The programs on these pages make a fresh tape for themselves with the same function, bentrix._native.make_tape(folder), so each run starts from an untouched workbench.

04First steps

import tempfile

from bentrix import _native
from bentrix.local import Local

# A practice recording: five days of one market, the same bytes on every computer.
folder = tempfile.mkdtemp(prefix="bentrix-practice-")
workspace, store = _native.make_tape(folder)

with Local(workspace=workspace, store=store) as engine:
    laboratory = engine.call("get_state")["laboratories"][0]
    bench = laboratory["benches"][0]["uri"]
    engine.arm(bench)                                  # the venue over the recording, ready

    state = engine.state(bench)
    symbol = state["markets"][0]
    print("workbench:", state["name"], "| market:", symbol, "| ticks:", state["tick_model"])

    # One hour forward: every tick of it fed to the venue, the closed candle handed back.
    reached, opened, candles = engine.next_close(bench, "H1", [symbol])
    time_ms, o, h, l, c, volume = candles[0][1]
    print("the H1 candle that closed:", *(round(x, 3) for x in (o, h, l, c)))   # gold has 3 decimals here

    # An order is answered at once and fills on the next tick.
    answer = engine.call("order_market", bench=bench, symbol=symbol, side="buy", volume=0.10)
    print("sent:", answer["last_answer"])
    engine.next_close(bench, "M1", [symbol])           # one minute on: the fill has happened

    book = engine.book(bench)
    print("then:", book["last_answer"])
    for p in book["positions"]:
        print("position", p["ticket"], p["side"], p["volume"], "at", p["price_open"], "profit", round(p["profit"], 2))

    home, owner, _, name = bench.removeprefix("bentrix://").split("/")
    account = engine.read("trade_account", home=home, owner=owner, bench=name)
    print("balance", account["balance"], "equity", round(account["equity"], 2), "margin", account["margin"])

It prints:

workbench: First run | market: XAUUSD | ticks: ohlc-m1
the H1 candle that closed: 2102.357 2103.553 2101.636 2102.268
sent: {'accepted': 'buy 0.1'}
then: {'filled': 'buy 0.1', 'stops_rewritten': False, 'ticket': 1}
position 1 buy 0.1 at 2102.518 profit -3.59
balance 9999.47 equity 9995.88 margin 7.01

Read it line by line:

  1. Local(workspace=…, store=…) opens a workspace and its recordings. Local() with nothing opens your own. Used with with, the workspace is written and released when the block ends.
  2. engine.call("get_state") is a tool call. Every tool of the MCP reference is called this way — its name, then its arguments by name — and the answer is a Python dict.
  3. engine.arm(bench) readies the workbench's venue over its recording. Do it once per workbench before moving its clock.
  4. engine.next_close(bench, "H1", [symbol]) moves the clock to the end of the hour it stands in. Every tick on the way is fed to the venue, so a stop, a target or a pending order between two closes is met where the recording meets it. It answers (reached, opened, candles): where the clock now stands, when the closed candle opened, and each market's candle as [time_ms, open, high, low, close, volume].
  5. order_market is answered at once with accepted, and fills on the next tick — never on the price your program was looking at when it decided. One minute later the book says filled and holds the position.
  6. engine.book(bench) and engine.read("trade_account", …) read the positions and the money without moving anything.

The buy was sent when the hour closed with the bid at 2102.268, and it filled at 2102.518: the next tick's ask. That difference — the spread, and the tick the program could not have seen — is what a backtest that fills at the closing price leaves out.

05Every method of Local

MethodWhat it does
Local(workspace=None, store=None)Opens a workspace (yours when None) and its recordings. Refused if another process holds the workspace, or if this computer's account is on Free.
close()Writes the workspace and lets it go. A program killed before this writes nothing, so use with Local(...) as engine:.
call(tool, **arguments)One tool by its name. A refusal by Bentrix raises RuntimeError carrying Bentrix's own sentence.
read(resource, **variables)One resource by its name: trade_book, trade_account, trade_deals, data_quotes, data_ticks, data_bars, workbench_state, workbench_journal. Moves nothing.
arm(bench, max_frames=20000)Readies the workbench's venue and waits until it is ready.
advance(bench, to_ms)Moves the clock to a moment (UTC milliseconds), tick by tick, the venue fed all the way. Answers where it stands.
next_close(bench, interval, symbols, end_ms=None)One close of interval in one call; None at end_ms or at the end of the workbench's days.
run_until(bench, interval, n, symbols, end_ms=None)next_close n times; the closes as a list. For a program that acts on none of them.
candle_span(bench, interval, at_ms)The candle holding a moment, as the workbench's chart cuts it: (opens, closes). A daily candle starts at the workbench's own midnight, a weekly one on Monday.
state(bench)The workbench as it stands: its clock (cursor_ms), its days (bounds), markets, tick model and time zone.
book(bench)Open positions, pending orders, and the venue's last answer.
snapshot(bench) and restore(bench, id)Keep a workbench's state in memory and come back to it: snapshots and branching.
settle(max_frames=1000)Lets Bentrix finish work it has queued. Needed after order_reverse and for a trailing stop: orders, legs and exposure.

A workbench is named by its address, such as bentrix://lab/lab-1/bench/bench-2. get_state lists them. A resource takes the address in three parts — home (lab), owner (lab-1) and bench (bench-2) — which is what the split("/") line produces.

06Two kinds of "no"

  • Bentrix refuses the call. The tool does not exist, an argument is missing or of the wrong kind, the workbench is gone. call raises RuntimeError with the sentence.
  • The venue refuses the order. The volume is outside the market's limits, a stop is on the wrong side, the market is closed. That is an answer, as it would be at a broker: the call returns, and last_answer holds refused and the reason in the venue's words. Nothing is changed into a different order.
answer = engine.call("order_market", bench=bench, symbol=symbol, side="buy", volume=0.001)
print(answer["last_answer"])   # {'reason': 'volume 0.001 outside 0.01..100', 'refused': 'buy 0.001'}

07The ready-made environment, on the engine

TradingEnv — the environment the rest of this section describes — runs on the engine too: pass the engine as local. Nothing else about it changes: the same settings, observations, actions and rewards.

import tempfile

from bentrix import _native, track
from bentrix.gym import TradingEnv, evaluate
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"]
    env = TradingEnv(bench, interval="M15", window=16, episode="window", episode_bars=96, reward="pnl@1", local=engine)

    obs, info = env.reset(seed=1)
    obs, reward, terminated, truncated, info = env.step(1)          # 1 = long
    print("after one step: reward", round(reward, 4), "| equity", round(info["equity"], 2), "| ledger", info["ledger_hash"][:12])

    flat = evaluate(lambda obs: 0, env, seeds=range(10))            # the policy that never trades
    always_long = evaluate(lambda obs: 1, env, seeds=range(10))
    print("flat: IQM of the log return", round(flat["iqm"], 6))
    print("always long: IQM", round(always_long["iqm"], 6), "interval", [round(x, 6) for x in always_long["interval"]])

    tags = track.identity(ledger_hash=always_long["ledger_hashes"][0], reward=env.reward_name, seed=0, bench=bench)
    print(tags)
    print("trackers reached:", track.log_run(tags, params={"window": 16}, metrics={"iqm": always_long["iqm"]}))
    env.close()
after one step: reward 0.959 | equity 10000.96 | ledger b135450247ca
flat: IQM of the log return 0.0
always long: IQM 5.3e-05 interval [-0.000261, 0.000221]
{'bentrix.env': 'bentrix/TradingEnv-v0', 'bentrix.build': '0.1.382+d7ec1b8', 'bentrix.reward': 'pnl@1', 'bentrix.seed': 0, 'bentrix.ledger_hash': 'deae5edd163763df8e47efe0932d4756bd7ef33bc525fe6f32fab1d141c98706', 'bentrix.bench': 'bentrix://lab/lab-1/bench/bench-2'}
trackers reached: []

bentrix.track.identity gathers what names a run — the engine's build, the reward, the seed, the ledger hash — and bentrix.track.log_run writes those tags, with your parameters and metrics, to MLflow's active run and to Weights & Biases when either is installed. It answers the trackers it reached: here none is installed, so the list is empty and nothing was sent anywhere.

08How fast it is

Measured on one desktop computer on the practice tape (one-minute candles of four ticks each): about 4,000 one-minute closes a second with next_close alone. A tool call costs about 2 milliseconds; reading the book or the account about 0.03. So a step that sends one order and reads the book and the account runs at roughly 400 a second while the book is small, and a step that only reads runs about ten times faster. Read with read and book where you can, and keep call for what changes something.

09Where to go next

Bentrix 0.1.382Every number, name and default on these pages is read from the application itself.What is comingWhat changed