ProjectsFlashbook

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.

Side project · Market microstructureRust · Python · Redis Pub/Sub · FastAPIGitHub repo
Live order book · Seed 42

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
Price formation
Last trade (stepped) Book midpoint
$100.95$98.53$96.10
Submit limit order
Order book depth (top 6 levels)Price · Qty · Cum
$97.88834
$97.73726
$97.48519
$97.38514
$97.0949
$97.0455
Spread $0.20Mid $96.94
$96.8455
$96.82510
$96.761020
$96.73525
Ledger & trade tapeExecutes at resting price
#14SELL$96.846
#14SELL$96.931
#14SELL$97.071
#14BUY$96.975
#14BUY$96.835
#13BUY$97.194
#13BUY$97.034
#13SELL$97.061
#13SELL$97.131
#13SELL$97.134
#13SELL$97.182
#12SELL$97.186
#12SELL$97.322
#12BUY$97.224

Live browser port of the Flashbook matching engine (seed 42, price-time FIFO).

Trading bots (8 active on this ticker)

Pause bot groups or scale order size

Order-size risk factor
CohortBehavior & signalInventoryRestingTradesRemaining cashNet P&L (realized + mark)Participation
Market maker2 agentsTwo-sided limit quotes ($0.10 target spread, ≤25% cash gate)Quoting symmetrically around BBO midpoint+6 sh2 ord (10 sh)26$19,352.83-$66.15 (-$58.18 real)
Momentum2 agents5-trade moving window; crosses spread when last trade diverges >$0.02Sell signal (-$0.09 vs 5-trade mean)-9 sh0 ord (0 sh)33$20,905.07+$31.71 (+$27.50 real)
Noise4 agents75% cycle activity, randomized ±0.5% limit interest around reference midUniform ±0.5% price band · ≤12% cash per order+3 sh8 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.

Price-time priority · BTreeMap + VecDeque

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.

Ask level · $100.10 FIFO queueResting depth: 12 sh
Order AAccepted · resting
Sell 5 @ $100.10 · t₁
Remaining5 / 5 sh
Order BAccepted · resting
Sell 7 @ $100.10 · t₂
Remaining7 / 7 sh
Incoming limit orderBuy 9 @ $100.10
Unfilled taker qtyNot submitted yet
Generated trades

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.

Processes & Redis channels

How a message moves across the stack

Simulation01
Python trading botsasyncio · 16 tasks

Market-maker, momentum, and noise tasks tracking cash, inventory, and BBO.

Gateway02
FastAPI + WebSocket hubPOST /api/v1/orders · WS

Checks incoming orders and bridges Redis Pub/Sub topics to browser sockets.

Messaging03
Redis Pub/Sub brokerorders:new · marketdata:*

Passes orders, Rust execution events, bot stats, and control messages.

Core matcher04
Rust matching engineTokio · rust_decimal

Holds per-symbol BTreeMap + VecDeque books and publishes fills + top-5 depth.

Browser05
Web dashboardLive book · controls

Shows depth snapshots, trade tape, bot P&L, and pause/reset/shock controls.

Active channelsPOST /api/v1/orders · orders:new

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

Wire payload
{ "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.