Order lifecycle¶
An order starts either as a POST /api/orders on the uWS thread or as a call to StrategyBase::submit_order from a strategy callback. Both end up in the same function. The order is checked, written to a shared queue, picked up by the connector of its broker, and answered by events that come back over the bus and fan out to every strategy and to the dashboard.
One order, end to end¶
sequenceDiagram
autonumber
participant C as Client
participant W as WebServer (uWS thread)
participant S as StrategyBase MANUAL (caller's thread)
participant R as RiskManager and BrokerStatusRegistry
participant Q as order_request_queue_
participant O as Order connector (order worker thread)
participant V as Venue
participant B as event_mux_
participant M as StrategyManager (worker thread)
participant P as PositionTracker (worker thread)
C->>W: POST /api/orders
W->>W: validate body, broker registered and order-ready
W->>S: submit_order(..., post_only = true)
S->>R: validate_order, order_unavailable_reason
R-->>S: pass, or a reason
S->>Q: publish NewOrderEvent (broker_id set)
S->>S: insert Order as PENDING_NEW
S-->>W: client_order_id
W-->>C: 202 Accepted (not an ack)
O->>Q: read(cursor), skip other brokers' requests
O->>V: REST or WebSocket order
V-->>O: accepted
O->>B: OrderAckEvent
B-->>M: read
M->>M: every strategy gets on_order_ack, the owner updates its Order
B-->>W: read by the uWS thread
W-->>C: order_update ack (WebSocket)
V-->>O: execution
O->>B: OrderFillEvent
B-->>M: read
M->>M: fill_handled? update mark, on_order_fill, fill_dispatched
M->>P: the owner books the fill (FIFO)
B-->>W: read by the uWS thread
W-->>C: order_update fill (WebSocket)
A strategy's path is the same from step 3, with the strategy's callback running on the worker thread instead of the uWS thread.
The HTTP answer is not an acknowledgement
202 means the request passed the local checks and was written to the queue. The broker's ack, fills, reject and cancel arrive only on the WebSocket (order_update messages) and in GET /api/orders and GET /api/fills. See WebSocket.
Entry points¶
POST /api/orders¶
The handler checks, in this order, and answers at the first failure:
| Check | Failure |
|---|---|
instrument, side, quantity and broker_id present, JSON parses |
400 |
broker_id is a number in BrokerId range and that broker was built into this engine |
400, with the list of brokers it has |
| The broker's order connector is enabled and connected | 503 |
time_in_force is 0 to 4 (default 0) |
400 |
side is buy, BUY, sell or SELL |
400 |
type is market (default) or limit, and a limit has price above 0 |
400 |
The MANUAL strategy exists |
404 |
submit_order accepts it (risk, broker status) |
422, Order rejected: <reason> |
Accepted orders get 202 and are seeded into the web server's own order map as PENDING_NEW. Orders go out with post_only = true always, so a limit order from the dashboard is post-only whatever its time in force (Hyperliquid sends it add-liquidity-only, Coinbase gets the flag on its REST call). Nothing in the handler or in RiskManager checks that quantity is positive.
Time-in-force values on the wire are 0 GTC, 1 IOC, 2 FOK, 3 GTD and 4 DAY.
From a strategy¶
std::string submit_order(std::string_view instrument, BrokerId broker_id, Side side, qty_t quantity,
OrderType type, price_t price = NULL_PRICE, TimeInForce tif = TimeInForce::FOK,
bool post_only = true, std::string* refusal = nullptr);
It returns the client order id, or an empty string when the order never left the engine. submit_order does not check is_running(), so a stopped, paused or halted strategy that calls it still reaches the risk check (a halted one is refused there, the others are not).
The defaults are FOK and post-only
A strategy that passes only the first six arguments sends a fill-or-kill order that is also flagged post-only. Hyperliquid's adapter lets post_only win and sends the order as add-liquidity-only whatever the time in force. Set both on purpose.
What submit_order does¶
- Builds the client order id as
<strategy name>_<steady-clock ns>. - For
CMEandICEorders, clearspost_only. Those venues have no such flag. - Remembers
instrument -> broker_id, whichclose_all_positions()later needs. - Calls
RiskManager::validate_order. On failure it builds anOrderRejectEventand calls the strategy's ownon_order_rejectdirectly, on the calling thread. Nothing goes on the bus, so the dashboard's WebSocket never sees it. The reason is returned throughrefusal. Checks are listed in Positions, PnL and risk. - Asks
BrokerStatusRegistry::order_unavailable_reason(broker_id):Broker order connector disabledorBroker order connector disconnected. A failure is turned into a local reject the same way as in step 4. - Publishes a
NewOrderEventtoorder_request_queue_. - Inserts an
Orderwith statusPENDING_NEWinto the strategy's map. This happens after the publish, so an ack can reach the worker first. It then finds no entry and creates one from the ack.
submit_order has no stop-price argument, so the request always carries stop_price = NULL_PRICE. A STOP, STOP_LIMIT or BRACKET order therefore goes out with no stop price: Hyperliquid's adapter then uses price as the trigger, and Coinbase's REST call is made without one.
The queue and the connector¶
Every order connector reads every record on order_request_queue_, each with its own cursor, and acts only on records whose broker_id is its own. The queue is lossy and has no backpressure. See Architecture.
Both in-tree connectors handle one request per loop pass on their order worker and call the venue synchronously. A slow REST call delays every request behind it for that broker. A request for a disabled broker is refused earlier by the status check.
| Coinbase | Hyperliquid | |
|---|---|---|
| Types | MARKET, LIMIT, STOP_LIMIT, STOP, BRACKET (REST create) |
MARKET (market open, 5% slippage), STOP and STOP_LIMIT (trigger order), LIMIT and BRACKET (limit) |
| TIF | GTC, GTD, IOC, FOK. DAY becomes a reject. |
IOC and FOK map to IOC, GTC and GTD to GTC. DAY becomes a reject. post_only overrides all of them with add-liquidity-only. |
| New order ack | PENDING_NEW after the REST call succeeds, then ACKNOWLEDGED from the user channel |
ACKNOWLEDGED when the order rests. An order that fills at once gets an ack with status FILLED plus a fill. |
| Fill source | User channel order updates: the increment is derived from the cumulative quantity and average price | userFills WebSocket |
| Fee on a fill | Incremental total_fees |
abs(fee) from userFills, 0 on an immediate REST fill |
| Journal | None | None |
Neither in-tree connector uses the fill journal, so their fills carry journal_seq = 0 (see Fill dedupe and the position store).
Events back¶
Connectors write OrderAckEvent, OrderFillEvent, OrderRejectEvent and OrderCancelEvent into their producer buffer. The StrategyManager worker reads them with everything else and calls dispatch_order_*, which hands the event to every strategy, MANUAL included. Each strategy keeps only what it owns. The web server reads the same records on its own cursor.
For a fill, the dispatcher first asks PositionTracker::fill_handled(). A handled fill is dropped. Otherwise it updates the instrument's mark to the fill price, calls on_order_fill on every strategy, and then calls fill_dispatched().
| Event | What StrategyBase does on the owner |
What the web server does |
|---|---|---|
| Ack | Creates the Order if untracked, otherwise updates broker order id, status, price, stop price, quantity, remaining quantity, TIF and post-only from the ack. Then on_ack. An ack with an empty client id is only passed to on_ack. |
Tracks the order (algo orders appear here at their first ack) and broadcasts if something changed. |
| Fill | Weighted-average fill price, filled and remaining quantity from the event, status FILLED when remaining is 0 else PARTIALLY_FILLED. Books the position by FillScope. Then on_fill. |
Updates remaining quantity. Removes the order when remaining is 0. Broadcasts and stores the fill in the last-1000 history. Skips replayed fills. |
| Reject | Sets status REJECTED. Then on_reject. |
Removes the order and broadcasts the reason. |
| Cancel | Sets status CANCELLED and remaining quantity. Then on_cancel. |
Removes the order. A cancel for an order it does not track is dropped. |
Strategy ownership¶
All order events reach all strategies, so ownership is decided by the client_order_id. StrategyBase::owns_order() says an event is mine when:
- the event's
client_order_idis one the strategy already tracks, or starts with<name>_followed by at least one more character, or - the id is empty and the broker
order_idwas recorded at ack time.
Foreign events are dropped before they can create an entry or book a position. An id that carries the prefix but is not tracked, as after a restart or a broker reconnect snapshot, is adopted.
Names must not be underscore-prefixes of each other
MM owns MM_fast_123456 because the id starts with MM_. If both MM and MM_fast exist, both claim every MM_fast order and MM books its fills. A strategy with its own id scheme must override generate_order_id() and owns_client_order_id() together.
Fill scopes¶
FillScope |
Meaning | Order moves | Position booked |
|---|---|---|---|
ORDER_AND_POSITION |
An ordinary fill. | Yes | Yes, in instrument |
ORDER |
A multi-leg order's fill at the order's own price. | Yes | No |
LEG |
One leg of that fill, with the leg's instrument, side, price and quantity. | No | Yes, in the leg's instrument. on_leg_fill is called. |
Fill dedupe and the position store¶
OrderFillEvent::journal_seq is the number a broker's journal gave the fill, or 0 for no journal. An adapter that journals replays the journal after a restart with replayed = true.
| Fill | fill_handled() |
|---|---|
journal_seq == 0 |
Never handled. It is always booked. |
| Replayed, no position store | Handled. Every replay is dropped, because positions started flat. |
| With a store, replayed or not | Handled when journal_seq is at or below the broker's recorded mark. |
fill_dispatched() raises the mark after every strategy had the fill, in memory and in the store. The store also records the journal number of the fill each position was last booked from, so a process that dies between booking and marking is repaired on the next start. More in Position store.
In-tree brokers have no dedupe
Coinbase and Hyperliquid fills carry journal_seq = 0. With position_store on, a restart restores positions, but nothing stops a connector that sees the same fill again from booking it a second time. Coinbase's per-order fill state lives in memory only, so an OPEN order with earlier partial fills, if the user channel snapshot after a restart includes it, is reported as one fill of its whole cumulative quantity. Hyperliquid's REST path publishes an immediate fill but never records a trade id in seen_fill_tids_, so nothing stops the userFills message for the same trade from being published as a second fill.
Hyperliquid fills always say 'nothing remains'
on_user_fill sets remaining_quantity = 0 and cumulative_filled to the fill's own size. StrategyBase takes remaining quantity from the event, so a partial fill of a resting Hyperliquid order marks it FILLED, and the web server drops it from its open orders.
Modify¶
PUT /api/orders/:strategy_id/:order_id takes client_order_id and at least one of new_price and new_quantity in the body. The handler needs the order to exist in that strategy's map (404 otherwise), fills the other value from the stored order, and calls modify_order. That publishes a ModifyOrderEvent to the order queue with the order's broker, side and instrument, the stored time-in-force and post-only, and new_stop_price = NULL_PRICE, then sets the order to PENDING_MODIFY and returns 202. There is no risk check and no broker status check on a modify, and the web server's tracked order does not change until the broker answers.
An accepted modify comes back as an ack with status ACKNOWLEDGED and the new price and quantity, which the owner copies into its Order. A refused modify comes back as an ORDER_REJECT that names the same order.
A rejected modify marks the live order REJECTED
on_order_reject sets the status of whatever order carries the client id, and the web server removes it from its open orders. A modify the venue refuses leaves the original order working at the broker, but the strategy then sees it as REJECTED (not open, so cancel_all_orders() skips it) and the dashboard no longer lists it.
Cancel¶
DELETE /api/orders/:strategy_id/:order_id takes client_order_id in the body. DELETE /api/orders/cancel-all calls cancel_all_orders() on every registered strategy, not only MANUAL.
cancel_order publishes a CancelOrderEvent addressed with the order's broker, instrument and side. It does not change the order's status. Nothing sets PENDING_CANCEL. The order stays ACKNOWLEDGED and tracked until a connector publishes ORDER_CANCEL. A cancel can fail without any event (a Coinbase network exception, a Hyperliquid refusal), and then the order stays where it was.
cancel_all_orders() cancels orders that are open or PENDING_MODIFY and already have a broker order id. An order still waiting for its first ack is skipped. Orders are cancelled by the strategy's own on_stop() in the shipped strategies, so a stop, an auto-pause and a loss halt all cancel them. See Positions, PnL and risk for the halt path.
Status values¶
OrderStatus has eight values. This is where each is actually set.
| Status | Set by | Notes |
|---|---|---|
PENDING_NEW |
submit_order and close_all_positions when they insert the local Order. Coinbase's REST ack and its user channel PENDING and QUEUED. The web server's seed entry. |
|
PENDING_MODIFY |
modify_order, locally. |
Not sent to the web server. Replaced by the next ack's status. |
PENDING_CANCEL |
A broker adapter, in an ack. | Nothing in the engine or the two in-tree adapters sets it. Order::is_open() does not count it, so cancel_all_orders() skips such an order. |
ACKNOWLEDGED |
Coinbase OPEN and a successful modify. Hyperliquid for a resting order and a successful modify. |
The default of OrderAckEvent. |
PARTIALLY_FILLED |
StrategyBase::on_order_fill, when remaining quantity is above 0. |
|
FILLED |
StrategyBase::on_order_fill, when remaining is 0. Hyperliquid's ack for an immediate fill. |
|
CANCELLED |
StrategyBase::on_order_cancel. |
Also used for expired orders on Coinbase. |
REJECTED |
StrategyBase::on_order_reject. |
Also what a refused modify does. See above. |
The web server shows the ack's status string, then FILLED or PARTIALLY_FILLED from fills. It has no PENDING_MODIFY or PENDING_CANCEL.
A strategy's Order map is never pruned by the engine. Done orders stay until the strategy calls prune_done_orders().