Skip to content

Order book

The matching engine and the messages it accepts and returns. Everything here is importable from microbook.

LimitOrderBook

LimitOrderBook(tick_size: float = 0.01, *, stp: STPMode = NONE)

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

price_of(tick: int) -> float

Float price of an integer tick, rounded to the grid's precision.

to_ticks

to_ticks(price: float) -> int

Integer tick of an on-grid price. Raises ValueError if off-grid.

round_price

round_price(price: float, side: Side) -> float

Round a price onto the grid passively: bids down, asks up.

best_bid

best_bid() -> float | None

Highest bid price, or None if there are no bids.

best_ask

best_ask() -> float | None

Lowest ask price, or None if there are no asks.

midprice

midprice() -> float | None

Average of the best bid and best ask, or None if either side is empty.

spread

spread() -> float | None

Best ask minus best bid, 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

top_of_book() -> dict[str, float | None]

Best bid, best ask and mid in one dict (None where undefined).

depth

depth(levels: int = 5) -> dict[str, list[tuple[float, int]]]

Aggregated L2 depth, best price first.

volume_at

volume_at(side: Side, price: float) -> int

Total resting quantity at price on side (0 if none or off the tick grid).

get_order

get_order(order_id: str) -> Order | None

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

queue_ahead(order_id: str) -> int | None

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

place_limit(order: Order) -> list[Fill]

Match a limit order and rest any remainder (subject to tif).

place_market

place_market(order: Order) -> list[Fill]

Execute order as a market order (its price is ignored); never rests.

cancel

cancel(order_id: str) -> bool

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

check_invariants() -> None

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.

order_id instance-attribute

order_id: str

Unique id. The book rejects an id that is already live.

side instance-attribute

side: Side

BUY or SELL.

price instance-attribute

price: float | None

Limit price, on the book's tick grid; None for market orders.

qty instance-attribute

qty: int

Open quantity. The book decrements it as the order trades.

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

order_type: OrderType = OrderType.LIMIT

LIMIT or MARKET.

tif class-attribute instance-attribute

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.

is_market property

is_market: bool

Whether this is a market order.

limit classmethod

limit(order_id: str, side: Side, price: float, qty: int, *, ts: int = 0, tif: TimeInForce = GTC, post_only: bool = False, owner: str | None = None) -> Order

A limit order (GTC unless tif says otherwise).

market classmethod

market(order_id: str, side: Side, qty: int, *, ts: int = 0, owner: str | None = None) -> Order

A market order: trades immediately against the book; any unfilled rest is cancelled.

Side

Bases: str, Enum

Side of an order or trade.

sign property

sign: int

+1 for BUY, -1 for SELL. Handy for signed quantities and PnL.

opposite property

opposite: Side

The other side.

OrderType

Bases: str, Enum

Limit or market order.

TimeInForce

Bases: str, Enum

How long an order's unfilled remainder stays on the book.

OrderStatus

Bases: str, Enum

Outcome of one order message, as reported in an ExecutionReport.

STPMode

Bases: str, Enum

Self-trade prevention: what happens when an order would trade with a resting order from the same owner.

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).

taker_order_id instance-attribute

taker_order_id: str

Id of the incoming (aggressing) order.

maker_order_id instance-attribute

maker_order_id: str

Id of the resting order it traded against.

price instance-attribute

price: float

Execution price: the resting order's price.

qty instance-attribute

qty: int

Shares traded.

aggressor_side class-attribute instance-attribute

aggressor_side: Side | None = None

Side of the taker; None for fills built outside the book.

ts class-attribute instance-attribute

ts: int = 0

Timestamp of the taker order (the simulator stamps orders with their arrival time).

ExecutionReport

Bases: NamedTuple

Outcome of a single message (submit or modify) sent to the book.

order_id instance-attribute

order_id: str

Id of the order the message was about.

status instance-attribute

status: OrderStatus

Status of the order after the message.

fills class-attribute instance-attribute

fills: tuple[Fill, ...] = ()

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

stp_canceled: tuple[str, ...] = ()

Ids of resting orders removed by self-trade prevention.

reason class-attribute instance-attribute

reason: str | None = None

Why the message was rejected; None unless status is REJECTED.

accepted property

accepted: bool

Whether the book accepted the message (status is not REJECTED).

filled_qty property

filled_qty: int

Shares filled by this message.

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.