Quant Memo
Coding/●●●●●

Design a limit order book / matching engine

Asked at Citadel, Jump Trading, HRT

Design a single-instrument matching engine supporting:

  • limit_order(side, price, qty), submit a buy or sell; it matches immediately against the opposite side at prices as good or better (price-time priority), and any unfilled remainder rests in the book. Return the new order id and the list of trades it generated.
  • cancel(order_id), remove a resting order.
  • best_bid() / best_ask(), the top of each book, or None.
b1 = ob.limit_order("sell", 101, 5)   # rests: ask 101 x5
b2 = ob.limit_order("sell", 102, 5)   # rests: ask 102 x5
ob.limit_order("buy", 103, 8)         # trades 5@101, 3@102; 0 remainder
ob.best_ask()  -> 102                 # 102 has 2 left

Every operation should be O(logn)O(\log n) amortized.

Show a hint

Buys want the lowest ask, sells want the highest bid, that's two heaps (min-heap of asks, max-heap of bids). The hard part is cancellation: you can't delete from the middle of a heap cheaply. How can you mark an order dead and skip it lazily?

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions