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.
Four guarantees, not four adjectives
Each one is backed by a specific test suite, not a claim in a README.
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.
Durable
Checksummed, length-framed WAL with group commit. Torn writes are detected and cut off; corruption is refused; snapshots bound replay time.
Exact
Integer ticks and lots from the gateway inwards. Decimals only on the wire, as strings — never a float near a price.
Tested like it fails
Golden files, property-based invariants, replay determinism, and a real process killed mid-load — not just unit tests.
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.
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.
| Operation | Complexity |
|---|---|
| Add at an existing price level | O(1) |
| Add at a new price level | O(log L) |
| Cancel (level stays non-empty) | O(1) |
| Cancel (last order at its level) | O(log L) |
| Best bid / ask | O(1) |
| Fill against the head of the best level | O(1) per fill |
| L2 depth, top n levels | O(n) |
| FOK fillability check | O(levels crossed), no mutation |
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.
| Feature | Behaviour |
|---|---|
| Limit | Matches at the resting price; the remainder rests if GTC |
| Market | Sweeps the book; must be IOC or FOK — no price to rest at |
| GTC / IOC / FOK | Rest / cancel unfilled / fill completely or reject with no trades |
| Post-only | Rejected if it would take liquidity; must be GTC |
| Self-trade prevention | cancel_taker (default), cancel_maker, cancel_both, or none |
| Stop / stop-limit | stop_price parks the order off-book until the last trade price reaches it; cancellable while parked (ADR 5) |
| Amend | PATCH a resting order's price and remaining size; shrinking at the same price keeps queue position, anything else re-queues |
| Cancel | Owner only; cancelling a filled or unknown order is rejected |
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
End to end over HTTP
Real uvicorn + httptools, 64 connections, 4 client processes
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.
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.
Environment variables
Every knob that changes durability, throughput or memory behaviour, with its default.
| Variable | Default | Meaning |
|---|---|---|
ME_DATA_DIR | data | One subdirectory per market: wal/, snapshots/ |
ME_MARKETS | BTC-USDT:0.01:0.00001, … | SYMBOL:TICK:LOT, comma-separated |
ME_FSYNC | 1 | 0 leaves flushing to the OS |
ME_BATCH_MAX | 512 | Commands per group commit |
ME_QUEUE_MAX | 10000 | Pending commands per market before 503 |
ME_SNAPSHOT_EVERY | 100000 | Commands between checkpoints |
ME_DEPTH_LEVELS | 20 | L2 levels pushed over WebSocket |
ME_SUBSCRIBER_QUEUE | 1000 | Messages buffered per subscriber before it's dropped |
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.