Quant research & trading·Python·Published
Limit Order Book Simulator
I wanted to understand what actually happens between the touch and the fill, so this is a price-time-priority limit order book with synthetic order flow and a microstructure study on top of it. Bids and asks are stored as price to FIFO deque mappings, which is what makes time priority fall out of the data structure instead of needing a sort. A resting limit order that crosses the touch executes immediately against the best opposite level with the remainder resting, a market order sweeps level by level until filled or the book empties, cancel removes a resting order, and queue_position returns the position in the level plus the quantity ahead with 1 meaning front of queue. On top of the book it computes spread, midprice, book imbalance as (B_L - A_L) / (B_L + A_L) in [-1, 1], a quantity-weighted microprice, signed order flow, and a forward-return study bucketed by imbalance sign. The CLI simulates seeded flow at 45% limit bids, 45% limit asks, 7% market orders and 3% cancels against a pre-seeded 10-deep book, prints the study and saves a matplotlib chart. The 16 tests cover matching, price and time priority, FIFO ordering, queue-ahead accounting, cancels, partial sweeps, invalid quantities, microprice tilt and simulation determinism.



- Storing each price level as a FIFO deque makes time priority a property of the data structure, so there is no timestamp sort to get wrong and no tie-breaking rule to invent.
- Queue position is the number that matters for a resting maker order and it is not derivable from the book snapshot alone; you have to track quantity ahead per order, which is why the engine keeps it explicitly.
- Book imbalance and microprice are related but not redundant: imbalance is a level-count ratio while microprice weights by quantity, and the forward-return study only shows a signal when the quantity weighting is included.
Scale 0–100: how much this project relied on each skill.