Bentrix Docs
HomePricingDashboard

Orders, legs and exposure

Every order operation from a program on the engine — several positions at once, adding, reducing, closing one or all, reversing, moving stops, trailing, pending orders — and net and gross exposure computed from the book.

An agent that manages a position as several separate entries — adding on the way, closing part, holding a hedge — needs each entry to keep its own price, size, stop and profit. On a hedging account Bentrix's venue works exactly that way: every filled order is a position of its own, with its own ticket. This page calls each one a leg.

Everything here runs on the engine in your own program. The same tools, with the same names and arguments, work through the open application.

01Hedging and netting

A laboratory's account is one of two kinds, chosen when the laboratory is made (lab_create's margin_mode):

  • Hedging — each order opens its own position. A buy and a sell of one market stand side by side. This is what a multi-leg agent wants, and what the practice tape uses.
  • Netting — one position per market. A buy adds to a long or reduces a short; a larger opposite order turns the position around.

02The whole tour

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"


def minute():
    """One minute forward: orders sent before it are filled inside it."""
    engine.next_close(bench, "M1", [symbol])


def legs():
    return engine.book(bench)["positions"]


def exposure():
    """Net and gross exposure from the legs, in lots and against the equity."""
    spec = engine.call("symbol_info", bench=bench, symbol=symbol)
    account = engine.read("trade_account", **where)
    long_lots = sum(p["volume"] for p in legs() if p["side"] == "buy")
    short_lots = sum(p["volume"] for p in legs() if p["side"] == "sell")
    price = legs()[0]["price_current"] if legs() else 0.0
    notional = lambda lots: lots * spec["contract_size"] * price
    return {
        "long_lots": round(long_lots, 2), "short_lots": round(short_lots, 2),
        "net_lots": round(long_lots - short_lots, 2), "gross_lots": round(long_lots + short_lots, 2),
        "net_to_equity": round(notional(long_lots - short_lots) / account["equity"], 3),
        "gross_to_equity": round(notional(long_lots + short_lots) / account["equity"], 3),
        "margin_used": account["margin"], "margin_free": round(account["free_margin"], 2),
    }


engine.next_close(bench, "H1", [symbol])

# Three legs: two longs and a short, each a position of its own with its own ticket.
for side, lots in (("buy", 0.10), ("buy", 0.05), ("sell", 0.03)):
    engine.call("order_market", bench=bench, symbol=symbol, side=side, volume=lots)
minute()
for p in legs():
    print("leg", p["ticket"], p["side"], p["volume"], "at", round(p["price_open"], 3))
print(exposure())

first, second, short = (p["ticket"] for p in legs())
quote = legs()[0]["price_current"]

engine.call("order_close", bench=bench, ticket=first, volume=0.04)          # reduce one leg
engine.call("order_modify", bench=bench, ticket=second, sl=round(quote - 8, 2), tp=round(quote + 12, 2))
engine.call("order_reverse", bench=bench, ticket=short)                     # the short leg: closed, then...
minute()
engine.settle()                                                             # ...its opposite order is sent
minute()
for p in legs():
    print("leg", p["ticket"], p["side"], round(p["volume"], 2), "sl", p["sl"], "tp", p["tp"])
print(exposure())

# A pending order rests in the book until its price is met; closing its ticket cancels it.
placed = engine.call("order_pending", bench=bench, symbol=symbol, kind="buy_limit", price=round(quote - 6, 2), volume=0.02)
resting = placed["orders"][0]["ticket"]
print("resting:", [(o["ticket"], o["kind"], o["price"]) for o in placed["orders"]])
engine.call("order_close", bench=bench, ticket=resting)
print("after the cancel:", engine.book(bench)["orders"])

# A refused order is an answer, in the venue's own words - nothing is clipped into another order.
answer = engine.call("order_market", bench=bench, symbol=symbol, side="buy", volume=0.001)
print("refused:", answer["last_answer"]["reason"])

engine.call("order_close_all", bench=bench)
minute()
print("legs left:", len(legs()))

# Every fill is a deal: the money events, oldest first.
for d in engine.read("trade_deals", **where)["items"]:
    print(d["time_ms"], d["entry"], d["side"], round(d["volume"], 2), "position", d["position"], "price", round(d["price"], 3),
          "commission", d["commission"], "profit", d["profit"])
engine.close()
leg 1 buy 0.1 at 2102.518
leg 2 buy 0.05 at 2102.518
leg 3 sell 0.03 at 2102.318
{'long_lots': 0.15, 'short_lots': 0.03, 'net_lots': 0.12, 'gross_lots': 0.18, 'net_to_equity': 2.524, 'gross_to_equity': 3.786, 'margin_used': 8.41, 'margin_free': 9985.13}
leg 1 buy 0.06 sl 0.0 tp 0.0
leg 2 buy 0.05 sl 2094.16 tp 2114.16
leg 4 buy 0.03 sl 0.0 tp 0.0
{'long_lots': 0.14, 'short_lots': 0, 'net_lots': 0.14, 'gross_lots': 0.14, 'net_to_equity': 2.946, 'gross_to_equity': 2.946, 'margin_used': 9.81, 'margin_free': 9979.32}
resting: [(5, 'buy_limit', 2096.16)]
after the cancel: []
refused: volume 0.001 outside 0.01..100
legs left: 0
1709514015000 in buy 0.1 position 1 price 2102.518 commission -0.53 profit 0.0
1709514015000 in buy 0.05 position 2 price 2102.518 commission -0.26 profit 0.0
1709514015000 in sell 0.03 position 3 price 2102.318 commission -0.16 profit 0.0
1709514075000 out sell 0.04 position 1 price 2102.209 commission -0.21 profit -1.24
1709514075000 out buy 0.03 position 3 price 2102.409 commission -0.16 profit -0.27
1709514135000 in buy 0.03 position 4 price 2102.288 commission -0.16 profit 0.0
1709514195000 out sell 0.06 position 1 price 2101.956 commission -0.32 profit -3.37
1709514195000 out sell 0.05 position 2 price 2101.956 commission -0.26 profit -2.81
1709514195000 out sell 0.03 position 4 price 2101.956 commission -0.16 profit -1.0

03What each operation does

OperationToolNotes
Open a legorder_market (side, volume, optional sl, tp as prices)Answered accepted; fills on the next tick, a buy at the ask and a sell at the bid.
Add to exposureanother order_market on the same sideA new leg with its own entry price. Averaging and pyramiding are this, repeated.
Reduce one legorder_close with volumeCloses that many lots of the leg; the rest keeps its ticket and entry price.
Close one legorder_close with its ticketA close is never refused for being a close.
Close chosen legsorder_close once per ticketIn the order you choose: oldest first, worst first, one side only.
Close everythingorder_close_all (optional symbol)Every position, or one market's. Pending orders stay. With no position open the call is refused with a sentence.
Reverse a legorder_reverseHedging: the leg is closed and a market order of its size is sent the other way. Netting: one order of twice the size.
Move a stop or a targetorder_modify (sl, tp as prices; 0 removes)Answered at once. Also moves a pending order's price.
Trail a stoporder_trail (points), order_untrailSee below.
Place a pending orderorder_pending (kind, price, volume)buy_limit, sell_limit, buy_stop, sell_stop, buy_stop_limit, sell_stop_limit (with stop_limit). It rests in orders until its price is met.
Cancel a pending orderorder_close with its ticket
Ask before sendingorder_previewThe fill price, margin, commissions, spread cost and nightly swap of a market order now. Sends nothing.

Two operations need engine.settle() on the engine. order_reverse on a hedging account is two orders: the close is sent at once, and the opposite order is sent by Bentrix's own housekeeping once the close is under way. In the open application that happens by itself, many times a second. In your own program it happens when you call engine.settle() — as the tour does after one minute — or at your next tool call. Until then the leg is closed and its opposite is not yet sent.

04A trailing stop

A trailing stop follows the price at a fixed distance and never moves back. Bentrix's trail is the trade panel's own: Bentrix moves it, by sending a modify each time the price has moved far enough, and — as in MetaTrader — it begins once the position is that far in profit.

On the engine it is moved when Bentrix does its housekeeping, which is when your program calls engine.settle(). Call it after every close you step, and the stop follows at the pace of your steps:

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)
symbol = "XAUUSD"

engine.next_close(bench, "H1", [symbol])
engine.call("order_market", bench=bench, symbol=symbol, side="sell", volume=0.03)
engine.next_close(bench, "M1", [symbol])
leg = engine.book(bench)["positions"][0]
engine.call("order_trail", bench=bench, ticket=leg["ticket"], points=50)     # 50 points behind the price

seen = None
for minute in range(1, 400):
    engine.next_close(bench, "M1", [symbol])
    engine.settle()                              # the trail is moved here, once a minute in this loop
    legs = engine.book(bench)["positions"]
    if not legs:
        print(f"minute {minute}: the trailing stop closed the position")
        break
    if legs[0]["sl"] != seen:
        seen = legs[0]["sl"]
        if minute < 60 or minute % 20 == 0:
            print(f"minute {minute}: price {legs[0]['price_current']:.3f}, stop now {seen:.3f}")
engine.close()
minute 1: price 2102.238, stop now 0.000
minute 4: price 2101.819, stop now 2102.320
minute 5: price 2101.668, stop now 2102.170
minute 6: price 2101.515, stop now 2102.010
minute 7: price 2101.362, stop now 2101.860
minute 8: price 2101.212, stop now 2101.710
minute 9: price 2101.067, stop now 2101.570
minute 10: price 2100.930, stop now 2101.430
minute 11: price 2100.802, stop now 2101.300
minute 12: price 2100.685, stop now 2101.190
minute 13: price 2100.581, stop now 2101.080
minute 14: price 2100.492, stop now 2100.990
minute 15: price 2100.418, stop now 2100.920
minute 16: price 2100.361, stop now 2100.860
minute 18: price 2100.297, stop now 2100.800
minute 28: the trailing stop closed the position

Without the settle() line the stop would not move at all. A trail that must react to every tick, between your steps, is not something this version does on the engine; a fixed stop (sl) is watched by the venue at every tick and needs nothing from you.

05Reading the legs

engine.book(bench) answers positions, orders and last_answer. Each position holds:

FieldMeaning
ticketThe leg's identity. Every operation on it takes this number.
symbol, side, volumeThe market, buy or sell, and the lots still open.
price_openThe entry price: the ask a buy filled at, the bid a sell filled at.
price_currentThe price it would close at now: the bid for a buy, the ask for a sell.
profitThe open profit at price_current, in the account's currency, before commission and swap.
sl, tpThe stop and the target as prices; 0 for none.
magicA number that says which strategy opened it; 0 for an order sent by a program or by hand.

What a position does not carry is in its deals. A deal is one fill — the money event. engine.read("trade_deals", …) lists them oldest first: entry is in for an opening fill and out for a closing one, position is the leg's ticket, and time_ms, price, volume, commission, swap and profit are that fill's own. So for any leg:

  • its entry time is the time_ms of its in deal;
  • its commission and swap so far are the sums over its deals;
  • its realised profit is the sum of profit over its out deals — a leg reduced twice has two.

06Net and gross exposure

The venue does not net your legs, so both figures are a sum over the book — the exposure() function in the tour:

  • Long and short lots: the sums by side.
  • Net = long − short. Gross = long + short.
  • Against the equity: lots × contract size × price, divided by the equity. symbol_info gives the contract size, trade_account the equity.
  • Against the margin: trade_account gives margin (held now) and free_margin; order_preview gives what one more order would take.

For several markets, compute it per symbol and add the notional values in the account's currency.

In the tour, three legs — long 0.10 and 0.05, short 0.03 — give a net of 0.12 lots and a gross of 0.18, and the margin held is far smaller than either notional: the practice account's leverage.

07A logical session of your own

A group of legs that belong together — opened over an hour, closed over the next — is something your program defines. Keep a set of tickets per group as you open them, and compute the group's figures from the deals whose position is in the set. The venue keeps every leg and every deal; the grouping is yours.

08Good to know

  • An order is refused in the venue's words, never changed into another: too small or too large a volume, a stop on the wrong side or closer than the market's stops level, too little free margin, a closed market. Read last_answer after every send.
  • A stop is met by the price that would close the position: the bid for a long, the ask for a short. It fills at the first such price at or through the stop, which can be worse than the stop itself.
  • When the margin level falls to the account's stop-out level (stop_out_pct in trade_account), the venue closes positions itself, as a broker does.
  • A pending order has no expiry time in this version: it rests until it is met or you cancel it.
  • An order fills whole, at one price. This version has no partial fills.

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