price-time priority · python 3.12+ · mypy --strict

A matching engine that tells you
what it actually did.

Deterministic down to queue position. Durable through a process killed mid-write. Exact in integer ticks and lots. Every number on this page was measured, not estimated.

~206k
cmd/s sustained
3.1 µs
p50 latency
O(1)
add / cancel
100%
acked orders survive a kill -9
why it's built this way

Four guarantees, not four adjectives

Each one is backed by a specific test suite, not a claim in a README.

D

Deterministic

No clock or randomness inside the engine. The same log always rebuilds the same book, down to queue position, checked by a state hash.

D

Durable

Checksummed, length-framed WAL with group commit. Torn writes are detected and cut off; corruption is refused; snapshots bound replay time.

E

Exact

Integer ticks and lots from the gateway inwards. Decimals only on the wire, as strings — never a float near a price.

T

Tested like it fails

Golden files, property-based invariants, replay determinism, and a real process killed mid-load — not just unit tests.

architecture

One worker per market, nothing shared

Each market owns its own sequencer, WAL, snapshots and book. Orders are acknowledged only after they are on disk.

Client
→
Gateway (FastAPI)
→
Sequencer
→
WAL · group commit
→
Engine
→
Events → caller + WS feed
order book

Price levels in a SortedList, orders in a linked list

Bid keys are negated prices, so on both sides keys[0] is the best level and "crosses the limit" is one comparison.

OperationComplexity
Add at an existing price levelO(1)
Add at a new price levelO(log L)
Cancel (level stays non-empty)O(1)
Cancel (last order at its level)O(log L)
Best bid / askO(1)
Fill against the head of the best levelO(1) per fill
L2 depth, top n levelsO(n)
FOK fillability checkO(levels crossed), no mutation
order types & rules

Every command produces an ordered event list

order_accepted, trade, order_cancelled (reason user, unfilled or self_trade), order_replaced, order_triggered, order_rejected — each carrying the command's seq and ts.

FeatureBehaviour
LimitMatches at the resting price; the remainder rests if GTC
MarketSweeps the book; must be IOC or FOK — no price to rest at
GTC / IOC / FOKRest / cancel unfilled / fill completely or reject with no trades
Post-onlyRejected if it would take liquidity; must be GTC
Self-trade preventioncancel_taker (default), cancel_maker, cancel_both, or none
Stop / stop-limitstop_price parks the order off-book until the last trade price reaches it; cancellable while parked (ADR 5)
AmendPATCH a resting order's price and remaining size; shrinking at the same price keeps queue position, anything else re-queues
CancelOwner only; cancelling a filled or unknown order is rejected
measured, not estimated

Benchmarks

Windows 11, i7-7700HQ (4c/8t laptop), 32 GB RAM, SATA SSD, CPython 3.14.7. Every figure is the median of several runs.

Engine, in-process

1M commands · 189,443 trades · 411,172 orders resting

Throughput185k–242k cmd/s
Latency p503.1–4.6 µs
Latency p9921.5–26.6 µs
Latency p99.945.1–104.4 µs

End to end over HTTP

Real uvicorn + httptools, 64 connections, 4 client processes

fsync on · p503.8 ms
fsync off · p501.9 ms
fsync on · throughput894 orders/s
fsync off · throughput1,320 orders/s
tested the way it can fail

Not just unit tests

make check runs ruff, ruff format --check, mypy --strict and pytest together.

Golden & property tests

Exact event streams for partial fills, level sweeps, time priority, IOC/FOK remainders, cancel rejections, post-only and all three STP modes. Hypothesis then throws random flows at the book and checks it is never crossed, every lot is accounted for, and no fill beats the taker's limit.

Recovery & crash tests

The same WAL replayed twice gives the same state hash. A truncated or corrupted last record is detected and repaired. A real writer process is killed (SIGKILL / TerminateProcess) mid-load, and every acknowledged sequence number still comes back.

try it now

Quickstart

No account needed. One process, one port, OpenAPI docs included.

# install & serve
uv sync --all-extras
uv run matching-engine serve            # http://127.0.0.1:8000/docs

# rest a sell, then take part of it with a market buy
curl -s localhost:8000/markets/BTC-USDT/orders -H 'content-type: application/json' \
  -d '{"account": 2, "side": "sell", "price": "64000.50", "quantity": "0.5"}'
curl -s localhost:8000/markets/BTC-USDT/orders -H 'content-type: application/json' \
  -d '{"account": 1, "side": "buy", "type": "market", "quantity": "0.2"}'

curl -s localhost:8000/markets/BTC-USDT/depth        # L2
# live feed: ws://localhost:8000/markets/BTC-USDT/ws

Or with Docker: docker compose up --build. State lives in the engine-data volume. To inspect a market's files after a crash without changing them: uv run matching-engine verify data/BTC-USDT.

configuration

Environment variables

Every knob that changes durability, throughput or memory behaviour, with its default.

VariableDefaultMeaning
ME_DATA_DIRdataOne subdirectory per market: wal/, snapshots/
ME_MARKETSBTC-USDT:0.01:0.00001, …SYMBOL:TICK:LOT, comma-separated
ME_FSYNC10 leaves flushing to the OS
ME_BATCH_MAX512Commands per group commit
ME_QUEUE_MAX10000Pending commands per market before 503
ME_SNAPSHOT_EVERY100000Commands between checkpoints
ME_DEPTH_LEVELS20L2 levels pushed over WebSocket
ME_SUBSCRIBER_QUEUE1000Messages buffered per subscriber before it's dropped
what's next

Roadmap

The engine boundary (process, export_state, restore, state_hash) is drawn so the next step is a swap, not a rewrite.

Rust core via PyO3

Same boundary, published numbers side by side. The golden, property and replay suites become the acceptance tests.

A process per market

Fed over a ring buffer or shared-memory queue, so markets stop sharing one GIL.

Client order ids

Idempotent retries after a timeout, plus stop / stop-limit orders and amend with defined priority rules.

Replication & ledger hooks

Acknowledge once a follower has the WAL record; hold funds before sequencing and settle on trade events.

Known today: no auth, risk checks or balances — the account field is trusted as sent. See SECURITY.md.