MetaTrader Expert Advisor Development

Overview

An Expert Advisor is the automated trading program that runs within MetaTrader — the software that monitors the market, evaluates strategy conditions on each price update, and places and manages orders without requiring manual intervention. For traders who have defined a trading strategy with enough precision to implement it in code, an Expert Advisor converts that strategy from a process dependent on human attention and discipline into an automated system that executes consistently regardless of time zone, fatigue, or distraction.

The quality difference between Expert Advisors is not primarily in the strategy logic — it is in the implementation. Two EAs implementing the same strategy can produce dramatically different live trading results depending on how they handle order management, how they respond to broker errors, how they manage position state across connectivity interruptions, and how robustly they handle the edge cases that backtesting does not surface. An EA that works correctly in the Strategy Tester but fails in live trading — because it does not handle requotes, because it accumulates position state errors after reconnection, because it does not correctly manage partial fills — is not a finished Expert Advisor. It is a strategy prototype.

Expert Advisor development to production standards means building the strategy logic and the operational infrastructure together — the entry and exit signal generation alongside the order management, error handling, position state management, risk controls, and monitoring that reliable automated trading requires. Every component that the EA depends on in live trading is implemented correctly, not just the parts that backtesting exercises.

We build MetaTrader Expert Advisors for MT4 and MT5 for forex traders, prop firm traders, systematic trading firms, and algorithm developers — from single-strategy EAs implementing a specific approach to multi-strategy and portfolio EAs running complex concurrent strategies across multiple instruments.


What Expert Advisor Development Covers

Strategy signal generation. The core logic that evaluates market conditions and identifies entry and exit signals — the conditions that must be met for the EA to open or close a position. Signal generation implements the strategy's specific logic in MQL4 or MQL5 — technical indicator conditions, price action patterns, time and session filters, multi-timeframe confirmation, and any other conditions the strategy specifies.

Technical indicator integration: using MetaTrader's built-in indicators (iMA, iRSI, iMACD, iBands, iATR, iStochastic, and others) with the correct parameter configuration and bar offset to avoid lookahead bias, and reading indicator values correctly from the indicator buffer at the appropriate historical position. Custom indicator integration: calling custom indicators via iCustom() in MT4 or the MQL5 indicator functions in MT5, reading the specific buffer values that the custom indicator exposes, and incorporating those values into the EA's signal logic.

Price action pattern detection: identifying candlestick patterns, bar structure conditions, swing highs and lows, support and resistance levels, and the price-based conditions that discretionary strategies use — implemented as explicit code that applies the same pattern recognition logic on every bar without the interpretation variation that manual analysis introduces.

Multi-timeframe signal generation: accessing higher and lower timeframe data from within the EA using the timeframe-parameterised indicator and price data functions, combining signals from multiple timeframes to produce the entry conditions that multi-timeframe strategies require.

Order placement and management. The translation of signal generation into broker order operations — the precise sequence of API calls that opens, modifies, and closes positions in MetaTrader.

MT4 order placement: OrderSend() with the correct price (Ask for buys, Bid for sells with the appropriate execution model adjustments), the correct stop loss and take profit calculation, and the slippage parameter appropriate to the instrument and execution model. Error checking on every OrderSend() call — reading GetLastError() when OrderSend() returns -1, identifying the specific error, and applying the appropriate response (retry for ERR_REQUOTE and ERR_PRICE_CHANGED, abandon for ERR_INVALID_STOPS, report and halt for unexpected errors).

MT5 order placement: building the MqlTradeRequest structure correctly for each order type, calling OrderSend() with the request and result structures, checking the return value and the result.retcode for success and failure conditions, and handling the asynchronous aspects of MT5's execution model. Using the CTrade class from the MQL5 standard library for cleaner order placement code that handles the request/result structure management internally.

Order modification: adjusting stop loss and take profit levels as the trade progresses — the trailing stop that moves the stop loss incrementally as price moves in the trade's direction, the breakeven adjustment that moves the stop to entry price once defined profit is achieved, and the target adjustment that modifies take profit levels based on evolving market conditions.

Order closure: explicit position closure when the EA's exit signal fires, partial closure that reduces position size by a defined proportion while leaving a portion open for the trade's remaining potential, and the handling of positions that were closed by stop loss or take profit execution rather than by the EA's explicit closure logic.

Position state management. The EA's internal model of its current positions — tracking which positions are open, their entry prices, their current stop and target levels, and any position-specific state that the EA's management logic depends on.

Position detection at startup: when the EA initialises on a chart where positions already exist (from a previous EA run, from manual trading, or from recovery after a restart), correctly identifying which of the account's current positions are managed by this EA versus positions from other sources. Position filtering by magic number — the unique identifier assigned to each EA's orders that allows the EA to distinguish its positions from others on the same account.

State reconciliation after reconnection: when the MetaTrader connection to the broker drops and reconnects, positions may have changed state (stops triggered, positions partially filled, new positions opened by pending orders) during the disconnection. Reading the current position state from the broker on reconnection and reconciling it against the EA's internal state to detect and resolve discrepancies.

Crash recovery: when MetaTrader restarts (planned restart, unexpected crash, VPS reboot), the EA reinitialises and must correctly reconstruct its operational state from the current account positions rather than starting from scratch. Robust EA design handles restart recovery without requiring manual intervention to bring the EA back to correct operation.

Risk management and position sizing. The calculation that determines the lot size for each new position and the portfolio-level controls that limit the EA's aggregate exposure.

Per-trade risk calculation: computing the lot size that risks a defined percentage of account equity on each trade, using the distance from entry to stop loss in pips, the pip value for the traded instrument, and the current account equity. The calculation that produces consistent dollar risk per trade regardless of instrument, regardless of the stop distance, and regardless of account size changes between trades.

Portfolio risk controls: maximum concurrent open positions, maximum aggregate exposure in lots or in dollar terms, maximum number of trades per day or per session, and the conditions under which the EA is suspended due to risk parameter breaches.

Drawdown protection: the daily drawdown limit and the total drawdown limit that trigger EA suspension when reached. For prop firm accounts, the specific drawdown calculation methodology that the firm uses — whether drawdown is measured from the initial account balance, from the daily starting balance, or from the peak equity achieved — implemented precisely to prevent the firm's drawdown limit from being exceeded.

Broker compatibility. Expert Advisors deployed across different brokers encounter differences that can cause incorrect operation if not handled explicitly.

Minimum stop distance: most brokers impose a minimum distance between the entry price and the stop loss or take profit level. When the strategy's stop distance is less than the broker's minimum, OrderSend() fails with ERR_INVALID_STOPS. Minimum stop distance detection and the appropriate response — widening the stop to meet the minimum, skipping the trade, or alerting the trader — prevents order placement failures.

Execution mode: instant execution versus market execution affects how orders are placed and how requotes are handled. EAs that do not detect and adapt to the broker's execution mode will fail to place orders correctly in one mode or the other.

Symbol specifications: tick size, tick value, minimum lot size, lot step, and maximum lot size differ by instrument and by broker. Correct lot size calculation uses the symbol's specific tick value and lot size constraints rather than hardcoded values that work for specific instruments but fail for others.

Logging and diagnostics. The record of the EA's operational history — every signal evaluation, every order operation, every error encountered, and every risk management decision — logged to MetaTrader's Expert tab and optionally to an external log file.

Structured logging that records sufficient context for each log entry to be useful for debugging: the timestamp, the current bar, the relevant indicator values and market conditions, the action taken, and the result. Log verbosity control — detailed logging in debug mode, reduced logging in production mode — that allows the logging overhead to be managed without losing the diagnostic record.

Alert generation for events requiring the trader's attention: an approaching drawdown limit, an order rejection that requires manual resolution, a connectivity issue that may have affected position state.


Multi-Strategy and Portfolio EAs

Expert Advisors that manage more than one strategy or trade more than one instrument require additional architecture to manage the complexity correctly.

Multiple concurrent strategies. An EA that runs multiple independent strategies simultaneously — each with its own signal logic, its own position sizing, and its own magic number for position identification — requires an architecture that isolates each strategy's state from the others and applies portfolio-level risk controls that consider the aggregate exposure across all strategies.

Strategy manager architecture: a central coordinator class that instantiates and manages multiple strategy instances, each encapsulating its own signal logic and position management. The coordinator applies the portfolio-level controls — maximum concurrent positions across all strategies, aggregate drawdown monitoring, correlated exposure detection — while delegating the individual strategy decisions to each strategy instance.

Multi-instrument trading. EAs that trade multiple currency pairs or instruments from a single EA instance — monitoring all instruments on each tick, managing positions across all traded instruments, and applying the allocation logic that determines which instruments receive capital and in what proportion.

For MT5 multi-symbol EAs, the OnTick() event fires when any of the instruments the EA is subscribed to receives a price update — the EA must identify which symbol fired the event and apply the correct strategy logic for that symbol. For MT4 multi-symbol EAs, a single chart-attached EA accesses other instruments via the symbol-parameterised price and indicator functions, without receiving tick events for those instruments directly.


Specific EA Types We Build

Trend following EAs. Moving average crossover systems, channel breakout EAs, ADX-filtered trend systems, adaptive trend EAs that adjust to market conditions. Position management with trailing stops that follow the trend while protecting accrued profit.

Mean reversion EAs. Bollinger Band reversion EAs, RSI overbought/oversold systems, statistical mean reversion using z-score normalisation. Position management with fixed take profit targets and defined stop losses.

Scalping EAs. Short timeframe EAs targeting small per-trade profits with high frequency. Spread filter logic that prevents entries when spread exceeds the strategy's viability threshold. Fast execution logic that minimises the latency between signal and order placement.

Grid and hedging EAs. Grid EAs that place orders at defined price intervals. Hedging EAs that open opposing positions under defined conditions. Position management for the complex multi-position state that grid and hedging systems accumulate.

News and event EAs. EAs that trade around scheduled economic releases — either avoiding news periods with news filters, or positioning before releases and managing the post-news move. Economic calendar integration for news awareness.

Prop firm compliance EAs. EAs specifically designed for prop firm challenges and funded accounts — incorporating the firm's specific drawdown rules, lot size limits, news trading restrictions, and other account conditions as enforced constraints rather than optional guidelines.

Trade management EAs. EAs that manage positions opened manually or by other EAs — applying trailing stops, moving to breakeven, scaling out at defined profit levels, and applying other position management logic to externally opened positions.


Technologies Used

  • MQL4 — MT4 Expert Advisor development
  • MQL5 — MT5 Expert Advisor development with object-oriented architecture and standard library
  • MQL5 Standard Library — CTrade, CPositionInfo, COrderInfo, CAccountInfo, CExpert for reliable MT5 platform interaction
  • C++ / C# — DLL development for EAs requiring external library integration
  • Python — external signal generation and data processing integrated with EAs via file or socket bridge
  • MetaTrader Strategy Tester — backtesting, visual validation, parameter optimisation
  • VPS infrastructure — Windows VPS for production EA deployment
  • SQL (SQLite / MySQL) — trade logging and performance tracking via external integration

Production Standards, Not Prototype Quality

The Expert Advisor that works in backtesting and fails in live trading is one of the most common and most costly failures in retail algorithmic trading. The failures are almost always in the operational infrastructure — the error handling, the position state management, the broker compatibility, the connectivity resilience — rather than in the strategy logic that backtesting validates. Building an Expert Advisor to production standards means building all of it: the strategy logic that backtesting validates and the operational infrastructure that live trading requires.


Automated Execution You Can Trust

The purpose of an Expert Advisor is to execute the strategy consistently and reliably in live trading — without the attention lapses, the emotional deviations, and the execution delays that manual trading introduces. An Expert Advisor built to production standards delivers this purpose. One that is not falls short of it in the conditions that live trading produces.