Home/Concepts/Finance/Algorithmic Trading Basics

Algorithmic Trading Basics

Build and backtest simple trading strategies

⏱️ 24 min⚑ 9 interactions

1. Trading at the Speed of Light

In 2010, a single algorithmic trading error caused the "Flash Crash," wiping out $1 trillion in market value in minutes. Today, over 70% of US equity trades are executed by algorithms. These bots make split-second decisions using mathematical models, processing millions of data points per second.

πŸ€– Core Concept

Algorithmic trading uses computer programs to execute trades based on predefined rules. The three main types are: Momentum strategies (trend following), Mean reversion (betting on price corrections), and Arbitrage (exploiting price differences). Success requires backtesting, low latency, and rigorous risk management.

🎯 Interactive: Choose Trading Strategy

Sharpe Ratio
1.2
Max Drawdown
15%
Win Rate
55%
Trades/Year
45

2. Building a Moving Average Crossover Strategy

πŸŽ“ From Idea to Algorithm: Building Trading Logic

Moving Average Crossovers: The Hello World of Algo Trading

Moving average (MA) crossover strategies are the simplest trend-following systems. The logic: when a fast MA (e.g., 10-day) crosses ABOVE a slow MA (e.g., 50-day), BUY (trend turning up). When fast crosses BELOW slow, SELL (trend turning down).

MA Crossover Logic:
Golden Cross (BUY Signal) πŸ“ˆ
Condition:
IF (yesterday: Fast MA <= Slow MA) AND (today: Fast MA > Slow MA)
β†’ Enter LONG position
Example: 10-day MA crosses above 50-day MA on SPY at $450
Interpretation: Short-term momentum stronger than long-term trend
Action: Buy 100 shares, set stop-loss at 50-day MA ($445)
Historical win rate: ~55% in trending markets, ~40% in choppy markets
Death Cross (SELL Signal) πŸ“‰
Condition:
IF (yesterday: Fast MA >= Slow MA) AND (today: Fast MA < Slow MA)
β†’ Exit LONG position (or enter SHORT)
Example: 10-day MA crosses below 50-day MA on SPY at $455
Interpretation: Short-term momentum weakening, trend reversing
Action: Sell position, capture $5 profit ($455 - $450 entry)
Death crosses preceded 70% of major market corrections since 2000
Why this works (when it works): MAs smooth out price noise, revealing the underlying trend. Crossovers identify momentum shifts early. BUTβ€”they lag price (by design), so you miss the first 10-20% of moves and get whipsawed in sideways markets. It's NOT a holy grail, just a simple starting point.

Parameter Optimization: The Overfitting Trap

Should you use a 10/50 MA crossover? 5/20? 20/200? Optimization finds the best historical parametersβ€”but also creates overfitting: a strategy that perfectly fits past data but fails on new data. This is the #1 killer of algo strategies.

Optimization Results: SPY (2015-2020)
Fast/SlowTotal ReturnWin RateMax DDTrades
5 / 20+45%52%-18%38
10 / 50+38%58%-12%22
20 / 100+28%62%-9%12
⭐ 13 / 37+62%68%-7%28
50 / 200+18%55%-11%5
⚠️ The Overfitting Problem:
The 13/37 combo looks PERFECT: +62% return, 68% win rate, low drawdown! You're rich, right?
WRONG. Test it on 2020-2025 data:
13/37: -12% return (worst performer!)
10/50: +22% return (best performer)
Why? The 13/37 parameters fit random noise in 2015-2020 data, not real market structure. It was "curve-fitted" to past quirks that didn't repeat.
βœ… How to Avoid Overfitting:
β€’ Walk-forward analysis: Optimize on Year 1-3, test on Year 4, re-optimize, test Year 5, repeat
β€’ Out-of-sample testing: Keep 30% of data hidden until final test (never use it for optimization)
β€’ Simple parameters: Round numbers (10, 20, 50, 100, 200) are more robust than weird ones (13, 37, 83)
β€’ Reasonable performance: If backtest shows 80% win rate or 100%+ annual return, it's probably overfit!
Rule of thumb: Live performance = 50-70% of backtest performance (after costs, slippage, reality)
Professional approach: Use robust parameters (10/50, 20/100) that have been widely used for decades. If thousands of traders use them, they're harder to arbitrage away. Fancy optimized parameters might give you a slight edge for 6 months before decaying. Simplicity + consistency > complexity.

Backtesting: The Reality Check

Backtesting runs your strategy on historical data to see what WOULD have happened. But backtests lie! They don't include real-world friction: commissions, slippage, liquidity constraints, and execution delays.

Backtest vs Reality: What Gets Lost
Perfect Backtest (Unrealistic):
Strategy return:+50%/year
Win rate:65%
Sharpe ratio:2.1
Trades executed:100% at desired price
↓ Reality Tax ↓
Live Trading Reality:
Commissions (120 trades Γ— $1):-$120 (-0.12%)
Slippage (0.1% per trade):-12% total
Missed fills (10% of trades):-5% opportunity
Latency (50ms delay):-3% timing
ACTUAL return:+29.8%/year
ACTUAL Sharpe:1.2
From +50% backtest to +30% reality = 40% performance decay!
πŸ“Š Realistic Backtest Checklist:
βœ… Include commissions ($0.50-$5 per trade depending on broker)
βœ… Add slippage (0.05-0.2% per trade for liquid stocks, 0.5%+ for illiquid)
βœ… Model bid-ask spread (enter at ask, exit at bid = instant 0.1% loss)
βœ… Add latency delay (50-200ms for retail, 5ms for institutions)
βœ… Test across multiple market regimes (bull, bear, sideways, volatile)
βœ… Ensure enough liquidity (can't buy $1M of microcap at market price!)
If strategy survives all this and still makes 15-20%+ annually, you might have something real!
The 50% rule: Assume your live trading returns will be ~50% of backtest returns. Backtest shows +40%? Expect +20% live (still excellent!). Backtest shows +10%? Expect +5% live (barely worth the effort after taxes). This is why HFT needs 100%+ backtest returnsβ€”live they make 20-30% after costs, which is still great on billions of capital.

πŸ“Š Interactive: Strategy Parameters

10 days
30 days
Price
Fast MA (10)
Slow MA (30)
Total Trades
1
Win Rate
0.0%
Avg Return
0.00%
Signals
1

πŸ”„ Interactive: Backtesting Period

252 days (1.0 years)
πŸ’‘ Longer backtests = more reliable: Test across multiple market cycles. A strategy that works in bull markets might fail in bear markets. Minimum 3-5 years recommended.

3. Order Execution & Slippage

πŸŽ“ Market Microstructure: Where Profits Go to Die

The Three Order Types (And Why Each One Costs You)

Every algo strategy eventually asks: "How do I actually BUY this stock?" The answer determines whether your 20% backtest becomes 15% reality or -5% disaster. Order type is the tradeoff between speed (certainty of execution) and price (slippage cost).

Order Type Comparison:
1. Market Order (Speed > Price)
What it is:
"Buy NOW at whatever price is available"
How it executes:
Hits the best ask price on the order book instantly (or best bid for sells)
Pros:
βœ… Guaranteed execution
βœ… Instant (milliseconds)
βœ… Simple logic
Cons:
❌ Pay bid-ask spread (0.1%+)
❌ Slippage on large orders
❌ Worst price possible
Example: Stock bid $100.00, ask $100.10. Market buy order executes at $100.10 (you pay 0.1% spread). On $100K order, that's $100 lost instantly!
2. Limit Order (Price > Speed)
What it is:
"Buy ONLY if price reaches $X or better"
How it executes:
Sits on order book at your limit price, waits for seller to match you
Pros:
βœ… Control price (no slippage)
βœ… Can capture spread
βœ… Maker rebates (some venues)
Cons:
❌ May never fill (miss trade!)
❌ Partial fills possible
❌ Slower (seconds to hours)
Example: Stock at $100.10, you place limit buy $100.00. If price drops to $99.95, you buy at $100.00 (saved $0.10). But if price rallies to $102, you miss the trade entirely!
3. Stop Order (Trigger-Based)
What it is:
"If price hits $X, submit market/limit order"
How it executes:
Dormant until trigger price, then becomes market order (stop-loss) or limit order (stop-limit)
Pros:
βœ… Automated risk management
βœ… No monitoring needed
βœ… Catches breakouts
Cons:
❌ Slippage when triggered
❌ Can be "hunted" by HFTs
❌ Gap risk (trigger at $95, fill at $90!)
Example: Buy at $100, set stop-loss at $95. Stock gaps down to $92 overnight. Your stop triggers at market open but fills at $92 (-8% loss, not -5%!).
Pro strategy: Use limit orders for entries (wait for good price), market orders for urgent exits (get out NOW in crashes). HFT uses 99% limit orders (they provide liquidity, earn rebates). Retail uses 70% market orders (pay for convenience). That's one reason HFT is profitable!

Slippage: The Silent Killer

Slippage is the difference between expected price and execution price. It's invisible in backtests (assumes perfect fills) but brutal in live trading. On a 100-trade strategy, 0.1% average slippage = -10% annual return gone!

Sources of Slippage:
1. Bid-Ask Spread (Always There)
SPY (mega-liquid):0.01% spread
AAPL (large-cap):0.05% spread
Mid-cap stock:0.15% spread
Small-cap / illiquid:0.5-2% spread
Market orders pay the full spread. On 100 trades/month in mid-caps: 0.15% Γ— 100 = 15% annual cost!
2. Market Impact (Large Orders)
Scenario:
Order book: 100 shares @ $100.00, 200 @ $100.05, 500 @ $100.10
Your order: Buy 1,000 shares market
Execution:
β€’ 100 shares @ $100.00
β€’ 200 shares @ $100.05
β€’ 500 shares @ $100.10
β€’ 200 shares @ $100.15 (had to go deeper!)
Average fill: $100.096 (0.096% slippage from $100.00)
Rule: If your order is >1% of average daily volume, expect significant market impact (0.5-5% slippage)
3. Latency (Network + Processing Delay)
You see price: $100.00 β†’ Click BUY β†’ 50ms network β†’ 20ms broker β†’ 30ms exchange
Total 100ms delay. In that time, HFT moved price to $100.08!
HFT (1-5ms latency):0.01% slippage
Institutions (10-50ms):0.03% slippage
Retail (50-200ms):0.1% slippage
Slow internet (500ms+):0.5%+ slippage
This is why HFT firms co-locate servers at exchanges. 1ms advantage Γ— 1,000 trades/day = major edge.
πŸ“Š Total Slippage Calculator:
Example: Day trading mid-cap stocks (100 trades/month)
Bid-ask spread: 0.15% per trade
Market impact: 0.05% (small positions)
Latency slippage: 0.08% (retail connection)
= 0.28% per round-trip trade
Γ— 100 trades = 28% annual cost!
Your strategy needs 30%+ backtest returns just to break even after slippage! This is why 90% of active traders lose money.
Minimizing slippage: Trade liquid stocks (SPY, AAPL, MSFT have 0.01% spreads), use limit orders (capture spread instead of paying it), reduce trade frequency (100 trades/year not 100/month), use algo execution (TWAP/VWAP slice large orders), and NEVER market order on open/close (spreads widen 5-10Γ—!).

πŸ“‹ Interactive: Order Types

0.1%
Requested Price:$100.00
Executed Price:$100.02
Slippage:$0.023 (0.02%)
Execution Latency:50ms

βš™οΈ Interactive: Execution Algorithms

TWAP Strategy

Splits a large order into equal slices executed at regular intervals. Example: 10,000 shares over 10 minutes = 1,000 shares per minute.

⚑ Interactive: Latency & HFT

50ms
1ms (HFT)50ms (Retail)200ms (Slow)
1-5ms
HFT
Co-located servers
5-20ms
Low-Latency
Fiber optic
20-100ms
Retail
Standard brokers
100+ms
Slow
Disadvantaged
⚑ Speed advantage: At 50ms latency, you're fast enough for day trading. HFT firms pay millions for 1-2ms speed improvements through co-location and microwave networks.

4. Risk Management & Trading Frequency

πŸŽ“ The Frequency Paradox: More Trades β‰  More Profit

Trading Frequency Tiers: The Reality Behind the Speed

Algo trading spans from low-frequency (hold days/weeks, 10 trades/month) to high-frequency (hold seconds, 10,000 trades/day). Higher frequency requires exponentially more capital, infrastructure, and sophistication. Most successful retail traders stay low-frequency.

Frequency Tier Comparison:
Low Frequency (Swing Trading) πŸ“Š
Characteristics:
β€’ Hold time: 1-30 days
β€’ Trades: 5-50/month
β€’ Latency tolerance: 100ms+
β€’ Profit/trade: 1-5%
Requirements:
β€’ Capital: $10K-$100K
β€’ Infrastructure: Retail broker
β€’ Data: EOD or 1-min bars
β€’ Cost: $100/month
βœ… Advantages:
β€’ Low transaction costs (0.5-1% annual)
β€’ Manageable with day job
β€’ Less infrastructure needed
β€’ Captures real trends (not noise)
❌ Disadvantages:
β€’ Overnight risk (gaps)
β€’ Lower Sharpe ratio (0.5-1.5)
β€’ Emotional discipline needed
Example: 20-trade/month MA crossover strategy. $50K account, 1% risk/trade = $500 risk. With 55% win rate and 2:1 R:R, expect 15-25% annual return after costs.
Medium Frequency (Day Trading) ⚑
Characteristics:
β€’ Hold time: Minutes to hours
β€’ Trades: 20-200/day
β€’ Latency tolerance: 20-100ms
β€’ Profit/trade: 0.1-0.5%
Requirements:
β€’ Capital: $50K-$500K (PDT rule!)
β€’ Infrastructure: DMA broker
β€’ Data: Tick data, L2 quotes
β€’ Cost: $1K-$5K/month
βœ… Advantages:
β€’ No overnight risk (flat by close)
β€’ More opportunities (50-100 trades/day)
β€’ Higher Sharpe potential (1.5-2.5)
❌ Disadvantages:
β€’ Transaction costs 5-10% annual
β€’ Full-time commitment required
β€’ PDT rule ($25K minimum)
β€’ High stress, burnout risk
Example: 50-trade/day scalping strategy. $100K account, need <$2 commission/trade and 0.05% slippage to be profitable. Win rate 52%, avg 0.15% per winner. Gross 30%, net 20% after costs.
High Frequency (HFT) πŸš€
Characteristics:
β€’ Hold time: Milliseconds to seconds
β€’ Trades: 1K-1M+/day
β€’ Latency tolerance: 1-10ms
β€’ Profit/trade: 0.001-0.01%
Requirements:
β€’ Capital: $1M-$100M+
β€’ Infrastructure: Co-location
β€’ Data: Direct exchange feed
β€’ Cost: $50K-$500K/month
βœ… Advantages:
β€’ Massive scale (billions traded/day)
β€’ High Sharpe (2.5-4.0+)
β€’ Market-neutral (no overnight risk)
β€’ Statistical edge vs slower traders
❌ Disadvantages:
β€’ Requires PhDs + massive capital
β€’ Arms race (speed constantly decaying)
β€’ Regulatory scrutiny
β€’ Alpha decay 30%+/year
Example: Market-making on SPY. 100K trades/day, $0.01 profit/trade = $1,000/day gross. But costs: $100K/month infrastructure + $50K/month salaries. Need $5B volume/day to be profitable!
Reality check: 95% of retail traders should stick to low-frequency. Medium requires $50K+ and full-time focus. HFT is unreachable (you're competing with Citadel, Virtu, Jane Street with billions in capital). The "trade more = earn more" myth kills accountsβ€”higher frequency = higher costs that eat all profits unless you have infrastructure + edge.

Cost Structure: Why Frequency Matters

Every trade has fixed costs (commissions) and variable costs (slippage). Higher frequency multiplies these costs exponentially. A 0.1% cost/trade strategy making 10 trades/month = -1.2% annual cost (manageable). Same strategy making 1,000 trades/month = -120% annual cost (impossible!).

Annual Cost Analysis by Frequency:
Cost ComponentLow (10 trades/mo)Med (100 trades/mo)High (10K trades/mo)
Commissions-0.1%-0.6%-5%
Slippage-0.5%-5%-30%
Data Feeds-0.1%-1%-5%
Infrastructure-0.1%-2%-10%
Opportunity Cost-0.2%-3%-15%
TOTAL COST-1.0%-11.6%-65%
⚠️ The High-Frequency Trap:
HFT strategy needs 65%+ gross returns just to BREAK EVEN after costs! Here's why most fail:
β€’ Slippage scales with volume: 10K trades/month = 20K trade sides = massive market impact
β€’ Infrastructure costs: Co-location $10K/month, data feeds $20K/month, servers $15K/month
β€’ Opportunity cost: Could've earned 10% risk-free in bonds instead of stressing over microseconds
Unless you're Citadel with billions and PhDs, stick to low-frequency!
The sweet spot: Low-frequency strategies (10-50 trades/month) have manageable 1-2% annual costs, leaving room for 15-25% net returns. Medium-frequency (100 trades/month) needs exceptional edge to overcome 10%+ costs. High-frequency needs institutional resources. Don't fight the mathβ€”trade less, earn more!

Position Sizing: Risk of Ruin in Algo Trading

Algos don't get emotionalβ€”but they can still blow up accounts with bad position sizing. The risk of ruin formula shows how many consecutive losses wipe you out. With 5% risk/trade, you're broke in 14 losses. With 1%, you can survive 70 losses!

Risk of Ruin Analysis:
Formula: Losses to 50% Drawdown
N = log(0.5) / log(1 - Risk%)
Where N = consecutive losses needed to lose 50% of account
0.5% risk/trade:138 losses to ruin
1% risk/trade:69 losses to ruin
2% risk/trade:35 losses to ruin
5% risk/trade:14 losses to ruin
10% risk/trade:7 losses to ruin πŸ’€
⚠️ Probability of Consecutive Losses:
Even with 60% win rate strategy (pretty good!), probability of losing streaks:
5 losses in a row:1.0% chance (happens!)
7 losses in a row:0.16% chance (rare but possible)
10 losses in a row:0.01% chance (unlikely but not impossible)
With 10% risk/trade, just 7 losses = account blown. That 0.16% chance WILL happen eventually!
βœ… Professional Position Sizing Rules:
β€’ Retail traders (small accounts): Use 0.5-1% risk per trade max
β€’ Full-time algo traders: Use 1-2% risk per trade max
β€’ Institutions (diversified): Can use 2-3% risk per strategy (but run 10+ uncorrelated strategies)
Golden rule: Size so that 20 consecutive losses = 20% drawdown (recoverable). For 60% win rate, that's ~1% risk/trade.
Kelly Criterion adjustment: Pure Kelly often suggests 5-10% position sizes (way too aggressive!). Use Quarter Kelly or Half Kelly for algo trading. If Kelly says 8%, use 2% (quarter) or 4% (half). This massively reduces drawdowns while keeping 70-90% of Kelly growth. Survival > optimization!

πŸ”„ Interactive: Trading Frequency

Commission Impact
2%
Infrastructure Cost
$1K/mo
Avg Holding Time
Hours
Complexity
Medium

🎲 Interactive: Position Sizing

1%
Consecutive Losses to Ruin (50% drawdown)
69
losing trades in a row
Ultra Safe (0.5%)
139 losses = 50% drawdown
139
Conservative (1%)
69 losses = 50% drawdown
69
Moderate (2%)
35 losses = 50% drawdown
35
Aggressive (5%)
14 losses = 50% drawdown
14

πŸ“Š Interactive: Strategy Performance

StrategyWin RateSharpeMax DDComplexity
Momentum55%1.215%Low
Mean Reversion60%0.912%Medium
Arbitrage85%2.15%High
Market Making52%1.88%Extreme
Statistical Arb58%1.510%High

5. Key Takeaways

πŸ”„

Backtest Everything

Never trade a strategy without backtesting it on at least 3-5 years of data across multiple market conditions. A strategy that works in bull markets might crater in bear markets. Out-of-sample testing is crucial.

πŸ’Έ

Transaction Costs Kill Returns

Commissions, slippage, and market impact can turn a profitable backtest into a losing live strategy. High-frequency strategies need commissions <$0.001/share. Include realistic costs in backtests.

⚑

Speed = Edge in HFT

High-frequency trading requires sub-5ms latency. Firms pay millions for co-location at exchanges and microwave networks between cities. Retail traders can't compete at this speedβ€”focus on slower strategies.

πŸ“Š

Overfitting Destroys Strategies

Optimizing parameters on historical data can create a strategy that perfectly fits the past but fails in live trading. Use walk-forward analysis and keep strategies simple with few parameters.

πŸ›‘οΈ

Risk Management is Non-Negotiable

Even with 60% win rate, risking 5% per trade = ruin in 14 losses. Use 0.5-2% risk per trade maximum. Implement circuit breakers to stop trading after X losses. One bad day shouldn't wipe out your account.

🎯

Alpha Decays Quickly

Profitable strategies attract competition until returns decline. The average algo strategy's edge decays 20-30% per year as others discover it. Continuously research and adapt or returns will vanish.