MQL5 EA basics — how a MetaTrader 5 robot really works

Last verified: · Long-term evergreen content
Risk warning · YMYL This article is for educational purposes only and is not investment advice. Trading on the Forex market involves a high risk of capital loss — ESMA reports 74–89% of retail accounts lose money.

An Expert Advisor written in MQL5 is a small application that sits on a chart inside MetaTrader 5 and, on every tick, checks whether the market just produced the condition you defined as your entry. If it has, the EA places the order itself — no permission asked. This article explains how an EA is built on the inside, how it talks to the platform and to the broker, and when running one actually makes sense. It is not a coding tutorial.

What an Expert Advisor in MQL5 actually is

MQL5 is a language close to C++ written specifically for the MetaTrader 5 platform. An Expert Advisor is a single program in that language, compiled to a binary .ex5 file and attached to a chart the way an indicator is. The difference comes down to permissions: an indicator only draws on the chart, whereas an EA is allowed to place real orders against your trading account. That single line in the platform's permission model separates passive display from autonomous automation.

How does an "EA" differ from a general "trading robot"? Only in ecosystem. A robot written in Python is also a robot — it just lives outside the terminal, usually connecting to the broker over a REST API or FIX. An EA, by definition, lives inside MT5. For a comparative view see our companion piece on Expert Advisors in MT4 and MT5, and for the wider landscape see algorithmic trading — first steps.

How an EA talks to the platform — the OnInit, OnTick, OnDeinit cycle

Every Expert Advisor has a life rhythm dictated by three events the platform invokes on its behalf. OnInit fires exactly once, when the EA is attached to a chart or the terminal restarts. This is when the EA reads its input parameters, opens handles to any indicators it relies on, and signals that it is ready to receive ticks.

The second event is the most important. OnTick is invoked every time a new quote arrives from the broker for the symbol the EA is sitting on. On a liquid pair like EUR/USD during the London session this can happen several dozen times per second. Inside OnTick the EA decides whether the current price meets the entry conditions, whether the stop-loss needs to be moved, or whether an open position should be closed. All of the strategy logic lives in this one function.

The third event, OnDeinit, is invoked when the EA is removed from the chart, the symbol is changed, or MT5 shuts down. Its job is housekeeping — releasing indicator handles, persisting state, closing log files. I am deliberately skipping helper handlers such as OnTimer and OnTrade, because they do not change the principle. Every EA is, at heart, an event-handling program responding to whatever MT5 hands it.

How an EA places orders — the CTrade class

The second thing worth understanding without diving into syntax is how an EA communicates with the broker. MT5 does not let you simply "send a buy" the way a human clicking in the interface does. Every order is dispatched as a structured request — an MqlTradeRequest — and the server replies with a result containing a code saying whether the order went through, or whether it was rejected for reasons such as insufficient margin, invalid stop levels, or exceeded deviation.

Filling those structures by hand is tedious, so MetaQuotes ships a class called CTrade in its standard library, wrapping everything in convenient methods like Buy, Sell, PositionClose, and OrderModify. Forum threads endlessly debate the subtleties — whether to use Buy(volume, symbol) or fill the request yourself, how to handle requotes, how to react to slippage on fast breakouts. For most retail strategies CTrade is more than enough.

The Strategy Tester, or how to check the EA has not just memorised history

The Strategy Tester built into MT5 is a much more serious tool than its MT4 cousin. It feeds an EA historical ticks (generated from bars or genuine ticks from the MetaQuotes server), runs thousands of passes across parameter combinations, and produces a report with the equity curve, drawdown, and profit factor.

The trouble is that the same tester meant to verify your work tends to become a factory of illusion. Optimising parameters across the full history almost always produces a curve as smooth as a string, and that curve almost always falls apart once the EA hits real money. The phenomenon has a name — curve fitting — and it is a mathematical certainty, not bad luck. The countermeasures are covered in how to run an honest backtest: split data into in-sample and out-of-sample periods, and ideally use walk-forward analysis on top.

"A strategy that has been profitable on historical data will not necessarily be profitable in the future. Historical data is a small sample of the universe of possible market states, and optimising parameters against that sample is exactly what it sounds like — fitting to the sample." — Ernest P. Chan, Algorithmic Trading: Winning Strategies and Their Rationale, Wiley, 2013

When an EA actually helps, and when it hurts

Whether running an EA makes sense depends heavily on the strategy. Three situations where an EA delivers a real edge: consistent execution of rules a human cannot enforce psychologically (think two hundred scalping trades a month), monitoring markets around the clock during Asian sessions when the rest of the world is asleep, and trading where the decision must be made in a fraction of a second — territory where a human is simply too slow.

An EA does poorly wherever judgement is required. Trading the release of Non-Farm Payrolls, deciding whether current price action is a genuine regime change or transient noise, interpreting geopolitical context — most of this disqualifies an EA. The statistic from independent MQL5-forum surveys is brutal: a clear majority of Marketplace EAs, despite glossy backtest charts, post a loss in live trading during their first year. This is not bad faith on the part of sellers — a beautiful backtest is cheap, and a real edge is rare.

Is it worth writing your own EA?

If you understand the strategy you trade and can describe it as rules precise enough that no discretion is left, building your own EA is the best investment of time you can make in this space. Three to six months with the MQL5 documentation, a simple test project, and the Strategy Tester builds knowledge no purchased robot bundle will give you.

The second reason is practical. An EA runs around the clock five days a week — but only if the machine it lives on also runs around the clock. A home desktop in Warsaw whose power depends on a single cable is not enough. That is why a VPS plays a separate role, covered in VPS, broker location and latency: the same EA can produce noticeably different results depending on the latency between the broker's server and the machine the EA sits on.

What to do tomorrow

  1. Download MetaTrader 5 from your broker's site, open a demo account, and go to the Strategy Tester tab. Load one of the built-in sample EAs (Moving Average or MACD Sample) on EUR/USD H1, run a single pass, and read the resulting report carefully to see what the basic metrics — equity curve, drawdown, profit factor — look like in practice.
  2. Open the official MQL5 documentation at mql5.com/en/docs and read only three chapters: OnInit, OnTick, and the CTrade class. Do not try to write anything yet — the goal is to see how the documentation is organised and where to find worked examples once you need them.
  3. Write down your strategy as logical rules of the form "if X and Y then enter long with stop at level Z". If after an hour the rules still contain phrases like "depending on context" or "intuitively", you have a discretionary strategy that automation will not save — go back to the setup checklist framework before writing any code.
  4. If the rules came out unambiguous, plan a learning schedule: roughly three months of MQL5 basics from the MetaQuotes documentation, plus a week-long side project to build the simplest possible EA based on a moving-average crossover. That single project teaches you more than ten purchased robots.
  5. Before running anything on live money, commit to at least one month of forward testing on demo with current quotes. A backtest cannot replace a forward test — the forward test exposes the broker's execution latency, which a backtest cannot see.
Jarosław Wasiński
About the author

Jarosław Wasiński

Editor-in-chief at MyBank.pl · Financial and market analyst

Independent analyst and practitioner with 20+ years in finance. Founder and editor-in-chief of MyBank.pl, running since 2004. Fundamental analysis of FX and macro markets since 2007.

Sources & bibliography

  1. MetaQuotes MQL5 Reference — OnTick event handler · oficjalna dokumentacja zdarzenia wywoływanego na każdą kwotację www.mql5.com ↗
  2. MetaQuotes MQL5 Standard Library — CTrade class · klasa biblioteki standardowej do składania zleceń przez EA www.mql5.com ↗
  3. MetaQuotes MetaTrader 5 — Strategy Tester documentation · narzędzie do backtestowania i optymalizacji EA www.metatrader5.com ↗

Frequently asked

How does an MQL5 EA differ from a Python "bot"?

Logically — they do not differ at all. Both boil down to a loop that periodically checks market conditions and sends orders. The difference is the ecosystem. An MQL5 EA is a child of MetaTrader: it attaches to a chart, taps the built-in indicators, and uses the Strategy Tester. A Python robot lives outside the terminal and connects to the broker externally — typically over a REST API or the FIX protocol. The EA wins if your strategy relies on MT5 indicators and you need the built-in tester. Python wins if you want to use machine-learning libraries, statistics, or combine data from several sources.

Do I need to know how to code to run an EA?

To run someone else's EA — no. You drag the .ex5 file onto a chart, set its parameters, and enable AutoTrading. The difficulty starts further on: without knowing MQL5 you cannot verify what the robot really does inside, how it reacts to slippage, or whether it quietly uses Martingale. Sellers on the MQL5 Market often hide the most important parameters from the user. Without the ability to open the source code (and most commercial EAs are closed) you are condemned to blind trust. That is why I recommend investing in the basics of the language — a few weeks of documentation are enough to understand what you are looking at.

Why does the Strategy Tester show stellar results while live trading shows a loss?

Because the Strategy Tester is an optimisation tool, not a prediction tool. If you comb the full historical data for parameters yielding the best equity curve, you will almost certainly find a combination that produces a great result — but only on that particular sample. This is called curve fitting and it is a mathematical certainty. The antidote is splitting data into an in-sample period for optimisation (say, 2018–2022) and an out-of-sample period for verification (say, 2023–2024), on which you run the EA without further parameter tweaking. Only a consistent result on the validation period makes it plausible that you are not looking at an artefact. Walk-forward analysis goes one step further — it slides the training and testing windows through the entire history.

Do you really need a VPS to run an EA?

For a strategy that reacts in a fraction of a second — yes, without debate. A scalper whose EA fires dozens of orders a day loses its edge every time the home connection hiccups or the computer goes to sleep. A VPS placed in the same data centre as the broker's server can cut the latency from around fifty milliseconds to a few. For a position strategy making one trade a week, a VPS is a comfort, not a requirement — a home desktop with a UPS will do. The cost at MT-specialist providers today sits around 15 to 50 EUR per month. Some brokers offer a free VPS above a certain deposit or volume threshold.

Go deeper · the complete guide