Matching engine¶
LimitOrderBook is a central limit order book with
price-time priority: an incoming order trades against the best opposite
price first, and within a price level against the order that arrived first.
Every trade happens at the resting order's price.
Prices and the tick grid¶
A book has a fixed tick_size (default 0.01). Internally every price is an
integer number of ticks, so two prices that should be equal always are, and a
price off the grid is rejected rather than silently rounded.
round_price() snaps a price onto the
grid passively (bids down, asks up), and
to_ticks() /
price_of() convert between prices and ticks.
Messages¶
| Message | What happens |
|---|---|
LIMIT GTC |
trades while it crosses the opposite side, then the remainder rests |
LIMIT IOC |
trades while it crosses, then the remainder is cancelled |
LIMIT FOK |
fills completely or does nothing; checked before any trade, so a failed FOK has no side effects |
MARKET |
sweeps the opposite side and never rests |
post_only |
rejected if it would take liquidity |
modify, smaller size at the same price |
amended in place; keeps its queue position |
modify, new price or larger size |
loses priority (cancel and replace); a reprice that crosses trades at once and returns its fills |
reduce(order_id, qty) |
cancels part of an order; keeps its queue position |
cancel(order_id) |
removes the order; returns whether it was live |
| invalid input | duplicate live id, off-grid price, bad modify: REJECTED, book untouched |
Orders are built with Order.limit() and
Order.market(). qty is the open quantity: the book
decrements it as the order trades.
Execution reports¶
submit(),
modify() and
reduce() return an
ExecutionReport, in the spirit of a FIX execution
report: the order's new status, its fills, the quantity left resting, the
quantity cancelled, and the reason for a rejection. These methods never raise for
a business rejection (a bad price, a duplicate id, a post-only order that would
cross), so a simulation keeps running. If you prefer exceptions,
place_limit() and
place_market() return the fills and
raise OrderRejected instead.
from microbook import LimitOrderBook, Order, Side, TimeInForce
lob = LimitOrderBook(tick_size=0.01)
lob.submit(Order.limit("a", Side.SELL, 100.05, 10))
lob.submit(Order.limit("b", Side.SELL, 100.05, 10))
# Reducing "a" keeps its place at the front of the queue ...
lob.modify("a", new_qty=4)
fills = lob.submit(Order.market("m1", Side.BUY, 6)).fills
print([(f.maker_order_id, f.qty) for f in fills])
# [('a', 4), ('b', 2)]
# ... while a post-only order that would cross is rejected, with a reason.
report = lob.submit(Order.limit("p", Side.BUY, 100.05, 1, post_only=True))
print(report.status, report.reason)
# OrderStatus.REJECTED post-only order would cross
# A fill-or-kill order larger than the available size does nothing.
report = lob.submit(Order.limit("f", Side.BUY, 100.05, 50, tif=TimeInForce.FOK))
print(report.status, report.filled_qty, report.canceled_qty)
# OrderStatus.CANCELED 0 50
# Off-grid prices and duplicate ids are rejected; the book is untouched.
print(lob.submit(Order.limit("x", Side.BUY, 100.004, 1)).reason)
# price not on tick grid
print(lob.depth())
# {'bids': [], 'asks': [(100.05, 8)]}
Self-trade prevention¶
An order's owner identifies the participant. When an incoming order would trade
against a resting order with the same owner, the book's
STPMode decides what happens:
| Mode | Effect |
|---|---|
NONE |
the orders trade (wash trades are allowed) |
CANCEL_RESTING |
the resting order is cancelled and matching continues |
CANCEL_INCOMING |
the rest of the incoming order is cancelled |
Orders without an owner never count as self-trades. The simulator fills in each
strategy's name as the owner and uses CANCEL_RESTING, so no participant can
trade with itself. Cancelled resting orders are listed in the report's
stp_canceled.
Reading the book¶
| Method | Returns |
|---|---|
best_bid(), best_ask() |
the best prices, or None if that side is empty |
midprice(), spread() |
the mid and the spread, or None if a side is empty |
microprice() |
the size-weighted mid, which leans toward the side with less resting size |
top_of_book() |
best bid, best ask and mid as a dict |
depth(levels) |
{"bids": [(price, qty), ...], "asks": [...]}, best first |
volume_at(side, price) |
the total resting size at one price |
get_order(order_id) |
the live order, or None |
queue_ahead(order_id) |
the size resting ahead of an order at its price |
Data structures¶
Each side keeps a sorted list of the price levels in use, with the best price at the end, so reading or removing the touch costs O(1). Each level is an ordered dictionary of orders, which gives FIFO order and O(1) removal by id, plus a running total of its size. A cancel is O(1); a new price level is a binary search plus a list insert.
check_invariants() verifies the
whole structure (sorted levels, consistent sizes, no crossed book) and is cheap
enough to call after every message in tests.
How it is tested¶
tests/test_book_model.py drives long random sequences of submits, cancels,
modifies, reductions and duplicate submits through the engine and through a
deliberately naive reference book (a flat list, re-sorted on every message), under
all three self-trade modes. After every message the two must agree exactly on
fills, statuses and depth, and check_invariants() must pass. Planting a FIFO
violation, an off-by-one in the crossing test or a stale size cache makes the
test fail.
For throughput figures and the optional compiled build, see the native build.