~/problems / Trading systems / Order books and matching engines

Basics: top of book from resting orders

easy basics ~10 min

An order book holds resting limit orders. Buyers post bids (the most they'll pay) and sellers post asks (the least they'll accept). The best bid is the highest bid price and the best ask is the lowest ask price. Together they are the "top of book".

Implement top_of_book(orders):

  • orders is a list of (side, price, qty) tuples. side is "buy" or "sell", price is a positive integer (prices are in integer ticks, never floats), and qty is a positive integer.
  • Return a pair (best_bid, best_ask). Each one is a tuple (price, total_qty), where total_qty adds up the quantity of every order resting at that price on that side. If a side has no orders, use None for it.
orders = [
    ("buy", 99, 5),
    ("buy", 100, 2),
    ("sell", 103, 4),
    ("buy", 100, 3),
    ("sell", 101, 1),
]
top_of_book(orders)   # ((100, 5), (101, 1))

top_of_book([("sell", 50, 7)])   # (None, (50, 7))
top_of_book([])                  # (None, None)

Your code shouldn't assume anything about how bid prices compare with ask prices: a bid and an ask may even sit at the same price, and they still belong to separate sides. One pass over the orders is enough.

Show hint

the best bid is a max over buy prices and the best ask a min over sell prices; group quantity per (side, price) in a dict so orders at the same level add up.

Topic: Order books and matching engines. Price levels, price-time priority, partial fills, cancels.

0:00
Ctrl ' run · Ctrl ↵ submit
esc