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):
ordersis a list of(side, price, qty)tuples.sideis"buy"or"sell",priceis a positive integer (prices are in integer ticks, never floats), andqtyis a positive integer.- Return a pair
(best_bid, best_ask). Each one is a tuple(price, total_qty), wheretotal_qtyadds up the quantity of every order resting at that price on that side. If a side has no orders, useNonefor 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.