Flashbook
A limit order book and multi-agent market simulator I built in Rust and Python to see how matching queues and competing trading bots form a live price.
Submit limit orders or shock the book
Prices, depth bars, fills, and bot P&L all run off one order book in your browser.
- Instrument
- ABCCycle #14
- Best bid
- $96.845 sh
- Best ask
- $97.045 sh
- Bid-ask spread
- $0.20Mid $96.94
- Last traded
- $96.8454 executions
- Session volume
- 189 shTop-5 depth: 25B / 26A
Pause bot groups or scale order size
| Cohort | Behavior & signal | Inventory | Resting | Trades | Remaining cash | Net P&L (realized + mark) | Participation |
|---|---|---|---|---|---|---|---|
| Market maker2 agents | Two-sided limit quotes ($0.10 target spread, ≤25% cash gate)Quoting symmetrically around BBO midpoint | +6 sh | 2 ord (10 sh) | 26 | $19,352.83 | -$66.15 (-$58.18 real) | |
| Momentum2 agents | 5-trade moving window; crosses spread when last trade diverges >$0.02Sell signal (-$0.09 vs 5-trade mean) | -9 sh | 0 ord (0 sh) | 33 | $20,905.07 | +$31.71 (+$27.50 real) | |
| Noise4 agents | 75% cycle activity, randomized ±0.5% limit interest around reference midUniform ±0.5% price band · ≤12% cash per order | +3 sh | 8 ord (49 sh) | 49 | $39,742.10 | +$30.65 (+$40.69 real) |
How the book
matches orders
After working on order routing and OMS workflows at Clearpool, I wanted to build the exchange side of the wire myself. Once an order reaches a venue, something has to rank price levels, drain queues in arrival order, and broadcast fills without drifting out of sync.
In the Rust engine, each ticker has two BTreeMap ladders (bids sorted high to low, asks low to high) keyed by rust_decimal::Decimal prices so $0.01 ticks never hit floating-point rounding bugs. Each price level points to a VecDeque<Order> for arrival order.
When a new limit order crosses the spread, the matcher walks resting levels from best price outward and drains each queue front to back. Fills always print at the resting order's price: send a buy at $200.00 into asks sitting at $100.05 and you fill at $100.05 until those asks run out, then any leftover shares sit on the bid side at $200.00.
Walking a 9-share buy through $100.10
Two sell orders rest at $100.10. Order A arrived before Order B.
Inside the asks BTreeMap, the $100.10 key points to a FIFO VecDeque. Order A (5 sh) sits at the front of the queue; Order B (7 sh) waits behind it, giving 12 shares of total ask depth at $100.10.
No trades emitted at this step.
Sixteen bots in
the same book
An empty order book isn't much fun to stare at on its own, so I wrote an async Python simulator that runs sixteen bots across two tickers (ABC near $100 and XYZ near $50).
Every bot starts with $10,000 in cash and a 1,000-share inventory limit, reading the same BBO and trade feeds as the browser UI. Per ticker, two market makers quote both sides around mid, two momentum bots watch a five-trade moving average and cross the spread on breakouts, and four noise traders drop random limit orders within 0.5% of mid.
Hitting a +/-5% shock wipes resting orders off both sides of the book and moves the reference price bots quote around. The last-trade line stays put until two orders actually cross at the new level.
Redis between the
matcher and the UI
The Rust process knows nothing about HTTP, browsers, or how many Python bots are running. Everything talks over Redis Pub/Sub: orders enter on orders:new, Rust updates the book and publishes fills, BBO updates, and top-five depth, and a FastAPI server forwards those feeds over WebSockets.
Manual orders from the browser hit the exact same FastAPI route and Redis channel as the Python bots, so your orders don't get any special path inside the matcher.
How a message moves across the stack
asyncio · 16 tasksMarket-maker, momentum, and noise tasks tracking cash, inventory, and BBO.
POST /api/v1/orders · WSChecks incoming orders and bridges Redis Pub/Sub topics to browser sockets.
orders:new · marketdata:*Passes orders, Rust execution events, bot stats, and control messages.
Tokio · rust_decimalHolds per-symbol BTreeMap + VecDeque books and publishes fills + top-5 depth.
Live book · controlsShows depth snapshots, trade tape, bot P&L, and pause/reset/shock controls.
POST /api/v1/orders · orders:newPython bots send JSON limit orders to FastAPI, which checks Decimal price and integer quantity with Pydantic and publishes to Redis channel orders:new for the Rust subscriber.
{ "symbol": "ABC", "side": "buy", "price": "100.05", "quantity": 16, "status": "new" }Bugs I hit and
shortcuts I took
The matching loop itself came together pretty fast. Most of the annoying bugs came from async state lag: when a Python bot fires orders over Pub/Sub, its local cash and inventory numbers trail behind the Rust book until fill events come back, so fast loops will happily spend the same cash three times if you don't reserve buying power up front. I also shot myself in the foot deriving PartialEq on BBO snapshots that included a timestamp field, which made every check look changed and spammed duplicate broadcasts.
There are real shortcuts here compared to a production venue. It only handles limit orders; OrderStatus has a Cancelled enum variant, but I never built a secondary order-ID hash map for O(1) single-order cancels, just full-book wipes on reset and shock. Books also sit behind an async Tokio mutex instead of a pinned single-threaded loop with an event log on disk.