MetaTrader 5 Expert Advisor development: from strategy to live account
How an MT5 EA gets built: EA vs. indicator, turning a strategy into a spec, MQL5 structure, risk management, backtesting, optimization and VPS hosting.
MetaTrader 5 (MT5) is a trading platform widely used in forex, commodity and index markets. Its greatest strength is that programs written in the MQL5 language can run on a chart and open and close trades on their own. These programs are called Expert Advisors (EAs). I am Berke Özyaşar; I develop EAs and indicators for MetaTrader 4 and 5, and Pine Script indicators for TradingView. In this post I explain how an EA project runs from start to finish, with a focus on the parts of the process that are not code.
EA or indicator?
This is usually the first question. Both are written in MQL5, but they do different jobs:
- An indicator draws information on the chart: a line, an arrow, a color change or an alert. You make the decision and place the order.
- An Expert Advisor sends the order itself when its rules are met, then manages and closes the position.
If you do not fully trust your strategy yet, or part of the decision requires judgment, starting with an indicator is often the better call. As the rules become clearer, the same logic can be moved into an EA. Some projects use both: the indicator generates the signal, and the EA reads that signal and trades on it.
The most important step: turning the strategy into a spec
Most requests start with a single sentence like "buy when the moving averages cross." That sentence may be enough for a person, but not for a program. Before writing any code, all of these questions need answers:
- Which symbol and which timeframe? Will it run on several symbols at once?
- Is the signal checked when a candle closes, or on every price change?
- What exactly are the entry conditions? Which indicators, with which parameters?
- How is the position closed: fixed stop-loss and take-profit, a trailing stop, or an opposite signal?
- How many positions can be open at the same time? What happens if a signal comes in the opposite direction?
- During which hours should it not trade: major data releases, the weekend close, times when spreads widen?
- How is lot size calculated?
Filling in this list together sometimes takes longer than the code itself, but it largely prevents the "that is not what I meant" conversations later on. The spec also becomes the reference for checking whether the EA behaves correctly during testing.
The structure of an EA in MQL5
An MQL5 EA is built around a few event functions:
- OnInit(): Runs once when the EA is attached to the chart. Indicator handles are created here and input parameters are validated. If the parameters make no sense, the EA should stop here without starting.
- OnTick(): Runs every time a new price arrives for the symbol, and it is the heart of the strategy. For strategies that work on candle closes, the first job is to check whether a new candle has formed; otherwise the same signal gets processed many times within a single candle.
- OnDeinit(): Runs when the EA is removed or the terminal closes. Indicator handles are released and objects drawn on the chart are cleaned up.
In addition, OnTimer() can be used for scheduled tasks and OnTradeTransaction() for tracking order and position events. Orders are usually sent with the CTrade class from the standard library. In a robust EA, the return code of every order should be checked: insufficient margin, a closed market, an invalid stop level or a requote happen more often on a live account than you would think. The code should also adapt to the symbol's minimum lot step, minimum stop distance and number of digits; an EA that runs smoothly with one broker can throw errors with another because of these details.
Risk management must be built into the code
The most important part of an EA is not the entry signal but risk management. The topics I cover as standard in every EA:
- Position sizing: Instead of a fixed lot, a structure that risks a set percentage of the account per trade and calculates the lot size from the stop distance.
- A stop-loss on every trade: Never opening a position without a stop.
- Daily and total loss limits: When a certain loss is reached, the EA stops trading for the day or entirely.
- Spread filter: Not opening trades while the spread is above a set value.
- Restart resilience: When the terminal restarts, the EA recognizes its open positions by magic number and keeps managing them.
Backtesting with the Strategy Tester
MT5's Strategy Tester runs the EA on historical data and reports the results. There are a few things to watch for here. The testing model matters: a test using only open prices is fast but misleading for strategies that depend on intra-candle movement; a test with real tick data is slower but more realistic. Costs such as spread, commission and swap should be included in the test. Rather than a single net profit figure in the report, look at maximum drawdown, the number of trades and how the results are spread over time.
Optimization and overfitting
The Strategy Tester can scan combinations of parameters and find the one with the best result. It is a powerful tool, but this is also where the most common mistake happens: if you fine-tune enough parameters finely enough, you end up with a system that looks great on past data but never catches the future. This is called overfitting.
To guard against it, I set aside part of the data that the optimization never sees and test the parameters it finds on that unseen period. MT5's forward testing option can do this automatically. I also prefer a broad region where neighboring parameters give reasonable results too, rather than a single peak value. The fewer the parameters, the more you can trust that the results are based on something real.
Demo account and forward testing
However good the backtest, the EA should run for a while on a demo account, or on a live account with very small lots, before going live. At this stage the goal is less about measuring profit and more about seeing whether the EA behaves according to the spec in real conditions: are orders opened at the right time, how much slippage is there, do the broker's rules cause problems? Having the EA log every decision makes this check much easier.
VPS: the EA's home
An EA only runs while the MetaTrader terminal is open. When your computer shuts down, the internet drops or the operating system restarts for an update, the EA stops too. That is why EAs that need to run continuously are usually hosted on a VPS. You can use MetaQuotes' own virtual hosting service or an independent Windows VPS. A location close to the broker's server reduces latency.
Conclusion
A good EA starts with a good spec and puts risk management at the center of the code. A backtest is a starting point, not proof; optimization misleads if it is not done carefully. No EA guarantees profit, and this post is not investment advice either. You can see my work in this area on the MetaTrader EAs and indicators page, and the market tracking side in the All Financial Market Watcher app. If you are considering an EA or an MQL5 indicator for your own strategy, you can reach me via the trading bots page.