Editorial coverage · Last reviewed
Build a Custom EA — Step-by-Step Series for MT5 Development
Phase 1: Strategy definition
Before writing code, document the strategy in plain English: entry conditions (when to open position), exit conditions (stop loss, take profit, time-based exit), position sizing rule (fixed lots, percent risk, Kelly fraction), instruments traded, timeframes, market regime expectations.
Example: 'Buy EURUSD on H1 timeframe when 20-period EMA crosses above 50-period EMA AND RSI(14) above 50. Risk 1% per trade with stop at recent swing low. Take profit at 2× risk. Skip Friday afternoons and major news events.'
Critical: the strategy should have a hypothesis about WHY it works. Trend-following hypothesis: 'persistent trends in forex driven by macro factors create exploitable directional moves'. Without a hypothesis, strategy is curve-fit pattern matching that won't generalise.
Anti-pattern: starting with backtest optimisation rather than strategy hypothesis. Optimising parameters to maximise backtest return produces over-fit strategies that fail live.
Phase 2: MQL5 implementation
Project structure: separate files for strategy logic, risk management, position management. Avoid monolithic single-file EAs that mix concerns.
Use Standard Library extensively: CTrade for execution, CPositionInfo for position queries, CSymbolInfo for symbol properties. Avoid raw OrderSend() unless you have specific reason.
Magic number convention: use unique magic number per EA so the EA can identify its own positions and avoid interfering with other EAs or manual trades. Different strategies = different magic numbers.
Error handling: every trade.Buy()/trade.Sell() should be followed by trade.ResultRetcode() check. Log failures; don't silently ignore. Common retcodes: TRADE_RETCODE_DONE (success), TRADE_RETCODE_REJECT (broker rejected — investigate), TRADE_RETCODE_REQUOTE (price moved — retry).
Time and market session handling: use TimeCurrent() and TimeToStruct() to filter trading hours. Many strategies are session-specific; running outside intended session degrades performance.
Phase 3: Backtesting
MT5 Strategy Tester runs your EA on historical data with simulated execution. Critical settings: (1) Modeling: 'Every tick based on real ticks' is most accurate but slowest; 'Every tick' for medium accuracy; 'OHLC 1 min' for fast initial tests. (2) Currency: USD. (3) Initial deposit: realistic ($5,000-$10,000). (4) Leverage: match production broker leverage.
Multi-pair and multi-timeframe testing: don't test on one pair/timeframe only. Trend-followers should work on multiple major pairs across H1-D1. If strategy only works on EURUSD H4, it's likely curve-fit.
Realistic spreads and slippage: Strategy Tester uses recorded historical spreads but may not capture slippage realistically. Add buffer (e.g., +0.5 pip to typical spread) for production safety margin.
Avoid look-ahead bias: use only data available at the time of decision. MQL5's iClose(symbol, timeframe, 0) returns current (incomplete) bar; index 1 is the just-closed bar. Most EAs should base decisions on closed bars (index 1+) to avoid look-ahead.
Common backtest pitfalls: over-fitting (too many parameters tuned to historical data), survivorship bias (only testing currently-active pairs), spread variance (using current spreads on historical data when historical was different).
Phase 4-6: Optimisation, demo, production
Walk-forward optimisation: optimise parameters on in-sample window (e.g., 2020-2022), test on out-of-sample window (2023). Re-optimise on (2021-2023), test on 2024. Continue rolling. Strategy should perform similarly out-of-sample as in-sample; large degradation = over-fitting.
Demo account testing: deploy on demo broker account for 2-4 weeks. Verify behaviour matches backtest expectations under real broker execution. Common surprises: slippage worse than backtest, missed trades during network issues, broker rejection of certain orders.
Production deployment: use VPS for 24/7 operation (Beeks Financial Cloud, Equinix Cloud, or broker-provided VPS). Set up monitoring (Myfxbook auto-sync, custom alerts on drawdown thresholds). Start with conservative position sizing; scale up gradually as confidence grows with live results.
Frequently asked questions
Should I build a custom EA or buy an existing one?
Build vs buy decision framework for retail EA traders: Buy when: • Beginner without programming experience. • Goal is supplemental income, not deep engagement with trading systems development. • Time-poor (full-time job, limited hours per week for project). • Want to start trading with EAs within months, not years. • Quality commercial EAs available for your strategy class. Build when: • Existing programmer wanting to learn systematic trading. • You have a specific strategy hypothesis not addressed by commercial EAs. • Strategy involves proprietary data or analytics (ML models, alternative data sources). • You're building for commercial distribution (selling EA to others). • Educational/research goal alongside trading. • Significant time available for multi-month project. Hybrid (recommended for many): • Buy quality commercial EAs to start trading immediately. • Learn MQL5 in parallel with trading operation. • Build your first custom EA after 12+ months of operational experience with commercial EAs. • First custom EA: simple strategy you can backtest and verify edges in; not ambitious 'ML beat-the-market' attempt. • Refine custom EAs as side project; continue running commercial EAs as production. Cost-benefit analysis (typical retail trader): Buying: $200-500 one-time per EA + monthly broker fees + VPS. Time investment: 20-50 hours total to get operational. Expected outcome: starting profitable EA operation within 1-3 months. Building: $0 software cost but 200-1000+ hours development + same operational costs. Expected outcome: functional EA within 3-6 months, profitable EA within 6-12 months IF you have programming and trading skill. Many projects don't reach profitability. For most retail traders, buying commercial EAs is the more efficient path. Custom EA development is rewarding for those with the time and inclination but rarely the most efficient route to trading income.