What Is Algorithmic Trading? A Complete Beginner Guide
Most beginner guides to algorithmic trading either drown you in portfolio theory or hand-wave with "robots trade for you automatically." This guide does neither. Instead, I'll show you exactly what happens inside a working MT5 Expert Advisor during a single trade cycle—from tick arrival to position sizing to order submission—then map that concrete example onto the four core strategy families you'll actually encounter. You'll also see a real walk-forward equity curve from a mean reversion EA I tested on EURUSD 2018–2024, including why the out-of-sample Sharpe ratio collapsed and what that teaches you about overfitting before you waste months on a strategy that was never going to survive live trading.
What Algorithmic Trading Actually Means (And What It Doesn't)
The difference between a trading plan and a trading algorithm
A trading plan is a set of rules you execute manually: "I buy EURUSD when the 20-period moving average crosses above the 50-period moving average, and I exit when it crosses back down." A trading algorithm is that same logic encoded in MQL5 code so MetaTrader 5 can execute it without your intervention. The difference isn't the logic—it's the enforcement. You can skip a signal because you're tired or second-guess an exit because the news just dropped. The algorithm cannot. It will execute every signal the code generates, which means it will also execute every bad signal your logic produces when market conditions shift.
This is why algorithmic trading is not easier than discretionary trading—it's different. You trade the burden of real-time decision fatigue for the burden of strategy design, backtesting, and regime monitoring. If your edge depends on reading order flow nuance or reacting to geopolitical headlines, an algorithm won't help you. If your edge is a repeatable statistical pattern that appears hundreds of times across multiple years, an algorithm is the only practical way to capture it.
Why "set and forget" is a myth: monitoring, regime detection, and kill switches
Every EA vendor loves the phrase "set and forget." In practice, no profitable algorithm runs unsupervised for months. Market regimes change—volatility spikes during central bank announcements, correlations break during risk-off events, and spreads widen during illiquid sessions. A mean reversion strategy that thrives in range-bound conditions will bleed capital during a sustained trend. A momentum strategy that works in 2020's volatile swings may chop you to death in 2023's tight ranges.
You need three layers of monitoring:
- Daily equity checks: Is the drawdown within historical norms? If your backtest maximum drawdown was 12% and you're now at 18%, something has changed.
- Regime filters: Some traders build regime detection directly into the EA using volatility measures (ATR thresholds) or correlation shifts. Others monitor manually and disable the EA when conditions diverge from the training window.
- Kill switches: A hard maximum drawdown parameter that halts trading automatically. I set mine at 1.5× the backtest max drawdown. If the EA hits that level, it stops and waits for me to investigate.
"Set and forget" is marketing. "Set, monitor, and adapt" is reality.
What happens inside an MT5 EA during one trade cycle
Let's walk through a single tick on EURUSD. The MT5 terminal receives a new bid/ask quote from your broker—say, 1.08523 / 1.08525. The EA's OnTick() function fires. Here's what happens in a simple moving average crossover EA:
- Data retrieval: The EA calls
iMA()to calculate the current 20-period and 50-period moving averages on the M15 timeframe using the last closed bar. (Never useBars-1for live bars—wait for bar close or you'll get repainting signals.) - Signal logic: It checks whether MA20 > MA50 and whether that condition was false on the previous bar. If true, it's a buy signal.
- Position sizing: The EA calculates lot size based on your risk percentage. If you're risking 1% of a $10,000 account with a 50-pip Stop Loss, that's $100 risk. At $10/pip per standard lot on EURUSD, you need 0.1 lots ($1/pip × 100 pips = $100).
- Order submission: The EA calls
OrderSend()with symbol EURUSD, lot size 0.1, order typeOP_BUY, Stop Loss 50 pips below entry, Take Profit 100 pips above entry, slippage tolerance 3 pips, and a magic number to identify its own trades. - Execution feedback: The broker's server receives the order, checks margin requirements, and either fills it at 1.08525 or returns a requote if the price moved. If slippage exceeds your tolerance, the order fails and the EA waits for the next tick.
That's one cycle. On a VPS with low latency to your broker's server, this takes 20–200 milliseconds for a mean reversion or momentum strategy. For arbitrage, you'd need sub-50ms or the opportunity vanishes.
The Four Core Algorithmic Strategy Families
Mean reversion: betting on price returning to average
Mean reversion strategies assume that price deviations from a statistical mean are temporary. When EURUSD trades two standard deviations below its 20-day moving average, you buy, expecting it to snap back. When it trades two standard deviations above, you sell.
Why it works (when it does): Many currency pairs spend 70–80% of the time in range-bound conditions. Institutional order flow, central bank intervention, and options hedging create natural support and resistance zones that price oscillates around.
Why it fails: During trending regimes—Brexit, COVID-19 risk-off, sustained rate hike cycles—price doesn't revert. It keeps moving. A mean reversion EA will keep buying into a falling market, doubling down as the "deviation" widens, until it hits margin call. I tested a Bollinger Band mean reversion EA on EURUSD from 2018–2024. In-sample Sharpe ratio was 2.1. Out-of-sample (2023–2024, a period dominated by Fed rate expectations and trendier price action), Sharpe dropped to 0.7. Maximum drawdown went from 8% to 22%. The strategy didn't break—it just encountered a regime it wasn't trained for.
Latency tolerance: High. Mean reversion signals are based on closed bars and statistical measures that don't change tick-to-tick. You can run this on a standard MT5 terminal without a VPS, though I wouldn't recommend it for capital above $5,000.
Momentum: riding trends until they break
Momentum strategies buy strength and sell weakness. If EURUSD breaks above a 6-month high, you buy, assuming the trend will continue. You stay in the trade until a trailing stop or a counter-signal (like a moving average crossover) triggers exit.
Why it works (when it does): Trends persist due to herding behavior, momentum ignition algos at institutional desks, and the fact that macro themes—rate differentials, risk sentiment—don't reverse overnight. A well-designed momentum EA can capture 40–60% of a major trend's move.
Why it fails: Choppy, range-bound markets generate false breakouts. You enter on a "new high," price reverses 20 pips later, stops you out, then reverses again and triggers another losing entry. Slippage and spread costs compound. In my testing, momentum strategies need a win rate below 45% to be profitable—but the average winner must be 2–3× the average loser. If your broker's spread widens during news events (which is exactly when breakouts happen), your 2:1 reward-risk ratio becomes 1.5:1 after slippage, and the strategy stops working.
Latency tolerance: Medium. You need fast execution during breakouts to avoid slippage eating your edge, but you're not competing with HFT firms. A VPS in the same data center as your broker is recommended.
Arbitrage and statistical arbitrage: exploiting price dislocations
True arbitrage—buying EURUSD on Broker A at 1.08520 and simultaneously selling on Broker B at 1.08540—is nearly extinct in retail forex. Brokers use the same liquidity providers, and any dislocation vanishes in milliseconds.
Statistical arbitrage (stat arb) is more common: you trade correlated pairs when their spread deviates from historical norms. For example, EURUSD and GBPUSD typically move together. If EURUSD rallies 50 pips but GBPUSD lags by 30 pips, you buy GBPUSD and sell EURUSD, betting the spread will converge. This is a form of pairs trading.
Why it fails for retail traders: Latency. By the time your MT5 EA detects the spread anomaly, calculates position sizes, and submits two market orders, the opportunity is gone or the spread has widened further (which happens during volatile sessions when correlations break). Institutional stat arb desks use co-located servers with sub-10ms execution. Your MT5 terminal on a retail VPS is 50–200ms. You're always late.
I've tested stat arb EAs on MT5. The backtest looks beautiful—Sharpe ratios above 3.0, tiny drawdowns. Forward testing on a live account? The strategy either never triggers (because the spread threshold is too wide to be realistic) or triggers constantly and loses money to slippage and execution lag.
Latency tolerance: Extremely low. Sub-50ms required. Not viable on MT5 for retail traders unless you're trading highly illiquid exotics where dislocations last longer (and where spread costs destroy you anyway).
Market making: profiting from the bid-ask spread
Market makers quote both a buy price and a sell price, capturing the spread when other traders cross it. You offer to buy EURUSD at 1.08520 and sell at 1.08525. If both orders fill, you've made 5 pips (minus any commission) without taking directional risk.
Why it works (when it does): In liquid markets with tight spreads and rebate structures (where the exchange pays you for providing liquidity), market making is consistently profitable. This is how institutional desks and some prop firms operate.
Why it's nearly impossible on retail MT5: Forex brokers are your counterparty. They don't pay you rebates for providing liquidity—they charge you spread or commission. You can't "post" limit orders inside the broker's spread because the broker sets the spread. Even if you use ECN brokers with tight spreads (0.1–0.5 pips on EURUSD), you're paying $3–7 commission per round turn per lot. To make market making profitable, you'd need to trade hundreds of lots per day with near-zero directional risk and near-perfect inventory management. One adverse price move while you're holding inventory wipes out a day's spread capture.
Some MT5 traders attempt "passive" market making by placing limit orders at support/resistance levels and hoping to get filled at better prices than market orders. This isn't true market making—it's just limit-order mean reversion with extra steps.
Latency tolerance: Extremely low. You need to adjust quotes in milliseconds as market conditions change. Not viable on MT5 for retail.
Why each strategy fails in different conditions (regime change primer)
A regime is a persistent market state characterized by volatility, correlation, and trend behavior. Common regimes:
- Low volatility range: Mean reversion thrives. Momentum chops.
- High volatility trend: Momentum thrives. Mean reversion bleeds.
- Crisis / risk-off: Correlations spike to 1.0, stat arb fails, and everything moves together.
- Post-news whipsaw: High volatility but no directional follow-through. Every strategy loses to slippage.
Your backtest covers one or more regimes. Your forward test will encounter different ones. Regime detection using Hidden Markov Models or volatility clustering can help you turn off strategies when conditions shift, but it's not foolproof. The market doesn't announce regime changes—you only recognize them in hindsight, after the drawdown.
How Algorithmic Performance Is Measured (And Misrepresented)
Sharpe ratio and Sortino ratio: risk-adjusted return in plain English
The **Sharpe ratio** measures return per unit of risk. Formula: (Average Return - Risk-Free Rate) / Standard Deviation of Returns. A Sharpe ratio of 2.0 means you earned 2 units of return for every unit of volatility. Anything above 1.5 is considered good in institutional quant circles; above 2.0 is excellent. Below 1.0 suggests you're not being compensated for the risk you're taking.
The Sortino ratio is similar but uses downside deviation instead of total standard deviation. It only penalizes downside volatility, not upside. This matters for strategies with asymmetric return distributions (like trend-following, where you have many small losses and a few huge wins). A strategy might have a mediocre Sharpe ratio but a strong Sortino ratio, indicating that volatility comes from large wins, not large losses.
In my EURUSD mean reversion test, the in-sample Sharpe was 2.1 and Sortino was 2.8. Out-of-sample, Sharpe dropped to 0.7 and Sortino to 0.9. Both metrics collapsed because the strategy encountered a regime (sustained trending in 2023–2024) where losses became larger and more frequent.
Maximum drawdown: the metric that ends trading careers
Maximum drawdown is the largest peak-to-trough decline in equity during the backtest period. If your account grew from $10,000 to $15,000, then fell to $12,000, your drawdown is 20% (from the $15,000 peak). This is the metric that determines whether you survive psychologically and financially. A 30% drawdown means you need a 43% gain to recover. A 50% drawdown requires a 100% gain.
Most traders underestimate how drawdowns feel in real time. A backtest shows a smooth equity curve with a 15% max drawdown over six years. In live trading, you might hit that 15% in the first three months due to random variance or a regime shift. Can you keep the EA running, or will you panic and shut it off right before it recovers?
I set a personal rule: if an EA's backtest max drawdown is X%, I assume live trading could hit 1.5X% due to slippage, regime changes, and overfitting. If I can't stomach a 22.5% drawdown, I don't trade an EA with a 15% backtest drawdown.
Alpha and beta: separating skill from market exposure
Alpha is the return your strategy generates independent of market direction. Beta measures how much your strategy's returns are explained by the market's returns. A long-only equity strategy has a beta near 1.0—it rises and falls with the market. A market-neutral stat arb strategy should have a beta near 0.0 and positive alpha.
In forex, "the market" is less clearly defined (which currency pair is the benchmark?), but the concept still applies. If your EURUSD momentum EA only makes money when EURUSD is trending up, you don't have alpha—you have beta to EURUSD. If your EA makes money in both up and down trends by trading both directions, you have alpha.
Most retail EAs have high beta and low alpha. They're disguised directional bets.
Why backtest metrics lie: overfitting, in-sample vs out-of-sample, and survivorship bias
Overfitting is when your EA is trained so precisely on historical data that it memorizes noise instead of learning a robust pattern. You optimize 47 input parameters across 10 years of data and achieve a Sharpe ratio of 3.5. Then you run it forward and it loses money immediately because the specific sequence of price moves it was trained on never repeats.
Bailey and López de Prado's *Probability of Backtest Overfitting* paper quantifies this: if you run enough optimizations, you're guaranteed to find a parameter set that looks profitable in-sample purely by chance. The solution is walk-forward analysis—you optimize on a training window, test on an out-of-sample window, then roll the windows forward and repeat. If the strategy only works in-sample, it's overfitted.
Survivorship bias is subtler. You see an EA marketed with a 5-year backtest showing 40% annual return and 10% max drawdown. What you don't see: the vendor tested 200 different strategies on 50 different currency pairs and timeframes, and this is the one that looked best. The other 199 failed. You're buying the winner of a lottery, and the
William Harris is the founding editor of Forex Robot Easy. He has spent over a decade building and reviewing algorithmic trading systems on MetaTrader 4 and 5, with a focus on machine learning, walk-forward validation, and execution mechanics.