How to Write an Expert Advisor?

How to Write an Expert Advisor?

Writing an Expert Advisor (EA) means transforming a precise trading strategy into automated code that runs on the MetaTrader platform without emotional interference. To achieve this, you must first convert your trading logic into clear, rule-based conditions, then implement it using the MQL4 or MQL5 programming language. This process includes defining entry and exit signals, managing risk, integrating technical indicators, testing the strategy using the Strategy Tester, and optimizing performance. A professional EA is not only technically sound but also stable and effective in live market conditions. It serves as a strategic tool for executing your analysis with consistency and precision.

4.7
★★★★★
★★★★★
(425)Rate this article

What is a Forex Expert Advisor and What Role Does It Play in Automated Trading?

An Expert Advisor or "EA" is a program that is installed on the MetaTrader platform and can execute trades automatically based on predefined logic. Expert Advisors are written in MetaTrader's specialized programming languages, MQL4 or MQL5, and enable a range of operations without direct human intervention, including opening and closing trades, volume management, and even applying complex technical analysis filters.
The main role of an Expert Advisor in the forex market is to eliminate emotional decision-making and execute trading strategies precisely and consistently. A trader can convert their strategy logic into code and ensure that each trade follows the same rules without fatigue, fear, or greed influencing decisions.
Expert Advisors are useful not only for automated trading but also for market analysis, signal generation, risk management, and symbol monitoring. They can monitor a market 24/7 and react within fractions of a second, a capability that is impossible for manual traders.

What Should We Know Before Writing an Expert Advisor?

Writing an Expert Advisor is not merely about coding; it requires preparation in three areas: analysis, logic, and tools. Before starting to write code, several key questions must be answered: What strategy exactly do you want to implement? What are the entry and exit conditions? How is capital management performed? How should the Expert Advisor behave in special conditions like news events or high volatility?
On the other hand, familiarity with the MetaTrader platform and the MQL programming environment is essential. Even if you don't intend to write the code yourself and want to delegate it to a programmer, you cannot accurately convey your idea without understanding the structure of Expert Advisors.
You should also consider the testability of your strategy. If your strategy is full of ambiguities or relies on visual judgment, converting it to reliable code will be very difficult. Therefore, strategies that are rule-based, measurable, and repeatable are the best choices for conversion into Expert Advisors.
Alongside these, basic concepts such as order types (Market, Limit, Stop), candle structures, timeframes, and conditional structures (like "if ... then ...") should also be clear to you. Without these preliminaries, entering the world of Expert Advisor development will simply be a waste of time.

MQL4 and MQL5 Programming Languages; The Right Choice for Expert Advisor Development


MQL4 and MQL5 are two specialized languages for the MetaTrader platform used to develop indicators, scripts, and Expert Advisors. If you intend to write an Expert Advisor for MetaTrader 4, you should use MQL4, and if your platform is MetaTrader 5, you should use MQL5. Both languages are based on the C structure and will be easier to learn for those familiar with programming languages like C++ or JavaScript.
MQL4 is the older language and has a larger user community, but it has more limited capabilities compared to MQL5. In contrast, MQL5 has a more advanced structure, provides the ability to manage multiple symbols simultaneously, and has advanced features for optimization and analysis.
If you are a beginner and your goal is to write simple or single-symbol Expert Advisors, starting with MQL4 might be a suitable choice because it has more educational resources and less complexity. But if you want to develop more complex systems based on multiple assets or with advanced optimization, MQL5 is a better option.
The important point is that the structure and logic of writing in both languages are largely similar. So by learning one, you will also gain a basic understanding of the other and can easily switch between them later.

Converting a Trading Strategy to Programming Logic; The First Real Step in Expert Advisor Development

If we want to build an Expert Advisor, we must understand that code is just a translation of our trading strategy logic. The Expert Advisor doesn't understand that "there is a higher probability of growth here" or "this candle looks good." It only understands that "if A and B occur simultaneously, then place a buy order." Therefore, the first serious step in writing an Expert Advisor is converting the mental strategy into precise conditional logic.
To start this process, you should write down your trading strategy carefully. For example:

  • Which indicators or factors should be examined?
  • What exactly are the entry conditions? For example, the crossing of two moving averages, or RSI crossing above 30
  • How are stop loss, take profit, and volume management set?
  • When is the trade closed? Upon reaching the target? Hitting the stop? Or new specific conditions?

The best method for preparing this logic is designing a flowchart or decision table. When you can draw the strategy on paper without ambiguity, you enter a stage where implementing it in code will be a technical and specific task.
Remember that the more precise and measurable your strategy is, the more powerful your Expert Advisor will be. Logic such as "I feel the trend is strong" or "I think the correction might be over" doesn't work for coding. The Expert Advisor works with numerical and conditional data, not with feeling and personal interpretation.

What is the Basic Structure of an Expert Advisor in MetaTrader?

When you're ready to enter the coding space, the first thing you need to understand is the standard structure of an Expert Advisor in MQL. An Expert Advisor consists of several key sections that must exist in every file. The most important ones are:

  • OnInit() This function is called when the Expert Advisor starts running (for example, the moment you run it on a chart). It's typically used for initial variable definitions, getting settings, or loading indicators.
  • OnDeinit() When the Expert Advisor is removed from the chart or turned off, this function is executed. If you want to free specific resources or save information, it's done here.
  • OnTick() This is the most important part of the Expert Advisor. Every time a new price is received from the market (i.e., every tick), this function is executed, and the main code for examining market conditions and decision-making is written here.

For example, the basic structure of a very simple Expert Advisor in MQL4 might look like this:
imageAn important aspect in designing this structure is maintaining order and modularizing the code. That is, it's better for each part of the strategy (entry, exit, risk management, logging, etc.) to be written as a separate function so that the code is more readable and expandable.

How to Define Entry and Exit Signals in an Expert Advisor?


Defining entry and exit signals is the beating heart of an Expert Advisor. At this stage, you need to convert the trading decision-making logic into code that checks every time the market provides new data, and if the conditions are met, takes action.
Let's say your strategy is: "If the short-term moving average crosses the long-term moving average upward, enter a buy. If the opposite happens, close the trade."
In MQL4, this logic might be coded simply like this:
imageThe key point here is that the signal definition must be simple, precise, and unambiguous. An Expert Advisor cannot hesitate or interpret multiple ambiguous conditions. So if, for example, you want to use a combination of RSI and MACD, specify exactly what RSI value and what MACD histogram status you're looking for.
Alongside signals, trading commands like OrderSend, OrderClose, OrderModify in MQL4 or trade.Buy(), trade.Sell() in MQL5 are used to execute buy and sell orders. At this stage, you need to pay close attention to parameters, trade volume, stop loss and take profit, and error management.

Adding Technical Indicators and Filters to the Expert Advisor

One of the powerful features of Expert Advisors is the ability to use technical indicators in trading decisions. An Expert Advisor can review and execute entry and exit signals based on the analysis of indicators such as Moving Average, RSI, MACD, Bollinger Bands, ATR, and many others—more precisely than a human could do in the moment.
For example, let's say you want the Expert Advisor to enter a trade only when the price is above the 20-day moving average and simultaneously the RSI is below 30. In MQL4, these two conditions are called as follows:
imageAdding filters follows a similar process. Filters might be as simple as timeframe (e.g., run only on H1 timeframe), or as complex as volume analysis, specific hours of the day, or avoiding trades during news events.
The important note here is: In designing an Expert Advisor, each indicator should have a specific purpose. You shouldn't add indicators just to "increase filters," but rather know what decision you're making simpler or more accurate with its help. This approach transforms your Expert Advisor from a simple system into a purposeful tool.

How to Test and Optimize an Expert Advisor? Strategy Tester Tutorial in MetaTrader

After writing an Expert Advisor, a vital stage arrives: testing and optimization. Without testing, no Expert Advisor is reliable, even if the code runs without errors. The main tool for this in MetaTrader is the Strategy Tester.
In MetaTrader 4, you can open the Strategy Tester from the View menu. There, you select the desired symbol, timeframe, time period, and test model (Every tick or Control points). Then by pressing Start, the testing process begins. MetaTrader simulates the Expert Advisor's behavior based on historical data and shows you the result in the form of a report.
The report includes items such as number of trades, profit percentage, profit-to-loss ratio, maximum drawdown, and net profit. Analyzing this data helps you understand where the Expert Advisor performed well and where it has weaknesses.
But the more important part is optimization. In this mode, you specify several variables such as average lengths, stop loss, or volume as changeable parameters, and MetaTrader performs hundreds or thousands of tests with different combinations of these values to find the best settings.
Important notes on optimization:

  • Don't always optimize with old data; it's better to keep some data for separate testing (Forward Testing).
  • Don't look for the best performance across the entire market; look for stable performance in diverse periods.
  • Ideal settings on past data won't necessarily work well in the future. So avoid "Overfitting."

Common Errors in Expert Advisor Development and How to Prevent Them


Expert Advisor development, like any other type of coding, is full of details and hidden traps. Even if the strategy logic is correct, its implementation in code might lead to behavioral or performance errors. Understanding these common mistakes makes the development path shorter and more stable.

Not checking the status of positions

Many traders forget to check if a trade is open before sending a buy or sell order. This can cause multiple positions to open simultaneously. To check the number of open positions, use OrdersTotal() in MQL4 or PositionsTotal() in MQL5 before sending a new order.

No error management

Some codes show no reaction if a trading order encounters an error (e.g., due to high spread or connection issues). The result? The Expert Advisor thinks the trade was executed, but it actually wasn't.

Ignoring timeframe and candle data

Incorrect use of Close[0] or iMA(..., 0) can lead to using a price that hasn't closed yet and might change during the candle. For definitive checking, use Close[1] to read the information of the previously closed candle.

Using fixed parameters without adjustment capability

When all values are written as constants in the code, the ability to optimize or adjust it for different symbols and conditions is lost. To prevent this, use extern or input for key variables and parameters like stop loss, volume, moving average period, etc.

Not testing in real market conditions

Some Expert Advisors only perform well on historical data and encounter serious problems in real accounts. Testing on a demo account with live conditions, using different data, examining behavior during news events and market opening/closing times are the best methods to prevent this problem.

How to Build a Professional Expert Advisor for Use in the Real Market?

Building a professional Expert Advisor goes beyond writing a series of trading commands. A professional Expert Advisor must not only be coded based on correct logic but also perform reliably and dependably in real market conditions.
The first characteristic of a professional Expert Advisor is having a modular and readable structure. Code that is compartmentalized, with specific functions and clear logic, is easily updatable, debuggable, and expandable. The second point is the Expert Advisor's adaptability to different symbols and timeframes. Using input parameters allows the user to change parameters according to their needs.
Additionally, a professional Expert Advisor must be capable of properly reacting to special market conditions, including high volatility, economic news, times of low liquidity, or market closures. Adding filters such as volume checks, spread monitoring, or candle closing time verification can help increase stability.
Finally, complete testing in a demo environment and examining behavior in different situations is essential before using the Expert Advisor in a real account. Detailed reporting, event logging, and performance monitoring during execution are also part of the process of professionalizing an Expert Advisor.
A professional Expert Advisor is the result of a precise, step-by-step, and tested process. Not just code, but a strategic tool for converting analytical discipline into automated performance.

Comments

Dilara Aksoy

Nicely structured tutorial, good job FeneFX.

Sam Whitlock

I built an EA to automate my grid strategy and it blew up a demo account in two weeks — best money I never lost. Now I test everything on demo for months first.

Meredith Lowe

Never coded in my life but the MQL basics section got me through my first 'hello world' EA. It just prints a comment on the chart but hey, it's a start. Thanks!

Victor Ionescu

Writing the EA is maybe 20% of the work. The other 80% is validation — walk-forward testing, out-of-sample data, avoiding curve fitting. Most beginner EAs die there, not in the code.

Felix Braun

Any plans for a follow-up on backtesting properly? I've heard 99% modeling quality in MT5 still isn't fully reliable and I'd love a deep dive on tick data.