Bentrix Docs
HomePricingDashboard

Snapshots and branching

Keep a workbench's whole state — its clock, positions, orders and account — in memory, come back to it in a millisecond, try several continuations from one moment, and pick a workbench up again in another sitting exactly where it was left.

Reaching an interesting state costs time: hours of replay, a position opened, a drawdown under way. Often you want to try several things from that same state — three stop distances, ten policies, a hundred random continuations — without replaying the hours before it each time. And sometimes you want to stop for the day and continue tomorrow.

Bentrix gives the engine two tools for this. A snapshot is kept in memory and restored in about a millisecond; it lives as long as your program. The workbench itself is written to disk when your program closes it and reopens where it stood.

01A snapshot, and branches from it

import tempfile

from bentrix import _native
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)
home, owner, _, name = bench.removeprefix("bentrix://").split("/")
where = dict(home=home, owner=owner, bench=name)
symbol = "XAUUSD"

# Reach a state worth branching from: a day in, one long leg open.
engine.run_until(bench, "H1", 24, [symbol])
engine.call("order_market", bench=bench, symbol=symbol, side="buy", volume=0.10)
engine.next_close(bench, "M1", [symbol])
fork = engine.snapshot(bench)
print("kept at", engine.state(bench)["cursor_ms"], "with", len(engine.book(bench)["positions"]), "position")


def outcome(stop_points, hours=12):
    """From the fork: set a stop this far under the entry, run on, and read what became of it."""
    engine.restore(bench, fork)
    leg = engine.book(bench)["positions"][0]
    engine.call("order_modify", bench=bench, ticket=leg["ticket"], sl=round(leg["price_open"] - stop_points * 0.01, 2), tp=0)
    engine.run_until(bench, "H1", hours, [symbol])
    account = engine.read("trade_account", **where)
    return round(account["equity"], 2), len(engine.book(bench)["positions"])


for stop in (100, 300, 900):
    equity, still_open = outcome(stop)
    print(f"stop {stop:>4} points under the entry -> equity {equity}, positions still open: {still_open}")

again = outcome(300)
print("the 300-point branch again:", again)
engine.close()
kept at 1709596860000 with 1 position
stop  100 points under the entry -> equity 9988.52, positions still open: 0
stop  300 points under the entry -> equity 9968.27, positions still open: 0
stop  900 points under the entry -> equity 9920.0, positions still open: 1
the 300-point branch again: (9968.27, 0)

engine.snapshot(bench) answers a number. engine.restore(bench, that_number) puts the workbench back: its clock at the kept moment, its positions and pending orders as they were, its balance and equity as they were, and every order, fill and close made after the snapshot gone.

The program reaches a state — a day into the recording with one long position — and keeps it. Then three branches start from it, each with a different stop. The 100-point and 300-point stops were both met within the twelve hours; the 900-point stop was not, and that position is still open. The last line runs the 300-point branch a second time and gets the same equity to the cent: a branch is as reproducible as a whole run.

02What a snapshot holds

HeldNot held
The clock's momentYour program's own variables: your environment's counters, your agent's memory. Keep those beside the snapshot's number yourself.
Open positions and pending orders, with their stops and targetsTrailing stops armed with order_trail: arm them again after a restore, and after reopening a workspace.
The balance, equity and margin
The deal history up to that moment

It does not copy the market data. A snapshot is the list of everything that was asked of the venue up to that moment — every order, modification and close — and a restore rebuilds the book from that list. That is why it is small and quick, and why it is exact: the venue is deterministic, so the same requests at the same moments give the same book.

A snapshot belongs to the workbench it was taken on and to the program that took it. Restoring it on another workbench is refused, and it is gone when the program ends.

03Uses

  • A fast reset. Take a snapshot of the untouched workbench once; restore it at every reset(). An environment of your own does exactly this.
  • A sweep from one state. As above: one costly approach, many cheap continuations.
  • Trying before deciding. Inside a step: take a snapshot, try an action, run forward, read the outcome, restore. A planning agent can look at several of its own futures this way — futures of its own actions on prices it has not seen, so use it for analysis and never to choose the action that the recording happens to reward: an agent that picks by peeking has learned nothing it can use on a live market.
  • Debugging. Keep a snapshot just before the step that goes wrong, and replay that one step as often as you need.

04Stopping and continuing another day

A workbench's state is written to its workspace when the engine is closed — which with Local(...) as engine: does for you — and it is there when the workspace is opened again.

import tempfile

from bentrix import _native
from bentrix.local import Local

workspace, store = _native.make_tape(tempfile.mkdtemp(prefix="bentrix-practice-"))
symbol = "XAUUSD"

# First sitting: half a day, one position opened, then the program ends.
with Local(workspace=workspace, store=store) as engine:
    bench = engine.call("get_state")["laboratories"][0]["benches"][0]["uri"]
    engine.arm(bench)
    engine.run_until(bench, "H1", 12, [symbol])
    engine.call("order_market", bench=bench, symbol=symbol, side="sell", volume=0.05)
    engine.next_close(bench, "M1", [symbol])
    home, owner, _, name = bench.removeprefix("bentrix://").split("/")
    where = dict(home=home, owner=owner, bench=name)
    left_at = engine.state(bench)["cursor_ms"]
    left_equity = engine.read("trade_account", **where)["equity"]
    print("left at", left_at, "equity", round(left_equity, 2))

# Second sitting, another process or another day: the workbench is where it was left.
with Local(workspace=workspace, store=store) as engine:
    engine.arm(bench)
    print("back at", engine.state(bench)["cursor_ms"], "equity", round(engine.read("trade_account", **where)["equity"], 2))
    for p in engine.book(bench)["positions"]:
        print("still open:", p["ticket"], p["side"], p["volume"], "at", round(p["price_open"], 3))
    engine.run_until(bench, "H1", 6, [symbol])
    print("and on:", engine.state(bench)["cursor_ms"])
left at 1709553660000 equity 9999.88
back at 1709553660000 equity 9999.88
still open: 1 sell 0.05 at 2101.215
and on: 1709575200000

The second Local could be another program, tomorrow. The workbench stands at the same moment with the same equity and the same position, and goes on from there.

Two things to remember:

  • A program that is killed writes nothing. The state is written at close(). A long training run that should survive a crash closes and reopens the engine from time to time, or works on a copy of the workspace folder made at a known point.
  • To keep a state for good, copy the workspace folder while no program has it open. A copy is a complete, independent workbench: open it with Local(workspace=the_copy, store=the_same_store). The recordings in store are not changed by replaying, so many copies can share one store.

05Good to know

  • Restoring is about a millisecond for a short history and grows with the number of orders since the workbench's start, since the book is rebuilt from them.
  • Going back in time without a snapshot is replay_seek with undo_deals=True, which also removes the deals that came after the moment. A snapshot is the direct door when you know in advance where you will want to return.
  • The numbers in this page's output are the practice tape's, a formula. They say nothing about stops in any market.

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