Limit Order Book
Prerequisites: Order Book API Shape, Matching Engine Concepts
An exchange receives buy and sell orders for AAPL throughout the day. Build its limit order book: orders that can trade do so immediately, and the rest wait in the book for future orders.
- Limit price: a buyer will pay up to it, and a seller will accept no less.
- Best bid: the highest buy price. Best ask: the lowest sell price.
- Price-time priority: better prices go first, and orders at the same price keep their arrival order.
What to implement
process_commands(commands)returns the lines the book prints, in order. Each command is one line.- Prices and quantities are positive integers. Prices are in ticks, as in the articles.
- Order ids are unique and never reused.
- On stdin, the first line is the number of commands, and each remaining line is one command.
- There are three parts, each adding behavior on top of the previous one. One solution must pass all nine tests.
| Command | What it does |
|---|---|
NEW id B price qty | Add a buy order |
NEW id S price qty | Add a sell order |
BOOK | Print the best bid and best ask |
CANCEL id | Cancel a resting order (Part 3) |
Part 1: The resting book
Output of BOOK:
BOOK bid_price bid_qty ask_price ask_qty
bid_priceis the best bid andask_pricethe best ask.bid_qtyandask_qtyare the total quantities resting at those prices.- An empty side prints as
NONE 0.
Tests 1–3 cover this part. In them, no buy price ever reaches a sell price, so nothing trades.
Part 2: Match crossing orders
A new order now trades before it can rest.
- An incoming buy consumes the lowest ask at or below its limit. An incoming sell consumes the highest bid at or above its limit.
- Better prices go first, and orders at the same price trade in arrival order.
- Partial fills are allowed. A partly filled resting order keeps its place at the front of its level.
- When the incoming order runs out of crossing prices, any remainder rests in the book like a Part 1 order.
Output: one line per fill.
TRADE buy_id sell_id price qty
priceis the resting order's price.
Tests 4–6 cover this part.
Part 3: Cancel resting orders
CANCEL idremoves the unfilled portion of a resting order.- Unknown, filled, and previously cancelled ids are ignored.
CANCELprints nothing.
Tests 7–9 cover this part.
The example below crosses orders, so it also uses Part 2's matching rules.
4 NEW 10 S 105 2 NEW 11 S 105 3 NEW 12 B 106 4 BOOK
TRADE 12 10 105 2 TRADE 12 11 105 2 BOOK NONE 0 105 1
Orders 10 and 11 rest at 105, with 10 first. Order 12 will pay up to 106, so it crosses the 105 level: it fills all 2 of order 10, then 2 of order 11's 3.
Both trades print at the resting price 105, not at 106. Order 12 is filled, so no bid rests, and order 11 has 1 left at the best ask.