Design an order book matching engine with limit orders, market orders and cancels

Quick Overview

Design the core of a stock order book that matches limit and market orders under price-time priority and supports cancellations and best bid and ask queries. It tests how you organize each side of the book for fast best-price access, handle cancels and partial fills, record trades in order, and state the real cost of each operation.

Design an order book matching engine with limit orders, market orders and cancels

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design the core data structure for a stock order book (matching engine) that supports limit orders, market orders and order cancellations. The engine must follow price-time priority: buy orders are matched at the highest price first, sell orders at the lowest price first, and among orders at the same price, earlier orders are matched first. A limit order specifies a price and quantity. A buy limit order matches against existing sell orders priced at or below its limit price. A sell limit order matches against existing buy orders priced at or above its limit price. Any unmatched quantity rests on the book. A market order specifies only a quantity and matches immediately against the best available orders on the opposite side. If there is insufficient liquidity, the remaining quantity is discarded. Each trade execution is recorded. Trades are returned as strings in the format `"buyOrderId,sellOrderId,price,quantity"`. Implement the following methods: - `placeOrder(orderId: int, side: str, orderType: str, price: int, quantity: int)`: place an order on the book. `side` is `"buy"` or `"sell"`. `orderType` is `"limit"` or `"market"`. For market orders, `price` is 0 and ignored. The engine matches the incoming order against resting orders on the opposite side using price-time priority. Unmatched quantity of a limit order rests on the book; unmatched quantity of a market order is discarded. - `cancelOrder(orderId: int)`: cancel an existing order by its ID. If the order does not exist, was already fully filled, or was already cancelled, this operation has no effect. - `getExecutedTrades() -> List[str]`: return all trades executed so far, in the order they occurred, each in the format `"buyOrderId,sellOrderId,price,quantity"`. - `getOrderQuantity(orderId: int) -> int`: return the remaining quantity of the given order on the book. Return 0 if the order does not exist, was fully filled, or was cancelled. - `getBestBid() -> int`: return the highest buy price currently on the book, or -1 if there are no active buy orders. - `getBestAsk() -> int`: return the lowest sell price currently on the book, or -1 if there are no active sell orders. For example: ```text placeOrder(1, "sell", "limit", 101, 5) placeOrder(2, "sell", "limit", 100, 3) placeOrder(3, "sell", "limit", 100, 4) placeOrder(4, "buy", "limit", 99, 2) getBestBid() -> 99 getBestAsk() -> 100 placeOrder(5, "buy", "limit", 101, 9) getOrderQuantity(1) -> 3 getOrderQuantity(5) -> 0 cancelOrder(1) getBestAsk() -> -1 placeOrder(6, "sell", "market", 0, 5) getBestBid() -> -1 getExecutedTrades() -> ["5,2,100,3", "5,3,100,4", "5,1,101,2", "4,6,99,2"] ``` Order 4 rests because the best ask (100) is above its limit of 99. Order 5 takes 3 from order 2 and then 4 from order 3 at 100 (order 2 arrived first at that price), then 2 of order 1's 5 at 101, so none of it rests. After order 1 is cancelled the sell side is empty. Market order 6 fills 2 against order 4 at 99 and its other 3 are discarded. ```hint Ordering each side Each side needs fast access to its best order, ranked by price first and arrival second. Work out one sort key per side that encodes both, and how orders at the same price are told apart. ``` ```hint Cancels Removing an arbitrary order from the middle of a priority queue is expensive. Think about what you could record at cancel time so that the matching loop and the best-price queries can recognize that order later and skip it. ``` ### Constraints & Assumptions - `1 <= orderId <= 10^6`, and all order IDs are unique across all `placeOrder` calls. - `1 <= price <= 10^6` for limit orders. Market orders pass `price = 0`, which is ignored. - `1 <= quantity <= 10^6`. - `side` is either `"buy"` or `"sell"`, and `orderType` is either `"limit"` or `"market"`. - At most `10^4` total operations. - A trade executes at the resting order's price, as in the example. The buy order's ID comes first in the trade string no matter which side arrived last. ### Clarifying Questions to Ask - When an incoming limit order crosses the spread, does the trade print at the resting order's price or at the incoming order's limit? - Is this a single-symbol, single-threaded engine, or can calls arrive concurrently? - Can a partially filled order be cancelled, and does that remove only its remaining quantity while the earlier trades stand? - Will later requirements add depth queries (total quantity per price level) or order modification? That affects which structure fits best. ### What a Strong Answer Covers - The structure used for each side of the book and how its ordering encodes price-time priority. - How cancellation works without scanning the book, and how cancelled or filled orders are kept out of matching and out of the best-price queries. - The matching loop for limit and market orders: the stop condition, partial fills on both sides, and what happens to leftover quantity. - How trades are recorded: the execution price, the buy-then-sell ID order, and chronological order. - A correct cost for each operation, including an incoming order that sweeps many resting orders. ### Follow-up Questions - How would you return the total resting quantity at a given price, or the top five price levels on each side? - How would you support changing an order's price or quantity, and which changes should keep its place in the queue? - If cancels made up most of the traffic and the book held millions of orders, what would you change? - How would you run the engine for many symbols and rebuild its state after a crash?

Overview: Design the core of a stock order book that matches limit and market orders under price-time priority and supports cancellations and best bid and ask queries. It tests how you organize each side of the book for fast best-price access, handle cancels and partial fills, record trades in order, and state the real cost of each operation.

Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design the core data structure for a stock order book (matching engine) that supports limit orders, market orders and order cancellations.

The engine must follow price-time priority: buy orders are matched at the highest price first, sell orders at the lowest price first, and among orders at the same price, earlier orders are matched first.

A limit order specifies a price and quantity. A buy limit order matches against existing sell orders priced at or below its limit price. A sell limit order matches against existing buy orders priced at or above its limit price. Any unmatched quantity rests on the book. A market order specifies only a quantity and matches immediately against the best available orders on the opposite side. If there is insufficient liquidity, the remaining quantity is discarded.

Each trade execution is recorded. Trades are returned as strings in the format "buyOrderId,sellOrderId,price,quantity".

Implement the following methods:

  • placeOrder(orderId: int, side: str, orderType: str, price: int, quantity: int) : place an order on the book. side is "buy" or "sell" . orderType is "limit" or "market" . For market orders, price is 0 and ignored. The engine matches the incoming order against resting orders on the opposite side using price-time priority. Unmatched quantity of a limit order rests on the book; unmatched quantity of a market order is discarded.
  • cancelOrder(orderId: int) : cancel an existing order by its ID. If the order does not exist, was already fully filled, or was already cancelled, this operation has no effect.
  • getExecutedTrades() -> List[str] : return all trades executed so far, in the order they occurred, each in the format "buyOrderId,sellOrderId,price,quantity" .
  • getOrderQuantity(orderId: int) -> int : return the remaining quantity of the given order on the book. Return 0 if the order does not exist, was fully filled, or was cancelled.
  • getBestBid() -> int : return the highest buy price currently on the book, or -1 if there are no active buy orders.
  • getBestAsk() -> int : return the lowest sell price currently on the book, or -1 if there are no active sell orders.

For example:

placeOrder(1, "sell", "limit", 101, 5)
placeOrder(2, "sell", "limit", 100, 3)
placeOrder(3, "sell", "limit", 100, 4)
placeOrder(4, "buy", "limit", 99, 2)
getBestBid()          -> 99
getBestAsk()          -> 100
placeOrder(5, "buy", "limit", 101, 9)
getOrderQuantity(1)   -> 3
getOrderQuantity(5)   -> 0
cancelOrder(1)
getBestAsk()          -> -1
placeOrder(6, "sell", "market", 0, 5)
getBestBid()          -> -1
getExecutedTrades()   -> ["5,2,100,3", "5,3,100,4", "5,1,101,2", "4,6,99,2"]

Order 4 rests because the best ask (100) is above its limit of 99. Order 5 takes 3 from order 2 and then 4 from order 3 at 100 (order 2 arrived first at that price), then 2 of order 1's 5 at 101, so none of it rests. After order 1 is cancelled the sell side is empty. Market order 6 fills 2 against order 4 at 99 and its other 3 are discarded.

Constraints & Assumptions

  • 1 <= orderId <= 10^6 , and all order IDs are unique across all placeOrder calls.
  • 1 <= price <= 10^6 for limit orders. Market orders pass price = 0 , which is ignored.
  • 1 <= quantity <= 10^6 .
  • side is either "buy" or "sell" , and orderType is either "limit" or "market" .
  • At most 10^4 total operations.
  • A trade executes at the resting order's price, as in the example. The buy order's ID comes first in the trade string no matter which side arrived last.

Clarifying Questions to Ask Guidance

  • When an incoming limit order crosses the spread, does the trade print at the resting order's price or at the incoming order's limit?
  • Is this a single-symbol, single-threaded engine, or can calls arrive concurrently?
  • Can a partially filled order be cancelled, and does that remove only its remaining quantity while the earlier trades stand?
  • Will later requirements add depth queries (total quantity per price level) or order modification? That affects which structure fits best.

What a Strong Answer Covers Guidance

  • The structure used for each side of the book and how its ordering encodes price-time priority.
  • How cancellation works without scanning the book, and how cancelled or filled orders are kept out of matching and out of the best-price queries.
  • The matching loop for limit and market orders: the stop condition, partial fills on both sides, and what happens to leftover quantity.
  • How trades are recorded: the execution price, the buy-then-sell ID order, and chronological order.
  • A correct cost for each operation, including an incoming order that sweeps many resting orders.

Follow-up Questions Guidance

  • How would you return the total resting quantity at a given price, or the top five price levels on each side?
  • How would you support changing an order's price or quantity, and which changes should keep its place in the queue?
  • If cancels made up most of the traffic and the book held millions of orders, what would you change?
  • How would you run the engine for many symbols and rebuild its state after a crash?