Stock Broker
hard · limit order book, price-time priority
Brief-reported interview attribution (unverified): Amazon
How to approach an LLD roundImplement a simplified stock exchange. Orders are placed for a
symbol with a side ("buy"/"sell"), a price (whole dollars), and a quantity
(shares). The exchange keeps a limit order book per symbol: bids (buy orders) and
asks (sell orders). A new order matches against the opposite book by **price-time
priority** — the best price first, the earliest order first among equal prices:
a buy matches the lowest-priced ask at or below the buy price; a sell matches the
highest-priced bid at or above the sell price. Each trade happens at the **resting
order's price** (the order already in the book). A partially filled order rests in
its own book with the remaining quantity; a fully filled order leaves no trace.
class StockBroker:
def __init__(self):
def place_order(self, symbol, side, price, quantity):
# -> (order_id, trades) where trades = [{"buy_order":, "sell_order":, "price":, "quantity":}, ...]
# in the order they happened; (None, []) for a bad side, price <= 0, or quantity <= 0
def book(self, symbol):
# -> {"bids": [{"order_id":, "price":, "quantity":}], "asks": [...]}
# bids by price desc then order id asc; asks by price asc then order id asc
# ({"bids": [], "asks": []} for an unknown symbol)
def cancel_order(self, order_id):
# -> True if a resting order was cancelled, False otherwise
# (a fully filled order cannot be cancelled)
Rules. Order ids start at 1 and increase. A trade's quantity is
min(remaining new quantity, resting quantity). A buy that cannot match at all
rests as a bid; a sell that cannot match at all rests as an ask. book() returns
copies, so callers cannot mutate the book.
Money units: order prices are whole dollars. Quantity is a count of shares.
Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.
Public demo
# Public demo: run after implementing the class API above.
s = StockBroker()
print(s.place_order('AAPL', 'sell', 150, 10))Starter code
class StockBroker:
def __init__(self):
"""Initialize the state described in the problem."""
pass
def place_order(self, symbol, side, price, quantity):
"""-> (order_id, trades) where trades = [{"buy_order":, "sell_order":, "price":, "quantity":}, ...] in the order they happened; (None, []) for a bad side, price <= 0, or quantity <= 0"""
pass
def book(self, symbol):
"""-> {"bids": [{"order_id":, "price":, "quantity":}], "asks": [...]} bids by price desc then order id asc; asks by price asc then order id asc ({"bids": [], "asks": []} for an unknown symbol)"""
pass
def cancel_order(self, order_id):
"""-> True if a resting order was cancelled, False otherwise (a fully filled order cannot be cancelled)"""
pass
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python compiler