Design a Stock Exchange with Trader Accounts
Model a small stock exchange: limit orders, price-time matching, partial fills, held cash and shares, and cancellation.
For this exercise, assume a small stock exchange runs inside one Python program. Each trader has an account holding cash and shares of several stocks. A trader places a limit order to buy or sell a whole number of shares of one stock at a price per share.
A buy order needs enough free cash and a sell order needs enough free shares; that cash or those shares are held for the order until it is filled or cancelled, and an order that cannot be covered is refused with no change. Orders for different stocks never trade with each other.
A new order trades against waiting orders on the other side whose price is acceptable to it: the best price first and, at the same price, the order that arrived earlier. A trade happens at the waiting order's price and may fill an order only partly; whatever is left of the new order then waits.
Every trade moves cash and shares between the two traders' accounts. A trader can cancel the unfilled part of their own waiting order, which frees what it was holding. Traders can see their balances and their waiting orders, and anyone can see the best buy and sell prices of a stock.
Design the objects, their responsibilities, the interfaces, and the interactions, then write Python for what happens when one new order arrives. One follow-up adds market orders. Fees, market hours, short selling, borrowing, saving data, and networking are out of scope. Everything runs on one thread.