Bentrix Docs
HomePricingDashboard

A strategy in Python, candle by candle

bentrix.backtest — write a strategy with on_bar, and the engine calls it at every closed candle with a context that buys, sells, modifies and closes on the workbench's own venue; one market or several on one clock.

The engine in your own program is a loop you write: move the clock, read, decide, send. For a rule-based strategy there is a shorter form. You write a strategy with callbacks — a small Python type of your own — and bentrix.backtest.run drives the loop: at every closed candle it calls your on_bar with that candle and a context to trade through.

Nothing is simulated twice. The orders go to the workbench's own venue: filled at the bid or the ask on the next tick, with the workbench's commission, swap, margin and stops rules, and with every tick between two closes fed to the venue — so a stop or a target is met where the recording meets it, not at the candle's close.

01A strategy

import tempfile

from bentrix import _native
from bentrix.backtest import Strategy, run
from bentrix.local import Local


class Breakout(Strategy):
    """Long when an hour closes above the highest high of the eight before it; out when it closes
    under the lowest low of the four before it. One position at a time."""

    def on_start(self, ctx):
        self.highs, self.lows = [], []

    def on_bar(self, bar, ctx):
        held = ctx.positions()
        if len(self.highs) >= 8:
            if not held and bar.close > max(self.highs[-8:]):
                ctx.buy(0.10, sl=round(bar.close - 6.0, 2))
            elif held and bar.close < min(self.lows[-4:]):
                ctx.close(held[0]["ticket"])
        self.highs.append(bar.high)
        self.lows.append(bar.low)


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"]
    result = run(Breakout(), bench, interval="H1", local=engine)
    print("hourly closes handed to the strategy:", result["bars"])

    home, owner, _, name = bench.removeprefix("bentrix://").split("/")
    deals = engine.read("trade_deals", home=home, owner=owner, bench=name)["items"]
    closes = [d for d in deals if d["entry"] == "out"]
    print("round trips:", len(closes))
    for d in closes[:3]:
        print("  closed", d["volume"], "at", round(d["price"], 2), "profit", d["profit"], "commission", d["commission"], "swap", d["swap"])
    account = engine.read("trade_account", home=home, owner=owner, bench=name)
    print("balance at the end:", account["balance"], "| positions still open:", len(engine.book(bench)["positions"]))
hourly closes handed to the strategy: 117
round trips: 4
  closed 0.1 at 2101.34 profit -33.23 commission -0.53 swap -6.29
  closed 0.1 at 2102.17 profit -18.94 commission -0.53 swap -6.29
  closed 0.1 at 2099.72 profit -24.2 commission -0.52 swap -18.87
balance at the end: 9903.75 | positions still open: 1

The practice tape is a formula, not a market, and this rule lost on it. The lines to read are the last ones: each closed trade carries its own commission and swap, booked by the venue. A position held over a night paid swap; one held over the triple-swap night paid three nights' worth. A backtest that ignores those reports a different balance.

02The callbacks

Override the ones you need:

CallbackCalled
on_start(ctx)Once, before the first candle. Set up your state here.
on_bar(bar, ctx)At each close of the interval, with the candle that closed.
on_bars(bars, ctx)With several markets: every market's candle that closed at this close, as a dict by symbol. A market with no candle there — its session shut — is absent.
on_end(ctx)Once, after the last candle.

A Bar has time_ms (its opening time, UTC milliseconds), open, high, low, close and volume.

on_bar is called after the candle closed and before the next tick. An order sent in it fills on that next tick. A strategy can never be filled at the close it has just read.

For the same reason an order sent in on_end has no next tick to fill on: the recording is over. A position still open at the last candle stays open, and the book the run answers shows it — as in the output above. To end flat, close a few candles before the end.

03The context

MethodWhat it does
ctx.buy(volume, sl=None, tp=None, symbol=None)A market buy. sl and tp are prices.
ctx.sell(volume, sl=None, tp=None, symbol=None)A market sell.
ctx.pending(kind, price, volume, sl=None, tp=None, stop_limit=None, symbol=None)A pending order: buy_limit, sell_limit, buy_stop, sell_stop, buy_stop_limit, sell_stop_limit.
ctx.close(ticket, volume=None)Close a position, whole or volume lots of it. A pending order's ticket cancels it.
ctx.modify(ticket, sl, tp, price=None)Set a position's or a pending order's stop and target (0 for none), and a pending order's price.
ctx.close_all(symbol=None)Close every position, or one market's.
ctx.positions(symbol=None)The open positions.
ctx.orders(symbol=None)The pending orders.
ctx.book()Positions, orders and the venue's last answer.

Each trading method answers the book, with the venue's answer in last_answer: accepted, or refused with its reason. ctx.symbol is the market an order takes when it names none; ctx.bench is the workbench.

04run

result = run(strategy, bench, symbol=None, interval="H1", local=None, max_bars=None, symbols=None)
ArgumentMeaning
strategyYour strategy: an object of the type you wrote.
benchThe workbench's address. The run starts from where its clock stands and goes to the end of its days.
symbolThe market. The workbench's first when omitted.
intervalThe candle on_bar is called on: M1 to W1, or a custom one such as M12. A daily candle closes at the workbench's own midnight, a weekly one at the week's end.
localThe engine to run on. A new Local() on your own workspace when omitted.
max_barsStop after this many closes.
symbolsSeveral markets, walked on one clock; on_bars receives them.

It answers {"bars": the closes handed over, "book": the book at the end}. The trades themselves are the workbench's: read them with engine.read("trade_deals", …), or open the workbench in Bentrix afterwards and see them on its chart and in its History.

05Several markets, one account

class Pair(Strategy):
    def on_bars(self, bars, ctx):
        if "XAUUSD" in bars and "XAGUSD" in bars and not ctx.positions():
            ctx.buy(0.10, symbol="XAUUSD")
            ctx.sell(0.50, symbol="XAGUSD")

run(Pair(), bench, interval="H1", symbols=["XAUUSD", "XAGUSD"], local=engine)

Both markets must be on the workbench. There is one account and one venue: margin, stop-out and the book are the workbench's across all of them, as on a real account. A practice tape with a second market is _native.make_tape(folder, also=[("XAGUSD", 0.0125)]).

06From a terminal

The same run without writing the loader, for a script or a CI job:

python -m bentrix tape practice
python -m bentrix backtest --workspace practice/ws --store practice/store --strategy my_module:Breakout --interval H1

It prints one JSON object — the closes handed over and the book at the end — and exits with 0, or with 2 and the reason when it could not run.

07Which form to use

  • This formA rule per closed candle, in a few lines.
  • The strategy engineA strategy written as a document, run by Bentrix itself, with batches, walk-forward and the trial ledger.
  • An environment of your ownWhen a learning algorithm, not a rule, chooses the action.
  • A fast first passThousands of rule variants in one sweep of NumPy columns, checked against the engine afterwards.

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