
Algorithmic Trading Strategies and Backtesting
Automating trading decisions with code and historical data
The Day the Machines Took Over for 36 Minutes
On May 6, 2010, at 2:32 p.m. Eastern, the U.S. stock market began to fall apart. In the next 15 minutes the Dow Jones dropped almost 1,000 points — the largest intraday point swing in its history at the time. Accenture briefly traded at one cent. Apple briefly traded at $100,000. Then, just as violently, the market snapped back. By 3:08 p.m. most of the damage had reversed. Nearly a trillion dollars in value had evaporated and rematerialized in barely half an hour.
No human did this. Algorithms did. A single large sell order, executed by an automated program that fired without checking for available buyers, cascaded into a chain reaction of other algorithms — market makers pulling quotes, momentum bots piling onto the slide, high-frequency systems trading hot-potato with each other thousands of times a second. The "Flash Crash" became the textbook lesson that machine trading is now the market's nervous system, not a side feature.
Today, the overwhelming majority of volume on major equity and crypto venues is placed by software, not by a person clicking "buy." Understanding algorithmic trading is no longer optional for a serious trader — it's literacy. This lesson takes you from what an algorithm actually is, to how strategies are built and tested, to the specific ways backtests lie to the people who build them.
What Algorithmic Trading Actually Is
Strip away the mystique and algorithmic trading is just placing orders by rule instead of by gut. You write down conditions — "if the 50-period moving average crosses above the 200-period, buy" — and a program watches the market and acts the instant those conditions are met, with no hesitation, no fear, and no lunch break.
This is older than crypto. The NYSE's DOT system routed orders electronically back in the 1970s. What changed is scale and speed: modern systems react in microseconds and manage thousands of instruments at once. But the core idea is unchanged — a human decides the logic; a machine executes it.
The single most important distinction in the field is between two completely different jobs that algorithms do. Confusing them is how beginners optimize the wrong thing:
- Execution algorithms answer "how do I trade an order I've already decided on, without moving the price against myself?" If you need to buy 500 BTC, dumping it as one market order would spike the price. An execution algo slices it into small pieces over time. TWAP and VWAP (below) live here.
- Alpha algorithms answer "what should I buy or sell, and when?" These are the strategies that try to make money — momentum, mean reversion, arbitrage. This is where backtesting and risk management dominate the work.
The Anatomy of a Trading Algorithm
Every alpha strategy, no matter how fancy, is built from the same four parts. If you can describe a trading idea in these terms, you can code it. If you can't, you don't actually have a strategy yet — you have a vibe.
- The signal (entry rule). The condition that triggers a trade. "RSI drops below 30," "price breaks above the 20-day high," "the spread between two coins exceeds two standard deviations." This is the hypothesis about why the market is mispriced.
- The exit rule. Equally important and usually neglected. When do you take profit? When do you cut a loss? A strategy with a brilliant entry and no exit plan is a coin flip with extra steps.
- Position sizing. How much capital goes into each trade. Risking 2% of your account per trade survives a losing streak; risking 50% does not. Sizing, not entries, is what separates traders who last from traders who blow up.
- Risk controls. The hard limits that override everything else — maximum drawdown, maximum open positions, a daily loss cap, and a kill switch that flattens everything when the world goes sideways.
Notice that only one of these four is about predicting the market. The other three are about surviving being wrong — because you will be wrong, constantly, and the goal of a robust algorithm is to be wrong cheaply and right expensively.
The Major Strategy Families
Most algorithmic strategies are variations on a handful of timeless ideas. Each one is a different bet about how prices behave — and crucially, each one works in some market regimes and dies in others.
- Momentum / trend following. Buys strength, sells weakness, on the bet that what's been going up keeps going up. Jegadeesh and Titman documented this effect in U.S. equities back in 1993, and crypto has shown ferocious trends (the 2020–2021 bull run) — but also brutal whipsaws that shred trend systems in choppy, sideways markets.
- Mean reversion. The opposite bet: that prices stretched far from their average will snap back. Buys dips, sells rips. Profitable in range-bound markets, lethal in a strong trend, because "oversold" can stay oversold all the way down.
- Arbitrage. Exploits the same asset trading at two different prices — across exchanges, or between spot and a perpetual future. In theory risk-free; in practice a race where fees, latency, and the risk of one leg not filling eat most of the apparent edge.
- Market making. Continuously quotes both a buy and a sell price and earns the spread between them, while carefully managing the inventory it accumulates. This is the strategy that the Flash Crash punished — when market makers pulled their quotes, liquidity vanished.
The hard truth is that no single family wins forever. A momentum bot that printed money in 2021 likely bled through 2022's grind. Knowing which regime you're in matters more than the elegance of any one strategy — and no backtest on a single regime can tell you how the strategy behaves in the others.
Execution: Getting In Without Moving the Market
Suppose your alpha model says "buy 1,000 ETH." On a thin order book, slamming that in as one market order walks the price up against you — your average fill is far worse than the price you saw. The art of execution algorithms is spending a large order quietly. Two benchmarks dominate:
- TWAP (Time-Weighted Average Price) slices the order into equal pieces released at steady intervals — say, 1% every minute for 100 minutes. It ignores volume entirely, which makes it simple and predictable. Best for quiet markets and illiquid assets, where you just want to trickle in without leaving a footprint.
- VWAP (Volume-Weighted Average Price) trades more when the market is busy and less when it's quiet, matching the day's volume profile. Because it leans into natural liquidity, it hides better in active markets and is the standard benchmark institutions grade their execution against — beating VWAP means you got filled better than the average participant that day.
This matters even if you never write an execution algo, because slippage — the gap between the price you expected and the price you got — is one of the silent killers of strategy profitability. A backtest that assumes you always fill at the last printed price is lying to you, and we're about to see exactly how.
Backtesting: Asking History the Right Way
Backtesting is simulating a strategy on historical data to see how it would have performed before you risk a dollar. Done honestly, it's the single most valuable tool in algorithmic trading. Done carelessly, it's an elaborate machine for generating false confidence.
There are two flavors. Manual backtesting means scrolling back through a chart and recording what your rules would have done at each point — slow, but it builds genuine intuition, and you only need a spreadsheet. Automated backtesting runs your coded rules across years of data in seconds; Python libraries like Backtrader and VectorBT are common, as are platform tools like TradingView's Strategy Tester.
A backtest is only as trustworthy as its assumptions. Four things separate a real backtest from a fairy tale:
- Realistic costs. Bake in fees (crypto maker/taker fees commonly run 0.04%–0.1% per trade), the bid-ask spread, and funding on perps. A strategy showing 20% gross can easily become 8% net — or negative — once costs land.
- Realistic slippage. Assume you fill slightly worse than the quoted price, especially on large or fast orders. A few ticks of slippage per trade compounds savagely over thousands of trades.
- No lookahead. Your strategy at 2:00 p.m. may only use data that existed at 2:00 p.m. Accidentally using the day's closing price to make a decision at the open is the most common silent bug in all of backtesting.
- Enough trades. Ten profitable trades prove nothing — that's luck. You want a sample large enough that a few lucky winners can't carry the whole result.
How Backtests Lie: Overfitting and the Hidden Biases
The reason most backtested strategies fail in live trading isn't bad luck — it's that the backtest was quietly rigged. Usually by the person who built it, without realizing it. Here are the ways history fools you:
- Overfitting (curve-fitting). The big one. You keep tweaking parameters until the equity curve looks gorgeous — but a strategy with twenty hand-tuned knobs and a buttery-smooth curve has memorized the past, not learned a pattern. Red flag: change a lookback from 20 to 21 and performance collapses. If your edge depends on "RSI period 17.3," you've fitted noise, not signal.
- Lookahead bias. Using information in the test that wasn't available at decision time — future prices, restated fundamentals, a too-late timestamp. It makes a useless strategy look psychic.
- Survivorship bias. Testing only on the coins that still exist today. Every token that went to zero is silently deleted from your dataset, so your backtest "buys the dip" on assets that, by construction, always recovered. In real time, plenty don't — they delist and vanish.
- Ignored frictions. Zero fees, zero slippage, infinite liquidity, instant fills. Each unrealistic assumption inflates results; stacked together they manufacture a strategy that only ever existed in the simulation.
The professional defense against overfitting is walk-forward analysis: fit your parameters on one window of history, test on the next window, then roll both windows forward and repeat. Because the strategy is always validated on data it was never tuned on, walk-forward approximates how it would actually behave deployed — chasing a market that keeps changing. The diagram below shows the rolling logic.
From Backtest to Live: Where Reality Bites
A clean backtest is a hypothesis, not a paycheck. The path to live capital has guardrails, and skipping them is how good strategies become expensive lessons.
Paper trade first. Run the strategy live against real market data but with fake money. If paper results diverge wildly from your backtest, assume the bug is in your code or your assumptions — not that the market is "behaving strangely." Reconcile the difference before risking a cent.
Engineer for failure, not just for profit. Exchanges go down, APIs return errors, and a flood of requests gets you a 429 Too Many Requests response — back off exponentially when that happens. Build a heartbeat alert that screams if the bot stops responding, and a kill switch that cancels open orders and flattens positions on command. The Flash Crash happened in part because automated systems had no brakes.
Size up slowly. Start small. Confirm that live fills, fees, and slippage roughly match what you modeled before adding capital.


