Core Entities
Order: order_id, user_id, symbol, side (BUY, SELL), order_type (MARKET, LIMIT, STOP_LIMIT, TRAILING_STOP), quantity, limit_price, stop_price, status (PENDING, PARTIALLY_FILLED, FILLED, CANCELLED, REJECTED), filled_quantity, average_fill_price, created_at. Trade: trade_id, buy_order_id, sell_order_id, symbol, quantity, price, executed_at. Position: position_id, user_id, symbol, quantity, average_cost_cents, current_value_cents, unrealized_pnl. Quote: symbol, bid_price, ask_price, last_price, volume, timestamp.
Order Book Data Structure
The order book maintains all outstanding limit orders sorted by price. Buy orders (bids): sorted descending by price (highest bid first). Sell orders (asks): sorted ascending by price (lowest ask first). Within each price level: sorted by time (FIFO — earlier orders execute first). Data structure: a sorted map (TreeMap in Java, SortedDict in Python) keyed by price, with each price level holding a queue of orders. Best bid: the maximum price in the buy side. Best ask: the minimum price in the sell side. Spread = best_ask – best_bid. Depth: the order book shows quantity available at each price level (L2 market data).
Matching Engine
The matching engine executes trades when buy and sell orders are compatible. Price-time priority: orders are matched first by price (best price executes first), then by time (older orders at the same price execute first). Market order matching: a market buy executes against the lowest-priced sell orders until filled. Limit order matching: a limit buy at price P executes against sell orders with price = best ask, or sell price <= best bid). (2) While crossed and quantity remaining: take the best opposing order. Create a Trade. Reduce both orders quantities. (3) If the incoming order is not fully filled: add the remainder to the book. Matching must be single-threaded or serialized per symbol to maintain price-time priority consistency.
def match_order(book, incoming):
trades = []
if incoming.side == BUY:
while incoming.qty > 0 and book.asks and book.asks.min_price() 0: # add remainder to book
book.bids.add(incoming)
return trades
Order Types
Market order: execute immediately at the best available price. Risk: in low-liquidity markets, slippage can be severe. Limit order: execute only at price = limit (sell). May not execute if the market never reaches the limit price. Stop order: becomes a market order when the price crosses the stop level. Stop-limit order: becomes a limit order at the stop level. Use case: stop-loss to limit downside. Trailing stop: the stop level follows the market price by a fixed delta (e.g., stop at current_price – $5). On price rise: stop rises. On price fall: stop holds, triggering when the price falls $5 from the peak. Good-till-cancelled (GTC): the order remains active until explicitly cancelled (vs day orders that expire at market close).
Portfolio Management and Risk
Portfolio tracks positions: each (user, symbol) pair has quantity and average cost basis. On each trade: update position quantity and compute new average cost basis: avg_cost = (old_qty * old_avg_cost + new_qty * fill_price) / (old_qty + new_qty). Unrealized PnL = (current_market_price – avg_cost) * quantity. Realized PnL is recorded on each closing trade. Risk checks before order acceptance: (1) Buying power: cash_balance >= order_quantity * current_price (for cash accounts). (2) Position limits: no single position > X% of portfolio (configurable). (3) Pattern day trader rules (US): accounts with less than $25K equity flagged after 3 day trades in 5 days. (4) Short selling eligibility: verify the user has a margin account and the stock is shortable.
Settlement
T+1 settlement (US equities since 2024): trades settle one business day after execution. Settlement means: cash is deducted from the buyer account and added to the seller, shares are transferred in the custodian system. During the T+1 window: shares and cash are in a pending state (cannot be withdrawn). Failed settlement: if a seller cannot deliver the shares by T+1, the broker buys the shares in the open market (buy-in) at the seller expense. Failed settlement tracking: monitor fail-to-deliver rates as a compliance KPI. Clearing: trades are netted at the clearinghouse (DTCC in the US) — if a user buys 100 shares and sells 80 shares of the same stock on the same day, only the net 20 shares are settled.
Asked at: Coinbase Interview Guide
Asked at: Stripe Interview Guide
Asked at: Databricks Interview Guide
Asked at: Shopify Interview Guide