Order book¶
The matching engine and the messages it accepts and returns. Everything here is importable from microbook.
LimitOrderBook
¶
Price-time priority limit order book.
Parameters:
-
tick_size(float, default:0.01) –Minimum price increment. Limit prices must lie on this grid.
-
stp(STPMode, default:NONE) –Self-trade prevention policy, applied when an incoming order would trade against a resting order with the same (non-
None)owner.
Order entry
submit(order) is the primary entry point and returns an
ExecutionReport; it never raises for business rejections.
place_limit / place_market are conveniences that return the list of
fills and raise OrderRejected if the book refuses the order.
price_of
¶
Float price of an integer tick, rounded to the grid's precision.
to_ticks
¶
Integer tick of an on-grid price. Raises ValueError if off-grid.
round_price
¶
Round a price onto the grid passively: bids down, asks up.
midprice
¶
midprice() -> float | None
Average of the best bid and best ask, or None if either side is empty.
microprice
¶
microprice() -> float | None
Size-weighted mid: leans toward the side with less resting size, i.e. toward where the price is more likely to move next.
top_of_book
¶
Best bid, best ask and mid in one dict (None where undefined).
depth
¶
Aggregated L2 depth, best price first.
volume_at
¶
Total resting quantity at price on side (0 if none or off the tick grid).
get_order
¶
The resting order with this id, or None if it is not on the book.
This is the book's own object: treat it as read-only.
queue_ahead
¶
Quantity resting ahead of order_id at its price level (O(queue)).
submit
¶
submit(order: Order) -> ExecutionReport
Process an order according to its order_type / tif / post_only.
place_limit
¶
Match a limit order and rest any remainder (subject to tif).
place_market
¶
Execute order as a market order (its price is ignored); never rests.
cancel
¶
Remove a resting order. Returns False if it is not on the book.
reduce
¶
reduce(order_id: str, qty: int) -> ExecutionReport
Partial cancel: remove qty shares from a resting order, keeping its priority.
Reducing by the whole open quantity or more cancels the order. Unlike
modify(new_qty=...) the amount is relative, so it is resolved against
the quantity resting when the message arrives (the semantics of an
exchange's cancel-by-size message, e.g. NASDAQ ITCH "order cancel").
modify
¶
modify(order_id: str, *, new_price: float | None = None, new_qty: int | None = None, ts: int | None = None) -> ExecutionReport
Amend a resting order with exchange-style priority semantics.
- same price and quantity reduced (or unchanged) -> amended in place, keeps priority
- price change or quantity increase -> loses priority (cancel/replace); a new price that crosses the spread trades immediately and the fills are returned in the report
new_qty == 0-> cancel
Invalid requests are REJECTED and leave the order untouched.
check_invariants
¶
Verify internal consistency; raises AssertionError on corruption.
O(n) — intended for tests and debugging, not the hot path.
Order
dataclass
¶
Order(order_id: str, side: Side, price: float | None, qty: int, ts: int = 0, order_type: OrderType = LIMIT, tif: TimeInForce = GTC, post_only: bool = False, owner: str | None = None)
An order message.
qty is the open quantity: the book decrements it as the order trades,
so after a submit it equals the quantity left resting (0 if none).
price is required for LIMIT orders and ignored for MARKET orders.
ts is informational (the simulator stamps it with the arrival time);
queue priority is determined by arrival order at the book, not by ts.
owner identifies the participant for self-trade prevention.
price
instance-attribute
¶
price: float | None
Limit price, on the book's tick grid; None for market orders.
ts
class-attribute
instance-attribute
¶
ts: int = 0
Informational timestamp. Queue priority comes from arrival order at the book.
order_type
class-attribute
instance-attribute
¶
LIMIT or MARKET.
tif
class-attribute
instance-attribute
¶
tif: TimeInForce = TimeInForce.GTC
Time in force: GTC rests the remainder, IOC cancels it, FOK fills completely or not at all.
post_only
class-attribute
instance-attribute
¶
post_only: bool = False
Reject the order instead of letting it take liquidity.
owner
class-attribute
instance-attribute
¶
owner: str | None = None
Participant id for self-trade prevention; None is never treated as a self-trade.
Side
¶
OrderStatus
¶
STPMode
¶
Fill
¶
Bases: NamedTuple
A single execution between an aggressing (taker) and a resting (maker) order.
Immutable record (a NamedTuple rather than a frozen dataclass: it is
created on the matching hot path, where frozen-dataclass construction costs
~2x more).
ExecutionReport
¶
Bases: NamedTuple
Outcome of a single message (submit or modify) sent to the book.
fills
class-attribute
instance-attribute
¶
Fills the message produced, in execution order.
resting_qty
class-attribute
instance-attribute
¶
resting_qty: int = 0
Quantity left on the book after the message.
canceled_qty
class-attribute
instance-attribute
¶
canceled_qty: int = 0
Quantity removed without trading (IOC or FOK remainder, unfilled market order, self-trade prevention).
stp_canceled
class-attribute
instance-attribute
¶
Ids of resting orders removed by self-trade prevention.
OrderRejected
¶
OrderRejected(report: ExecutionReport)
Bases: ValueError
Raised by the convenience entry points (place_limit/place_market)
when the book refuses an order. submit returns a REJECTED report instead.