← 返回 twosigma 的题目列表Order Matching Engine
类型:qbank
Implement a simplified stock exchange that matches buy and sell orders by price-time priority, handles partial fills, and maintains an order book.
Requirements
Implement a simplified trading matching system. Orders include side, price, quantity, and either timestamp or order id.
Core behavior:
Buy side uses highest bid first.
Sell side uses lowest ask first.
At the same price, earlier orders have priority.
Repeatedly compare best bid and best ask; if best_bid >= best_ask, execute a trade.
Trade quantity is min(buy_remaining, sell_remaining).
Partially filled orders keep their remaining quantity in the book.
Return executed trades or maintain queryable order-book state, depending on prompt shape.
Notes
A max-heap for buys and min-heap for sells is the standard implementation. Include timestamp / sequence as the secondary key.
One follow-up changes order id semantics: order numbers may be out of order, but matching must still follow arrival time. Use an internal monotonic sequence rather than sorting by id.
The details that consume time are partial fill, tie-breakers, heap updates, remaining quantity, and deterministic trade output.
Preparation
Implement a minimal price-time priority book in 30 minutes: add_order, match loop, and trade log.
Write tests for crossed book, equal price but different arrival time, partial fill on both sides, and leftover resting quantity.
Practice narrating the matching invariant before coding: the top of each heap must always represent the next executable order on that side.