Design an online stock brokerage. Customers hold cash and shares, place buy and sell orders (market or limit), and the exchange matches them.
Customers have an **account** with cash and **holdings**.
A customer places a **buy or sell order**, **market** or **limit**.
A buy needs **enough cash**, and a sell needs **enough shares**. Funds are reserved while the order is open.
Orders are **matched** by price then time; partial fills are allowed.
A customer can **cancel** an open order.
Stage 1: Accounts, holdings and orders
Name the things.
Money and shares need a reserved amount, or two orders spend the same cash. An `Account` has cash and `reserved` cash, and each `Holding` has reserved shares. `Order` is abstract; `LimitOrder` adds a price. Available cash is cash minus reserved, so a second order sees what is really free. Reservation adds bookkeeping but is the only way to avoid overspending.
Stage 2: Market orders and the order book
Hold open orders sorted for matching.
Matching needs orders ordered by price, then time. `OrderBook` keeps buys (highest first) and sells (lowest first). `MarketOrder` has no price and takes the best available. The best price is always at the front, so matching never scans. A sorted list gives O(log n) insert. A price-level map is faster for a hot stock.
Stage 3: Trades and matching
Match the best buy with the best sell.
Nothing turns two compatible orders into a trade or handles partial fills. `MatchingEngine.submit` matches while the best buy price is at least the best sell price, creating a `Trade` for the smaller quantity and leaving the rest in the book. A partial fill is just a trade for less than an order's size, with the remainder still open. One engine per symbol keeps locking simple: each symbol is matched by one thread.
Stage 4: The broker, risk and fills
Check funds, reserve, then tell the customer.
An order must be funded before it enters the book, and customers must be told about fills. `BrokerService.place` asks `RiskCheck` whether the account can afford it and reserves, then sends the order to the engine. `TradeListener`s (settlement, notifications) react to each trade. Funds are checked once, at the door. Settlement and messages are separate (**Observer**). Settlement is not instant in real markets. Model it as a later step that releases reservations.