Why Build Custom Expert Advisors?

Retail traders lose money primarily due to two factors: emotional decision-making and inconsistent strategy execution. An Expert Advisor (EA) eliminates both. Once coded and deployed, an EA executes its strategy with perfect discipline — no hesitation on entries, no holding losing trades out of hope, no deviation from risk parameters regardless of market conditions.

MetaTrader 5 with MQL5 is the dominant platform for EA development, covering forex, CFDs, commodities, and indices. Whatever the strategy, broker choice matters: a well-regulated broker with raw-spread ECN execution is essential, because EA results are extremely sensitive to trading costs.

The EA Development Pipeline

01
Strategy Design & Edge Identification

Define the trading hypothesis: what market inefficiency does this EA exploit? Without a genuine statistical edge, no amount of code quality or optimisation will produce a profitable EA.

02
MQL5 Implementation

Code the strategy in MQL5 — entry/exit logic, order management, position sizing, and risk controls. Modular architecture critical for testability and future modification.

03
Backtesting & Validation

Run Strategy Tester against historical data. Verify results across multiple time periods and market regimes. Check for curve fitting and overfitting.

04
Optimisation & Forward Testing

Optimise parameters within defined ranges using genetic algorithms. Forward-test on out-of-sample data. Verify Walk-Forward Analysis consistency.

05
Demo Deployment

Run EA on a demo account with identical parameters for minimum 4–8 weeks. Verify live execution matches backtest behaviour: fills, slippage, swap costs.

06
Live Deployment & Monitoring

Go live with conservative sizing. Monitor in real-time. Establish drawdown circuit-breakers. Review performance weekly. Adjust only when statistically significant evidence warrants it.

Phase 1: Strategy Design and Edge Identification

The most important work happens before a single line of MQL5 is written. A trading edge is a systematic pattern in price data that, when exploited consistently, produces positive expectancy — meaning the average profit per trade is positive across a large sample.

Common edge categories that form the basis of robust EA strategies:

  • Trend following — Markets exhibit autocorrelation on certain timeframes: a move in one direction is slightly more likely to continue than to reverse. Moving average crossovers, Donchian channel breakouts, and momentum-based entries exploit this.
  • Mean reversion — Highly liquid markets (particularly forex pairs) tend to revert to equilibrium after extended moves. Bollinger Band mean-reversion, RSI extremes, and VWAP reversion strategies capture this.
  • Volatility breakouts — Price consolidation followed by a breakout often leads to directional follow-through. ATR-based breakout systems and opening range breakout strategies exploit this dynamic.
  • Session-based patterns — The London open, New York open, and Asian session handoff create predictable liquidity patterns. EAs targeting specific session dynamics (particularly the London-NY overlap) exploit institutional order flow patterns.
INF Rule #1

Never optimise first. Validate the hypothesis on raw, unoptimised parameters across a long historical period. If the unoptimised strategy has positive expectancy, optimisation refines a genuine edge. If it doesn't, optimisation creates a curve-fitted illusion that fails in live trading.

Phase 2: MQL5 Implementation

EA Structure in MQL5

Every MQL5 EA has the same three core event handlers. Understanding their execution order is fundamental to writing reliable EAs:

//+------------------------------------------------------------------+
// INF EA Template — Core Structure                                  
//+------------------------------------------------------------------+

// Input parameters — exposed in MT5 UI
input double RiskPercent     = 1.0;   // Risk per trade (%)
input int    FastMA_Period   = 20;    // Fast MA period
input int    SlowMA_Period   = 50;    // Slow MA period
input int    ATR_Period      = 14;    // ATR for SL calculation
input double ATR_Multiplier  = 2.0;   // SL = ATR × multiplier

// OnInit: runs once when EA is loaded or restarted
int OnInit() {
   // Validate parameters, create indicator handles
   return(INIT_SUCCEEDED);
}

// OnTick: runs on every new price tick — main logic loop
void OnTick() {
   // 1. Check for new bar (avoid re-processing same bar)
   if(!IsNewBar()) return;

   // 2. Get current indicator values
   // 3. Check entry conditions
   // 4. Check exit conditions
   // 5. Manage open positions (trailing stop, partial close)
}

// OnDeinit: cleanup when EA is removed
void OnDeinit(const int reason) {
   // Release indicator handles, clean up resources
}

Position Sizing: The Most Critical Function

Position sizing determines how many lots to trade based on the account balance, risk percentage, stop-loss distance, and instrument pip value. This is the single function that most directly determines whether an EA survives or blows an account:

// Risk-based position sizing — standard INF implementation
double CalculateLotSize(double stopLossPips) {
   double accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
   double riskAmount     = accountBalance * (RiskPercent / 100.0);
   double pipValue       = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tickSize       = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double lotSize        = riskAmount / (stopLossPips * pipValue / tickSize);

   // Normalise to broker's lot step requirements
   double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   lotSize = MathFloor(lotSize / lotStep) * lotStep;

   // Clamp within broker min/max lot constraints
   double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   return MathMax(minLot, MathMin(maxLot, lotSize));
}

Phase 3: Backtesting Methodology

MetaTrader 5's Strategy Tester is one of the most capable backtesting environments available. It supports tick-by-tick simulation using real historical tick data — critical for accurately modelling spread costs and short-term price behaviour.

Key Backtest Metrics

Profit Factor
Gross profit / Gross loss. Must be above 1.3 to be considered. Above 1.6 is strong. Above 2.0 warrants scrutiny for curve fitting.
Max Drawdown
Peak-to-trough equity decline. Should not exceed 20% on backtests. Live EAs with >15% drawdown should trigger review.
Sharpe Ratio
Risk-adjusted return. Above 1.0 is acceptable. Above 1.5 is good. Balances return against volatility of equity curve.
Win Rate
Alone this means nothing. A 30% win rate with 3:1 R:R is more robust than an 80% win rate with 0.3:1 R:R.
Expectancy
(Win Rate × Avg Win) – (Loss Rate × Avg Loss). The fundamental measure of edge. Must be positive after spread and swap costs.
Recovery Factor
Net profit / Max drawdown. Should be above 3.0. Measures how efficiently the system recovers from inevitable drawdown periods.

The Overfitting Trap

The greatest danger in EA optimisation is curve fitting — finding parameter combinations that perform perfectly on historical data but fail entirely on new data. Common signs of overfitting:

  • Extremely tight, specific parameter values that work (e.g., RSI period 17 but not 16 or 18)
  • Performance that degrades dramatically on different time periods or similar instruments
  • Profit factor above 3.0 with large number of parameters
  • Walk-Forward Analysis results much worse than in-sample results

Our approach: use the MQL5 Cloud Network's genetic algorithm optimisation to find parameter ranges (not specific values) that perform consistently. Then validate across at least 3 independent out-of-sample periods before considering live deployment.

Phase 4: Risk Management Architecture

Risk management is not a single setting — it is an architecture. Well-built EAs implement risk controls at three layers:

  • Per-trade risk — Maximum 1–2% account risk per trade via dynamic position sizing. Stop-loss mandatory on every order. No exceptions.
  • Daily drawdown limit — If the account loses more than 5% in a single day, the EA halts trading for the remainder of that day and alerts the operator.
  • Maximum drawdown circuit breaker — If cumulative drawdown exceeds a defined threshold (typically 15% from peak equity), the EA halts all trading and requires manual re-authorisation to restart.
Execution Costs Matter

EA results are extremely sensitive to spread costs: a strategy backtested on a 1.0 pip spread may be unprofitable on a 1.5 pip spread. Choose a well-regulated broker offering raw-spread ECN accounts and reliable execution with minimal slippage, and always backtest with realistic, variable spreads rather than a fixed best case.

Common Mistakes in EA Development

These are the failure modes we see most often in EA development:

  1. Lookahead bias in backtests — Using future data in the calculation of indicators. The most common form: using the current bar's close to make a decision that should only be made after the bar closes. Always reference bar[1] for completed bar values.
  2. Ignoring swap costs — Overnight position financing can eliminate the profit of trend-following strategies that hold positions for days. Always include realistic swap rates in backtests.
  3. Optimising correlated strategy parameters together — Running multiple EAs on the same account without measuring their correlation amplifies drawdowns rather than diversifying them.
  4. Insufficient sample size — A strategy with 50 trades in a backtest is not statistically significant. Minimum 200+ trades across multiple market regimes is required for meaningful statistical inference.
  5. Skipping demo deployment — Backtest performance never exactly matches live performance due to spread variation, requotes, and execution latency. Demo testing quantifies this gap before real capital is at risk.