System Design — Limit Order Book
The heart of an exchange: buyers and sellers post limit orders, and the engine matches them
by price-time priority.
solve(args, ops) builds new OrderBook() and replays ops:
submit(id, side, price, qty)—sideis"buy"or"sell",idis unique. The new order
(the taker) is matched against the opposite side while it can trade:
- a buy trades with the lowest-priced asks priced `<=` its limit; a sell trades with
the highest-priced bids priced `>=` its limit;
- among resting orders at the same price, the one submitted first trades first;
- each trade is [takerId, makerId, price, qty] where price is the **resting (maker)
order's price** and qty is the smaller of the two remaining quantities;
- whatever quantity is left after matching rests in the book at the taker's limit price.
Returns the list of trades, in the order they happened ([] if none).
cancel(id)— remove a resting order. Returnstrueif it was resting, elsefalse.depth(side)— the resting quantity per price level on that side as[price, totalQty]
pairs, best price first (highest first for "buy", lowest first for "sell").
Example
submit(1,"sell",101,5) submit(2,"sell",100,3) depth("sell") → [[100,3],[101,5]]
submit(3,"buy",100,2) → [[3,2,100,2]] depth("sell") → [[100,1],[101,5]]
submit(4,"buy",101,10) → [[4,2,100,1],[4,1,101,5]] // 4 units are left and rest as a bid at 101Sample tests