Chapter 8

Algorithmic Trading

Market microstructure, execution strategies, and high-frequency trading.

Algorithmic Trading

Algorithmic trading uses computer programs to execute trading strategies automatically. From simple order execution to complex statistical arbitrage, algorithms now dominate market activity. Understanding these systems is essential for quantitative developers and traders.

Market Microstructure

Order Book Dynamics

The limit order book (LOB) is the central data structure of modern markets:

  • Bid side: Buy orders sorted by price (highest first)
  • Ask side: Sell orders sorted by price (lowest first)
  • Mid price: Pmid=Pbid+Pask2P_{mid} = \frac{P_{bid} + P_{ask}}{2}
  • Spread: S=PaskPbidS = P_{ask} - P_{bid}

Order Types

Market orders: Execute immediately at best available price. Take liquidity.

Limit orders: Execute only at specified price or better. Provide liquidity.

Iceberg orders: Large orders with only a portion visible.

TWAP/VWAP orders: Algorithmic orders targeting time/volume-weighted averages.

Market Impact

Trading moves prices. Market impact is the price change caused by a trade:

Temporary impact: Price displacement during execution; reverses afterward.

Permanent impact: Lasting price change due to information in the trade.

The square root law approximates permanent impact: ΔPσQV\Delta P \approx \sigma \sqrt{\frac{Q}{V}}

where QQ is order size and VV is daily volume.

Adverse Selection

Market makers face adverse selection: informed traders profit at their expense. The bid-ask spread compensates for this risk.

Execution Algorithms

Time-Weighted Average Price (TWAP)

Splits a large order evenly across time: qi=QNq_i = \frac{Q}{N}

where QQ is total quantity and NN is number of intervals.

Pros: Simple, predictable. Cons: Ignores volume patterns.

Volume-Weighted Average Price (VWAP)

Matches trading to expected volume profile: qi=Qvijvjq_i = Q \cdot \frac{v_i}{\sum_j v_j}

where viv_i is expected volume in interval ii.

Target: Achieve execution price near market VWAP.

Implementation Shortfall (IS)

Minimizes total cost including market impact and timing risk: IS=Decision PriceExecution Price\text{IS} = \text{Decision Price} - \text{Execution Price}

Optimal execution balances:

  • Market impact cost: Trading too fast
  • Timing risk: Adverse price moves while waiting

Almgren-Chriss model solves: minE[Cost]+λVar[Cost]\min E[\text{Cost}] + \lambda \cdot Var[\text{Cost}]

Optimal trajectory for risk-averse trader: xt=Xsinh(κ(Tt))sinh(κT)x_t = X \cdot \frac{\sinh(\kappa(T-t))}{\sinh(\kappa T)}

Participation Rate

Trade a fixed percentage of market volume: qi=γViq_i = \gamma \cdot V_i

where γ\gamma is participation rate (e.g., 10%).

Trading Strategies

Statistical Arbitrage

Exploits temporary mispricings identified through statistical analysis:

Pairs trading: Trade mean-reverting spreads between correlated assets.

  1. Identify cointegrated pairs
  2. Calculate spread: zt=S1,tβS2,tz_t = S_{1,t} - \beta S_{2,t}
  3. Trade when spread deviates from equilibrium

Mean reversion signals: z-score=ztzˉσz\text{z-score} = \frac{z_t - \bar{z}}{\sigma_z}

Enter when |z-score| > threshold; exit at mean.

Momentum Strategies

Trade in the direction of recent price trends:

Time-series momentum: Signal=sign(Rtk:t)\text{Signal} = \text{sign}(R_{t-k:t})

Long if recent return positive; short if negative.

Cross-sectional momentum: Long winners, short losers relative to universe.

Market Making

Provide liquidity by quoting both sides:

  • Post bid at PbidP_{bid}, ask at PaskP_{ask}
  • Earn spread on round-trip trades
  • Manage inventory risk

Avellaneda-Stoikov model for optimal quotes: Pbid=Pmidδbid,Pask=Pmid+δaskP_{bid} = P_{mid} - \delta^{bid}, \quad P_{ask} = P_{mid} + \delta^{ask}

Quotes depend on inventory, volatility, and time remaining.

Arbitrage

Statistical arbitrage: Probabilistic mispricings.

Index arbitrage: Exploit differences between index and component prices.

ETF arbitrage: Create/redeem ETF shares when prices diverge from NAV.

High-Frequency Trading (HFT)

Characteristics

  • Latency measured in microseconds
  • High message rates
  • Small profit per trade, large volume
  • Flat end-of-day positions

Infrastructure

Colocation: Servers physically near exchange matching engines.

Network optimization: Custom network cards, kernel bypass, FPGA acceleration.

Data feeds: Direct market data feeds (faster than consolidated).

Strategies

Latency arbitrage: Profit from speed advantage in processing information.

Market making: Capture spread while managing adverse selection.

Order anticipation: Detect and front-run large institutional orders.

Backtesting and Research

Framework

  1. Data acquisition: Historical prices, order book data, fundamental data
  2. Signal generation: Define entry/exit rules
  3. Backtesting: Simulate strategy on historical data
  4. Analysis: Performance metrics, risk assessment

Common Pitfalls

Look-ahead bias: Using information not available at decision time.

Survivorship bias: Only testing on assets that survived.

Overfitting: Strategy performs well historically but fails live.

Transaction costs: Ignoring realistic slippage, commissions, impact.

Performance Metrics

Sharpe ratio: SR=μrfσSR = \frac{\mu - r_f}{\sigma}

Maximum drawdown: Largest peak-to-trough decline.

Profit factor: Gross profit / Gross loss.

Win rate: Percentage of profitable trades.

Risk Controls

Pre-Trade

  • Position limits
  • Order size limits
  • Price reasonability checks
  • Margin requirements

Real-Time

  • P&L limits (kill switch)
  • Message rate limits
  • Latency monitoring
  • Inventory limits

Post-Trade

  • Trade reconciliation
  • Performance attribution
  • Model validation

Programming Considerations

Building trading systems requires:

  • Low-latency architecture: Lock-free data structures, memory pre-allocation
  • Reliable messaging: Market data parsing, order management
  • State management: Position tracking, order lifecycle
  • Event-driven design: React to market events efficiently
  • Testing infrastructure: Simulation, replay, paper trading
  • Monitoring: Real-time dashboards, alerting

Languages: C++ for ultra-low latency; Python for research and slower strategies; Rust for safety-critical components.

ELI10 Explanation

Simple analogy for better understanding

Imagine you're playing a video game where you need to buy and sell virtual items as fast as possible. Algorithmic trading is like having a super-smart robot play this game for you, following rules you programmed. Some robots try to buy low and sell high really quickly (like finding deals at a garage sale before anyone else). Other robots help big investors buy huge amounts without pushing prices up, like slowly filling a swimming pool with a garden hose instead of dumping it all at once. The fastest robots can make decisions in less than a millionth of a second!

Self-Examination

Q1.

Explain the difference between TWAP and VWAP execution algorithms. When would you prefer each?

Q2.

What is market impact, and how does the square root law model relate execution size to expected price movement?

Q3.

Describe the setup for a pairs trading strategy. How do you identify suitable pairs and generate trading signals?

Q4.

What are the main risks in high-frequency market making? How do market makers manage inventory and adverse selection?

Q5.

List common backtesting pitfalls. How would you design a robust backtesting framework to minimize these issues?