A trading engine matches buy and sell orders for financial instruments. Correctness and latency are paramount — microsecond-level matching with zero tolerance for data loss.
Order Book
For each instrument, maintain two sorted lists: bids (buyers) sorted descending by price, asks (sellers) sorted ascending by price. The best bid (highest buy price) and best ask (lowest sell price) form the spread. Data structure: a price-level map where each price level holds a FIFO queue of orders at that price, implementing price-time priority matching.
Order Types
Market order: execute immediately at the best available price. Limit order: execute only at the specified price or better, resting in the book if not immediately matchable. Stop order: becomes a market order when price crosses the trigger. Stop-limit order: becomes a limit order at the trigger price. IOC (immediate or cancel): fills what it can and cancels the remainder. FOK (fill or kill): must fill entirely or cancel.
Matching Algorithm
On new limit order arrival: if a buy order, check the ask side for price <= order.price. Match against the oldest order at each price level (FIFO). Generate a trade for the matched quantity. Repeat until the order quantity is filled or no more matchable orders remain. The remaining quantity rests in the book. Market orders match against the best available price until filled.
Order Schema
Order: order_id, instrument_id, trader_id, side ENUM (buy/sell), type ENUM (market/limit/stop), price, quantity, filled_qty, status ENUM (pending/partial/filled/cancelled), created_at, time_in_force. Trade: trade_id, buy_order_id, sell_order_id, instrument_id, price, quantity, executed_at.
Market Data Feed
After each trade and order book change, publish Level 1 data (best bid, best ask, last trade price, volume) and Level 2 data (full order book depth by price level) to a market data topic. Subscribers — trading clients, risk systems, display terminals — consume via multicast UDP for minimum latency. Level 1 latency target: <1ms.
Circuit Breakers
Halt trading if price moves more than X% in Y minutes, implemented as a rolling window check on each trade. A trading halt is also triggered by exchange-wide news events. During a halt, no new orders are matched, but cancel requests are still processed. Trading resumes after a configurable pause.
Settlement
Trades are confirmed to both counterparties immediately. The clearing house receives a trade report. Settlement is T+2 for cash equities or T+1 for some asset classes. The settlement service debits securities from the seller’s custodian and credits the buyer, and debits cash from the buyer and credits the seller. Failed settlements are handled via a buy-in process.
{ “@context”: “https://schema.org”, “@type”: “FAQPage”, “mainEntity”: [ { “@type”: “Question”, “name”: “How does price-time priority matching work in a stock trading engine?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Price-time priority (also called FIFO matching) ranks orders first by price—best bid or best ask wins—and then, among orders at the same price level, by the time they were received. A buy order at $105 will match before one at $104; two buy orders both at $105 match in the order they arrived. The matching engine iterates the order book from the best price outward, consuming contra-side liquidity until the incoming order is fully filled or the book is exhausted.” } }, { “@type”: “Question”, “name”: “What data structure should an order book use?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “The canonical choice is a sorted map (e.g., a red-black tree or skip list) keyed by price level, where each entry holds a FIFO queue of resting orders at that price. The sorted map gives O(log n) insertion and best-price lookup; the per-level queue gives O(1) FIFO dequeue. For ultra-low latency engines, price levels are often stored in a pre-allocated array indexed by integer price ticks, reducing the map overhead to O(1) at the cost of fixed memory.” } }, { “@type”: “Question”, “name”: “What are the latency requirements for a market data feed?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Retail-grade market data feeds typically target end-to-end latencies of 1–50 ms. Co-located direct feeds at exchanges target microsecond-range latencies (1–100 µs). The feed must publish every order book change as a normalized message (add, modify, cancel, trade) with a sequence number so subscribers can detect gaps. Multicast UDP is the standard transport for high-throughput feeds; a separate TCP recovery channel handles retransmission of missed packets.” } }, { “@type”: “Question”, “name”: “Under what conditions should a circuit breaker trigger in a trading engine?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “Circuit breakers halt trading when price moves exceed a configurable threshold within a rolling time window—commonly a 5% or 10% move in 5 minutes for equities. They also trigger on trading volume spikes beyond N standard deviations of recent averages, on consecutive erroneous trade prints, or when the best bid crosses above the best ask (locked/crossed market). Upon triggering, the engine enters a cooling-off period (typically 5–15 minutes) during which only limit orders are accepted, before reopening with a call auction.” } }, { “@type”: “Question”, “name”: “How does the T+2 settlement flow work after a trade executes?”, “acceptedAnswer”: { “@type”: “Answer”, “text”: “T+2 means the trade settles two business days after the trade date (T). On T, the matching engine emits a trade confirmation with symbol, quantity, price, buyer, and seller identifiers. A clearinghouse (e.g., DTCC) novates the trade, becoming the central counterparty to both sides, and nets positions across participants. On T+1, participants confirm and affirm the trade details. On T+2, the central securities depository (CSD) transfers ownership of shares from seller’s custodian to buyer’s custodian and moves cash in the opposite direction via the settlement bank.” } } ] }Frequently Asked Questions: Stock Trading Engine
How does price-time priority matching work in a stock trading engine?
Price-time priority (also called FIFO matching) ranks orders first by price—best bid or best ask wins—and then, among orders at the same price level, by the time they were received. A buy order at $105 will match before one at $104; two buy orders both at $105 match in the order they arrived. The matching engine iterates the order book from the best price outward, consuming contra-side liquidity until the incoming order is fully filled or the book is exhausted.
What data structure should an order book use?
The canonical choice is a sorted map (e.g., a red-black tree or skip list) keyed by price level, where each entry holds a FIFO queue of resting orders at that price. The sorted map gives O(log n) insertion and best-price lookup; the per-level queue gives O(1) FIFO dequeue. For ultra-low latency engines, price levels are often stored in a pre-allocated array indexed by integer price ticks, reducing the map overhead to O(1) at the cost of fixed memory.
What are the latency requirements for a market data feed?
Retail-grade market data feeds typically target end-to-end latencies of 1–50 ms. Co-located direct feeds at exchanges target microsecond-range latencies (1–100 µs). The feed must publish every order book change as a normalized message (add, modify, cancel, trade) with a sequence number so subscribers can detect gaps. Multicast UDP is the standard transport for high-throughput feeds; a separate TCP recovery channel handles retransmission of missed packets.
Under what conditions should a circuit breaker trigger in a trading engine?
Circuit breakers halt trading when price moves exceed a configurable threshold within a rolling time window—commonly a 5% or 10% move in 5 minutes for equities. They also trigger on trading volume spikes beyond N standard deviations of recent averages, on consecutive erroneous trade prints, or when the best bid crosses above the best ask (locked/crossed market). Upon triggering, the engine enters a cooling-off period (typically 5–15 minutes) during which only limit orders are accepted, before reopening with a call auction.
How does the T+2 settlement flow work after a trade executes?
T+2 means the trade settles two business days after the trade date (T). On T, the matching engine emits a trade confirmation with symbol, quantity, price, buyer, and seller identifiers. A clearinghouse (e.g., DTCC) novates the trade, becoming the central counterparty to both sides, and nets positions across participants. On T+1, participants confirm and affirm the trade details. On T+2, the central securities depository (CSD) transfers ownership of shares from seller’s custodian to buyer’s custodian and moves cash in the opposite direction via the settlement bank.
See also: Coinbase Interview Guide
See also: Stripe Interview Guide 2026: Process, Bug Bash Round, and Payment Systems
See also: Scale AI Interview Guide 2026: Data Infrastructure, RLHF Pipelines, and ML Engineering