Back to Blog
BlockchainTradingAlgorithmsExchangeFinance

Trading Engine Algorithms: How Orders Get Matched

Explore the algorithms powering exchange matching engines. From price-time priority to pro-rata matching, learn how different approaches affect fairness, speed, and market dynamics.

Nawab Khairuzzaman10 min read
Share:
BLOG POST

The matching engine is the heart of any exchange. When you click "Buy," a sophisticated algorithm determines which seller you're paired with, at what price, and in what quantity. These algorithms shape market behavior, influence trading strategies, and determine who gets filled first during volatile moments.

What Does a Matching Engine Do?

A matching engine maintains the order book and executes trades when compatible orders exist. Its responsibilities include:

Order Management — Accepting new orders, modifying existing ones, and processing cancellations.

Price Discovery — Determining the current market price based on the intersection of supply and demand.

Trade Execution — Pairing compatible buy and sell orders and generating trade confirmations.

Market Data Distribution — Broadcasting order book updates, trades, and statistics to connected systems.

The engine must do all this with extreme speed and perfect accuracy. A bug that matches orders at wrong prices or double-counts fills could cost millions.


The Order Book Data Structure

Before exploring matching algorithms, we need to understand how orders are stored.

Price Levels

Orders are grouped by price into price levels. All buy orders at $50,000 form one level, orders at $49,999 form another. Within each level, orders are typically stored in arrival order.

plaintext
Price Level: $50,000 (BUY)
├── Order #1001: 0.5 BTC (arrived 09:00:01.234)
├── Order #1002: 1.2 BTC (arrived 09:00:01.567)
└── Order #1003: 0.3 BTC (arrived 09:00:02.123)
    Total: 2.0 BTC

Efficient Data Structures

The order book requires efficient operations:

  • Insert — Add new orders (must be fast for high-frequency trading)
  • Delete — Remove canceled or filled orders
  • Find Best — Locate the highest bid or lowest ask
  • Match — Find all orders at a price level for execution

Common implementations use balanced trees (Red-Black, AVL) or skip lists for price levels, with queues or linked lists for orders within each level. This provides O(log n) insertion/deletion and O(1) access to best prices.


Price-Time Priority (FIFO)

The most common matching algorithm is Price-Time Priority, also called First-In-First-Out (FIFO). It uses two simple rules:

  1. Better price wins — A higher bid beats a lower bid; a lower ask beats a higher ask
  2. Earlier order wins — Among orders at the same price, the one that arrived first gets filled first

Why Price-Time Priority?

This algorithm rewards two behaviors:

Price Improvement — Traders willing to offer better prices get priority. This tightens spreads and improves price discovery.

Speed — Traders who act first at a price level gain an advantage. This incentivizes quick reactions to market information.

How It Works

Imagine this order book for BTC/USD:

plaintext
ASKS:
$50,100: [Order A: 1.0 BTC, Order B: 0.5 BTC]
$50,050: [Order C: 0.8 BTC]
 
BIDS:
$50,000: [Order D: 2.0 BTC, Order E: 1.0 BTC]
$49,950: [Order F: 3.0 BTC]

A market buy order for 1.5 BTC arrives. The engine:

  1. Takes from the best ask ($50,050) first
  2. Fills 0.8 BTC from Order C, exhausting that level
  3. Moves to next level ($50,100)
  4. Fills 0.7 BTC from Order A (arrived first)
  5. Order A has 0.3 BTC remaining
  6. Total: 1.5 BTC filled at average price $50,070

Order B at the same price level never gets touched because Order A had time priority.

Advantages

  • Simple and predictable — Easy to understand and verify
  • Rewards price improvement — Better prices always win
  • Transparent — Order position in queue is deterministic

Disadvantages

  • Speed arms race — Encourages co-location and low-latency infrastructure
  • Front-running risk — Fast traders can jump ahead of slower participants
  • Favors large players — Institutions can afford speed advantages

Pro-Rata Matching

Pro-Rata matching distributes fills proportionally among all orders at the best price, regardless of arrival time.

How It Works

Using the same order book, if a market buy for 1.5 BTC arrives when multiple orders exist at the best ask:

plaintext
$50,050: [Order C: 0.8 BTC, Order D: 0.4 BTC, Order E: 0.8 BTC]
Total at level: 2.0 BTC

Each order gets filled proportionally:

  • Order C: (0.8 / 2.0) × 1.5 = 0.6 BTC filled
  • Order D: (0.4 / 2.0) × 1.5 = 0.3 BTC filled
  • Order E: (0.8 / 2.0) × 1.5 = 0.6 BTC filled

Advantages

  • Reduces speed advantage — Arrival time doesn't determine fill priority
  • Encourages size — Larger orders get proportionally larger fills
  • Fairer for slower participants — Retail traders aren't disadvantaged by latency

Disadvantages

  • Discourages price improvement — Less incentive to offer better prices
  • Size manipulation — Traders might submit large orders to capture allocation
  • More complex — Calculating proportional fills adds computational overhead

Where It's Used

Pro-rata matching is common in derivatives markets, particularly options exchanges where institutional hedgers need predictable fills. The CME uses a hybrid system for many products.


Time-Weighted Pro-Rata

Some exchanges combine elements of both approaches. Orders that have been in the book longer get weighted more heavily in pro-rata calculations.

plaintext
Weight = Base + (Time in Book × Time Factor)

This rewards both patience (providing liquidity) and size, creating a middle ground between pure FIFO and pure pro-rata.


Price-Size-Time Priority

This variant adds order size as a secondary priority after price:

  1. Best price wins
  2. Larger orders win (at same price)
  3. Earlier orders win (at same price and size)

The theory is that larger orders represent more committed liquidity and deserve priority. However, this can encourage order size manipulation and discourage smaller participants.


Auction Mechanisms

Rather than continuous matching, some markets use periodic auctions to batch orders and find clearing prices.

Call Auctions

Orders accumulate during a collection period, then match simultaneously at a single clearing price that maximizes traded volume.

plaintext
Collection Period (5 minutes):
- Buy: 100 BTC at $50,100 or less
- Buy: 50 BTC at $50,000 or less
- Sell: 80 BTC at $49,900 or more
- Sell: 60 BTC at $50,000 or more
 
Clearing Price: $50,000
- Matches 140 BTC of demand with 140 BTC of supply
- All trades execute at $50,000

Advantages of Auctions

  • No speed advantage — All orders submitted during the period are treated equally
  • Price discovery — Single clearing price reflects true market equilibrium
  • Reduced manipulation — Harder to front-run when orders batch together

Disadvantages

  • Delayed execution — Must wait for auction to complete
  • Less flexibility — Can't react to real-time price changes
  • Lower liquidity between auctions — No continuous market

Where Auctions Are Used

Stock exchanges use opening and closing auctions to set official prices. Some DEXs (like CowSwap) use batch auctions to protect against MEV. Dark pools often use periodic auctions to match large institutional orders.


Dark Pool Matching

Dark pools hide order information to reduce market impact for large trades. Several matching approaches exist:

Midpoint Matching

Orders match at the midpoint between the best bid and ask on a reference exchange. Neither side knows the other's price, and both get the same fair price.

plaintext
Reference Market: Bid $50,000 / Ask $50,100
Midpoint: $50,050
 
Dark Pool:
- Hidden Buy: 100 BTC
- Hidden Sell: 80 BTC
- Match: 80 BTC at $50,050

Volume-Weighted Matching

Orders match based on prices from recent trades on lit markets, ensuring dark pool executions reflect true market conditions.

Advantages

  • Reduced market impact — Large orders don't move visible prices
  • Better execution — Institutions avoid signaling their intentions

Regulatory Concerns

Regulators worry that dark pools fragment liquidity and create information asymmetries. They require minimum price improvement and transparency reporting.


Matching Engine Performance

The technical requirements for matching engines are demanding.

Latency Requirements

Exchange TypeTypical LatencyNotes
Traditional Stock10-50 microsecondsNASDAQ, NYSE
Crypto (Major)50-500 microsecondsBinance, Coinbase
Crypto (Mid-tier)1-10 millisecondsSmaller exchanges
DEX (L1)1-15 secondsBlockchain block time
DEX (L2)100ms - 2 secondsOptimistic/ZK rollups

Throughput

Major exchanges handle:

  • NASDAQ: 1+ million messages per second
  • Binance: 100,000+ orders per second during peaks
  • CME: 500,000+ messages per second across products

Implementation Considerations

High-performance matching engines typically:

  • Run in-memory — No database round-trips during matching
  • Use lock-free data structures — Avoid contention between threads
  • Minimize allocations — Pre-allocate memory to avoid garbage collection pauses
  • Employ kernel bypass — Direct NIC access for lowest latency
  • Shard by symbol — Each trading pair on dedicated hardware

Fairness and Market Microstructure

The choice of matching algorithm has real consequences for market participants.

Speed Advantages

Price-time priority creates demand for speed. Firms invest millions in:

  • Co-location (servers physically close to exchange)
  • Custom hardware (FPGAs, ASICs)
  • Network optimization (shortest fiber routes)
  • Predictive algorithms (anticipating order flow)

This arms race benefits technology vendors and large institutions while potentially disadvantaging retail traders.

Gaming and Manipulation

Each algorithm has vulnerabilities:

FIFO: Front-running, latency arbitrage, quote stuffing Pro-Rata: Size manipulation, quote flickering Auctions: Information leakage during collection, timing games

Exchanges continuously update rules to address emerging manipulation techniques.

The Fairness Debate

What's "fair" depends on perspective:

  • Speed advocates: Fast execution rewards those who process information quickly, improving market efficiency
  • Speed critics: Pure speed advantages have nothing to do with fundamental analysis, just technology budgets
  • Compromise: Hybrid systems, speed bumps (intentional delays), and frequent batch auctions attempt balance

Emerging Approaches

New matching paradigms are evolving, particularly in DeFi:

Intent-Based Matching

Instead of specifying exact orders, users express intentions ("swap up to 100 ETH for USDC at best available price"). Solvers compete to fulfill intents optimally, potentially aggregating across multiple venues.

Frequent Batch Auctions

Systems like CowSwap batch orders every few seconds, finding optimal matching that maximizes trader welfare while minimizing MEV extraction.

Encrypted Order Flow

Orders are encrypted until matching time, preventing front-running. Zero-knowledge proofs verify valid matching without revealing order details.

AMM Hybrids

Some DEXs combine AMM liquidity with order books, using concentrated liquidity or limit orders alongside constant product pools.


Choosing the Right Algorithm

There's no universally best matching algorithm. The choice depends on:

Market Type

  • Highly liquid markets benefit from continuous matching
  • Less liquid markets might prefer auctions

Participant Mix

  • Retail-heavy markets might use pro-rata for fairness
  • Institutional markets often prefer price-time for execution certainty

Regulatory Environment

  • Some jurisdictions mandate specific priority rules
  • Best execution requirements influence design

Technical Capabilities

  • Complex algorithms require more sophisticated infrastructure
  • Simpler rules are easier to audit and verify

Want Your Own Exchange?

I build production-ready cryptocurrency exchanges with advanced trading engines, secure wallet systems, and real-time order matching.

View Gig

Conclusion

Matching algorithms are the invisible rules that govern how trades happen. Price-time priority dominates most markets due to its simplicity and price improvement incentives, but pro-rata, auctions, and hybrid approaches each serve specific needs.

Understanding these algorithms helps traders optimize execution, regulators design fair markets, and developers build better trading systems. As crypto markets mature and DeFi evolves, we'll likely see continued innovation in how orders meet.

The matching engine might seem like pure infrastructure, but its design shapes incentives, determines winners and losers, and ultimately influences how efficiently markets discover prices.

N

Nawab Khairuzzaman

Full-Stack Web & Blockchain Developer with 6+ years of experience building scalable applications.

Comments

Related Posts