Positions, PnL and risk¶
Every fill an owning strategy sees is booked into PositionTracker, one position per strategy and instrument. PnLCalculator marks those positions against prices from the market data stream. RiskManager checks each order before it leaves the engine, and the StrategyManager worker halts a strategy whose PnL passes its loss limit. An optional memory-mapped file keeps the positions across restarts.
Positions and FIFO lots¶
A Position holds the signed quantity (positive long, negative short), the average entry price, gross realized PnL, realized_fees, open_fees, the contract multiplier and the time of the last fill. Beside it PositionTracker keeps a queue of open lots (quantity, price, timestamp).
A fill in the direction of the position, or onto a flat one, adds a lot and updates the average price. A fill against it consumes lots oldest first. Each lot closed realizes (exit - entry) x quantity x multiplier for a long and the reverse for a short, rounded to 1e-8 per lot. A fill larger than the whole position closes every lot, then opens a new lot at the fill price for the rest. A position that reaches 0 resets its average price to 0.
The average price is not recomputed after a FIFO close
avg_price is the weighted average of every entry since the position was last flat. Closing the oldest lot does not change it, but unrealized PnL is quantity x (mark - avg_price) x multiplier. Example: buy 1 at 100, buy 1 at 200 (average 150), sell 1 at 200. Realized is +100 (the 100 lot closed) and the open lot is the one at 200, but avg_price stays 150, so at a mark of 200 unrealized is +50 and total PnL reads 150 where the cash result is 100. The error stays until the position is flat. The same avg_price is what GET /api/positions returns and what the store keeps.
Fills of scope ORDER book no position, and LEG fills book the leg's instrument. See Order lifecycle. Positions are keyed by the owning strategy's name. Two strategies trading one instrument have two positions.
There is no way to clear a position at runtime. clear_strategy_positions and clear_all exist on the tracker and nothing calls them.
Fees¶
A fill's fee is fee_amount when it is above 0, otherwise compute_fee() over the tracker's fallback FeeStructure. Nothing in the engine sets that fallback. The fee_structure a connector sends in its register event is not read, so unless a host sets it the fallback rate is 0 and a fill with no fee_amount costs nothing. Fee types are PERCENTAGE (|price x qty| x rate), PER_UNIT (|qty| x rate) and FIXED_AMOUNT (rate per fill).
Coinbase fills carry the increment of the order's total_fees. Hyperliquid fills carry abs(fee) from userFills, so a negative (rebate) fee is booked as a cost, and an immediate fill reported by the REST call carries 0.
Fees move through the position like this:
- An entry fee is added to
open_feesand reduces unrealized PnL while the lot is held. - Closing a lot moves that lot's share of
open_fees(by quantity) torealized_fees, together with the matching share of the closing fill's fee. - On a reversal, the part of the closing fill's fee that belongs to the new quantity becomes the new
open_fees.
PnLSnapshot reports net values: realized_pnl is gross realized minus realized_fees, unrealized_pnl is mark-to-market minus open_fees, total_pnl is their sum, and total_fees is realized_fees + open_fees for reference only.
Futures multipliers¶
An instrument's contract multiplier is the currency value of a one-unit price move per unit held (ES is 50, a spot product is 1). It comes from the broker's InstrumentDefinitionEvent, or from a fill that carries contract_multiplier (as a replayed one does, before any definition arrives). set_contract_multiplier refuses a value that is not finite or not positive.
A new multiplier applies to positions already held from then on, and to later fills. PnL realized earlier stays as booked. Realized PnL, unrealized PnL and the order value check (|price x qty| x multiplier) all use it. The multiplier is stored with each position, so it is known again after a restart before the definition arrives.
Zero and negative prices¶
Calendar spreads and some outright futures trade at zero or below, so the engine treats only NULL_PRICE as a missing price. A fill at NULL_PRICE is skipped with an error. A mark is valid when it is not NULL_PRICE and its magnitude is below NULL_PRICE / 100 (about 9.2e8 in price units), which also rejects the exchange sentinels some venues send. The risk order value takes the absolute value.
POST /api/orders still refuses a limit price of 0 or less, and close_all_positions() builds its price as 90% or 110% of the mark, which points the wrong way for a negative mark (see Loss-limit halts).
Marks and unrealized PnL¶
PnLCalculator stores a bid mark and an ask mark per instrument. A long position is valued at the bid mark and a short one at the ask mark. An instrument with no mark yet contributes no unrealized PnL to the snapshot.
| Event | Bid mark | Ask mark |
|---|---|---|
Any TRADE on the bus |
the trade price | the trade price |
| A fill, before strategies see it | the fill price | the fill price |
A QUOTE with both sides valid |
best bid | best ask |
| Top of an L2 or MBO book, both sides non-empty | best bid | best ask |
Prices that fail the validity rule are ignored. A one-sided book or quote marks nothing. A trade or fill overwrites both marks until a top of book with different prices arrives, so the bid and ask split holds only between a book change and the next trade. An instrument that only a dashboard ladder streams has trades and fills as its only marks, because MANUAL's holds keep no strategy book. See Market data.
The marks are not persisted. After a restart a restored position has no unrealized PnL until its instrument next trades, quotes or fills.
/api/positions and /api/pnl value a position differently
GET /api/positions computes unrealized_pnl from the mid of the two marks, gross of fees, and a position whose instrument has no mark is valued against a mark of 0. GET /api/pnl and the WebSocket pnl_update use the bid or ask side and net of open fees. GET /api/positions/:strategy_id returns no marks or unrealized PnL.
Risk manager¶
submit_order calls RiskManager::validate_order before any order is queued. It runs these checks in order and stops at the first failure.
| # | Check | Rejects when |
|---|---|---|
| 1 | Halted | The strategy is halted. Reason Strategy halted: <reason>. |
| - | No limits | The strategy has no limits registered: every other check is skipped and the order passes. |
| 2 | Position | The position after the order exceeds max_position_size in magnitude and the order does not reduce it. Uses the instrument's override if there is one. |
| 3 | Order value | abs(price x quantity) x multiplier is above max_order_value (instrument override if any). |
| 4 | Rate | The strategy already placed max_orders_per_second orders in the current one-second window. |
The window is fixed (it starts at the first order after the previous one ended) and counts only orders that passed checks 1 to 3. A limit of 0 rejects every order.
A reducing order is one that leaves the position smaller in magnitude, even if it flips the sign.
Defaults¶
Key in risk_limits |
Struct default | No <name>.config.json at all (plugin) |
|---|---|---|
max_position_size |
1,000,000 | 1.0 |
max_order_value |
100,000 | 50,000 |
max_orders_per_second |
100 | 10 |
max_loss_per_strategy |
-10,000 | -10,000 |
instruments |
none | none |
A strategy with a config file that leaves out risk_limits, or any key in it, gets the struct default for that key, which is looser than having no file. MANUAL takes the struct defaults unless a file named MANUAL gives limits. The per-instrument block is risk_limits.instruments.<name>.{max_position_size, max_order_value}, and the REST endpoints call it instrument_limits. PUT /api/strategies/:id/risk replaces the limits at once. See REST API.
What is not checked¶
- Working orders. The position check sees only what has filled, so many orders at the size limit can rest together and fill past it.
- Market orders have no order value check: their price is
NULL_PRICE, the notional is NaN, and NaN is never above the limit. - Total exposure across instruments, strategies or brokers. Every limit is per strategy, and per instrument for position and value.
- Modifies.
modify_orderpublishes with no risk or broker status check. - Order quantity: zero, negative or below the instrument's minimum. The definition's tick size and quantity limits are passed to strategies and are not enforced.
- The loss limit. It is polled once a second, not applied to an order.
close_all_positions(), which bypasses risk and the broker status check by design.- Currency. PnL and order value sum raw price units across instruments.
Loss-limit halts¶
Once a second the worker computes calculate_pnl for every strategy that is not halted, MANUAL included. If total_pnl is below max_loss_per_strategy (strictly), it logs an error and runs:
close_all_positions():cancel_all_orders(), then for every non-flat position a limit order for the whole quantity, with time in forceIOCandpost_onlyfalse, priced 10% through the mark (a long sells at 0.90 x mark, a short buys at 1.10 x mark). The mark is the mid of the instrument's bid and ask marks when it has any, otherwise the position's average price. These orders skip risk and the broker status check.RiskManager::halt_strategy: every latersubmit_orderis refused until a resume.strategy->stop().
POST /api/strategies/:id/halt sets only the halt flag, so it refuses new orders but does not stop the strategy or cancel anything. POST .../resume clears only the flag. A strategy halted by a loss limit stays stopped after a resume, and needs POST .../control with start. Halted strategies are skipped by the 1 s checks.
Emergency close has limits
- It needs the broker of each instrument, and that map is filled only when this process's
submit_orderplaces an order in it. Positions restored from the store, and any instrument the strategy has not traded since the start, are skipped with a warning and stay open. - The 90% and 110% factors work only for positive prices. A negative mark gives a limit price on the wrong side of the market.
- A halted or stopped strategy still receives every market data and order callback. Its code decides whether to react.
- The loss counts everything the position store holds. It is cumulative, not daily, and it restarts from the stored realized PnL, so a strategy that is already past its limit when the engine starts is halted at the first check.
Auto-pause on broker disconnect¶
At the same 1 s tick, check_broker_status() looks at the brokers named in each strategy's get_subscriptions() when it was added. If one of them has market data enabled and not connected, the strategy is stopped through its normal stop(), recorded as auto-paused with the reason MD disconnected for broker <name>, and shown as paused in GET /api/strategies. When every such broker is connected again it is started again.
- A start or stop through
POST /api/strategies/:id/controlclears the auto-pause record, so a reconnect does not override it. - Only market data counts. A disconnected order connector does not pause anything: orders are refused by the broker status check with
Broker order connector disconnected. - Halted strategies are skipped.
MANUALhas no subscriptions when added and is never auto-paused. - A paused strategy still receives callbacks, as a stopped one does. Its own
on_stop()is what cancels its orders.
Position store¶
position_store makes positions survive a restart. Without it, positions live in memory and a restart starts every strategy flat, whatever it holds at the broker.
| Key | Type | Default | Notes |
|---|---|---|---|
position_store |
object | absent | Its presence turns the store on. |
path |
string | state/positions.dat |
Created with any missing directories. |
capacity |
integer | 1024 | Positions, one slot per strategy and instrument. An existing file grows if this is larger and never shrinks. At the default the file is about 1.8 MiB. |
The engine opens the store in initialize(), before any fill can be booked. If the file cannot be opened, because it is not a position store or was written with a different layout, startup stops. It is never overwritten.
What is stored for each position: quantity, average price, realized PnL, realized and open fees, the multiplier, the last update time and the open lots. What is not: marks, orders and anything a broker holds. The store knows what the engine booked. A fill that happened while the engine was down is booked after the restart only if the broker reports it again.
File format¶
All integers are little-endian as the host writes them. The layout is the format, with no checksum.
| Part | Size | Content |
|---|---|---|
| Header | 192 bytes | Magic SLKPOSN1, version (1), slot size, max lots (32), reserved, then journaled[16]: a uint64 per BrokerId |
| Slot | 1,816 bytes | state byte (0 empty, 1 or 2 names the current record), 7 reserved, strategy id (63 characters and NUL), instrument (63 and NUL), two records |
| Record | 840 bytes | quantity, avg_price, realized_pnl, realized_fees, open_fees (int64), multiplier (double), last_update_time, lot_count, journal_broker, journal_seq, then 32 lots of (quantity, price, timestamp) |
Crash safety¶
Recording a fill is a copy into mapped memory on the worker thread: no system call, no wait for the disk. A slot holds two copies of its position. An update writes the copy that is not current in full, then flips the state byte. A process that dies mid-update leaves the position as it was before the fill, never half of each.
A position recorded before the process is killed is in the file, because the operating system writes mapped pages out even when the process dies. The engine never calls PositionStore::flush(), so against a power loss or kernel crash that guarantee does not hold: the file is whatever the OS had written by then.
Replay of fills¶
A broker that journals its fills numbers each one (OrderFillEvent::journal_seq) and replays its journal at startup with replayed = true. The store keeps, per broker, how far the strategies have got: a mark in the header, and in each position the journal number of the fill it was last booked from. At startup the store takes the highest of those, so a process that died after booking and before marking is repaired. Then fill_handled() drops a replayed fill at or below the mark. A replayed fill above it is booked, once.
Without a store, every replayed fill is dropped, since positions began flat. A fill with journal_seq 0 is never dropped by this mechanism. The in-tree brokers do not journal, so for them the store protects positions that were booked and does not protect against a fill reported twice. The journal and its dedupe are described in Order lifecycle.
Limits¶
- A slot keeps 32 open lots. A position built from more keeps the oldest 31 as they are and the rest as one lot at their average price. FIFO closes the oldest first, so this matters once those are gone. The in-memory lots are not merged, so the position and the store differ until a restart.
- A strategy name or instrument over 63 characters cannot be kept. It is logged and the position lives in memory only.
- When the store is full, new positions are not kept (logged once, raise
capacity) and existing ones still update.
Starting flat¶
Stop the engine and delete the file. Nothing in the engine clears a store.