Implement a simplified limit-order matching engine for a stock exchange.
You receive a stream of orders. Each order has:
-
order_id
: unique identifier
-
side
:
BUY
or
SELL
-
price
: limit price
-
quantity
: positive integer share quantity
-
timestamp
: arrival time, or an equivalent sequence number
Matching rules:
-
A buy order can match a resting sell order when the buy price is greater than or equal to the sell price.
-
A sell order can match a resting buy order when the sell price is less than or equal to the buy price.
-
Among eligible resting orders, match by best price first: highest bid for buys, lowest ask for sells.
-
If multiple resting orders have the same price, match the earliest order first.
-
A trade quantity is the minimum of the incoming order's remaining quantity and the resting order's remaining quantity.
-
Partially filled orders keep their remaining quantity. Fully filled orders leave the book. Any unfilled remainder of the incoming order is added to the book.
Implement an API such as add_order(order) that processes one order and returns the trades generated by that order. Each trade should include the buy order id, sell order id, execution price, and executed quantity. Also maintain the current order book state so that future orders can match against it.
Discuss the data structures you would use and handle partial fills, price-time tie breaking, heap updates, and order ids correctly.