Skip to main content

Requirements for the Stock Brokerage

Editorial

Functional Requirements

Let's define what our Stock Brokerage system needs to do. Each requirement is specific enough to drive at least one class or method in the final design.

Account & Portfolio Management:

  1. R1: Trader account management — The system shall allow traders to register with a unique username, maintain a cash balance, and hold a portfolio of stock positions. Each position tracks the stock symbol and the quantity owned.

  2. R2: Stock catalog — The system shall maintain a catalog of tradeable stocks, each identified by a unique ticker symbol (e.g., AAPL, GOOGL) with a current market price that updates after every trade execution.

Order Submission:

  1. R3: Market orders — A trader shall be able to place a Market Order (buy or sell) that executes immediately at the best available price on the opposite side of the order book. If the order book has insufficient liquidity, the unfilled portion is cancelled.

  2. R4: Limit orders — A trader shall be able to place a Limit Order (buy or sell) at a specified price. A buy limit order executes only at the specified price or lower. A sell limit order executes only at the specified price or higher. If the order cannot be filled immediately, it rests on the order book until it matches or is cancelled.

  3. R5: Order validation — Before placing an order, the system shall validate: (a) for buy orders, the trader has sufficient cash balance to cover the order value; (b) for sell orders, the trader holds sufficient shares of the stock; (c) the stock symbol exists in the catalog; (d) the quantity is a positive integer.

Order Book & Matching:

  1. R6: Order book per stock — Each stock shall have its own order book containing two sides: bids (buy orders) sorted by price descending, and asks (sell orders) sorted by price ascending. Within each price level, orders are queued in FIFO (First In, First Out) order.

  2. R7: Price-time priority matching — The matching engine shall enforce price-time priority: (a) a buy order matches against the lowest-priced ask first; (b) a sell order matches against the highest-priced bid first; (c) among orders at the same price, the order that arrived earliest matches first.

  3. R8: Partial fills — An order may be partially filled if the opposite side has insufficient quantity at the matching price. The remaining unfilled quantity stays on the order book (for limit orders) or is cancelled (for market orders).

  4. R9: Trade execution — When a match occurs, a Trade record is created capturing: buyer, seller, stock, quantity, execution price, and timestamp. Both traders' portfolios and cash balances are updated atomically.

Order Lifecycle:

  1. R10: Order status tracking — Each order shall have a status: PENDING (submitted, not yet matched), PARTIALLY_FILLED (some quantity matched), FILLED (all quantity matched), or CANCELLED. Status transitions follow this lifecycle.

  2. R11: Order cancellation — A trader shall be able to cancel their own pending or partially-filled limit order. Market orders cannot be cancelled (they execute or cancel immediately). Cancelled orders are removed from the order book.

Price Alerts:

  1. R12: Price alert subscriptions — A trader shall be able to create a price alert for a stock: "Notify me when the price of SYMBOL crosses THRESHOLD from above (or below)." The alert fires once and is then deactivated.

  2. R13: Alert evaluation on trade — After every trade execution, the system shall check all active alerts for that stock and trigger any whose threshold conditions are now met.

Non-Functional Requirements

Beyond functionality, the design must satisfy:

  1. NF1: Correctness above all — The matching engine must guarantee that no order is lost, no trade is double-counted, and price-time priority is never violated. A single correctness bug can represent millions of dollars in erroneous trades. Our design must make it structurally impossible to violate priority rules.

  2. NF2: Extensibility for new order types — The system should be easy to extend with new order types (Stop-Loss, Stop-Limit, Trailing Stop) without modifying the existing order processing pipeline. The Strategy Pattern for matching and the Command Pattern for orders make this possible.

  3. NF3: Separation of concerns — The Order Book (data structure), the Matching Engine (algorithm), and the Alert System (notifications) should be independent modules. Changing the matching algorithm should not require touching the alert system or the order book structure.

  4. NF4: Auditability — Every order submission, cancellation, and trade execution should be traceable. The Command Pattern ensures each action is a logged, inspectable object.

  5. NF5: Testability — Each component (Order validation, Order Book insertion, Matching Engine logic, Alert evaluation) should be testable in isolation with mock dependencies.

Scope Clarification

In Scope:

  • Trader accounts with cash balance and stock portfolio
  • Stock catalog with ticker symbols and last-traded price
  • Market and Limit order types (buy and sell)
  • Order validation (balance, holdings, symbol, quantity)
  • Order book data structure per stock (sorted bids and asks with FIFO per price)
  • Matching engine with price-time priority (full and partial fills)
  • Trade execution with portfolio and balance updates
  • Order lifecycle (Pending → Partially Filled → Filled / Cancelled)
  • Order cancellation for limit orders
  • Price alert subscriptions with threshold-crossing notifications

Out of Scope:

  • Network protocols — FIX/FAST protocol handling is infrastructure, not LLD
  • Persistence — no database, ORM, or file storage; all state is in-memory
  • REST APIs — no HTTP endpoints; we model domain objects directly
  • Advanced order types — Stop-Loss, Trailing Stop, Iceberg, and Fill-or-Kill are natural extensions but not in our initial scope
  • Margin trading & short selling — these require credit/risk systems outside LLD scope
  • Real-time market data feeds — we model the internal matching, not external data ingestion
  • Distributed systems — no horizontal scaling, no partitioning across multiple matching engines
  • Options, Futures, or Derivatives — we model equities (stocks) only

Interview Tip

In a real interview, spend 3-5 minutes clarifying requirements before jumping into design. For this problem, the critical clarifying questions are:

  • "What order types do we support?" — Market and Limit are expected. Stop-Loss and others are usually out of scope unless the interviewer says otherwise. Asking shows you know the domain has complexity beyond the basic types.
  • "How does the matching engine handle partial fills?" — This is the make-or-break question. If you assume all orders fill completely, your design is wrong. Partial fills mean an order's quantity decreases over multiple matches — the order stays on the book until fully filled or cancelled.
  • "Is this a single stock or multi-stock system?" — Almost always multi-stock. Each stock has its own independent order book. This is a key architectural decision: the order book is per-stock, not global.
  • "Do we need to handle concurrent access?" — For LLD, typically single-threaded is acceptable. But mentioning that a production matching engine is single-threaded per stock (to avoid locking overhead) shows deep understanding.
  • "Should we model the broker as a separate entity, or is the 'system' the broker?" — In our scope, the system IS the broker. Traders interact directly. In a real-world brokerage, there's a multi-tier system (client → broker → exchange), but for LLD we flatten this.