An Expert Advisor (EA) is a program that trades a MetaTrader account for you, following rules you write in MQL. If you have never built one, this guide walks through what an EA actually is, how its code is structured, and the pitfalls that trip up almost everyone on their first attempt.
MQL4 or MQL5? MT4 or MT5?
MetaTrader comes in two generations. MT4 uses MQL4; MT5 uses MQL5. They look similar but are not interchangeable — MQL5 is more powerful (a proper object model, a netting/hedging position system, multi-asset and multi-timeframe testing) while MQL4 is simpler and still widely used. Pick the platform your broker and strategy need, then learn its dialect. Code written for one will generally not compile on the other without changes.
The three events every EA is built around
An EA is event-driven. You don't write a loop that runs forever; instead the terminal calls your functions when things happen:
The shape of a first EA
Conceptually, a minimal trend EA does this inside OnTick():
Inputs (lot size, MA periods, stop distance) are declared with the input keyword so you can change them from the EA's settings dialog and in the Strategy Tester without editing code.
Common pitfalls on the first EA
A sensible learning path
Bottom line
An EA is just rules plus discipline, expressed in MQL and executed without emotion. Master the OnInit/OnTick/OnDeinit structure, handle orders defensively, respect spread and stops, and prove the thing in the tester and on demo before it ever sees real capital. Start simple — a working one-rule EA you fully understand beats a complex one you don't.
Educational content from the PipFlow staff — not investment advice.
MQL4 or MQL5? MT4 or MT5?
MetaTrader comes in two generations. MT4 uses MQL4; MT5 uses MQL5. They look similar but are not interchangeable — MQL5 is more powerful (a proper object model, a netting/hedging position system, multi-asset and multi-timeframe testing) while MQL4 is simpler and still widely used. Pick the platform your broker and strategy need, then learn its dialect. Code written for one will generally not compile on the other without changes.
The three events every EA is built around
An EA is event-driven. You don't write a loop that runs forever; instead the terminal calls your functions when things happen:
- OnInit() — runs once when the EA is attached or inputs change. Validate parameters, set up indicator handles, prepare state. Return an error here and the EA won't start.
- OnTick() — runs on every incoming price tick. This is the heart of the EA: check conditions, decide whether to open, modify, or close orders. It can fire many times per second in a fast market, so it must be fast and defensive.
- OnDeinit() — runs once when the EA is removed or the terminal closes. Clean up: release indicator handles, delete chart objects, tidy state.
The shape of a first EA
Conceptually, a minimal trend EA does this inside OnTick():
- read the values of, say, a fast and a slow moving average;
- if the fast crosses above the slow and you have no open position, send a buy order with a stop-loss and take-profit;
- if the fast crosses below and you are long, close the position;
- otherwise, do nothing and wait for the next tick.
Inputs (lot size, MA periods, stop distance) are declared with the input keyword so you can change them from the EA's settings dialog and in the Strategy Tester without editing code.
Common pitfalls on the first EA
- Acting on every tick instead of every bar. If your logic is meant to work on closed candles, evaluate it once per new bar — not on every one of the hundreds of ticks inside that bar. Otherwise you fire dozens of duplicate signals.
- No error handling on orders. Trade requests fail — bad stops, insufficient margin, requotes, market closed. Always check the return code and react, instead of assuming the order went through.
- Ignoring spread and stop levels. Brokers enforce a minimum distance for stops, and the spread eats into tight targets. A strategy that ignores both backtests beautifully and loses live.
- Repainting indicators. Some indicators change their past values as new data arrives. Building signals on them means your backtest used numbers that didn't exist at the time — pure look-ahead bias.
- Trusting the Strategy Tester blindly. Use realistic modelling (real ticks / every tick where possible), include commission and slippage, and remember that "99% modelling quality" on bad assumptions is still bad. Forward-test on a demo before risking money.
- Magic numbers. Tag your EA's orders with a unique magic number so it manages only its own trades and doesn't fight other EAs or your manual positions on the same account.
A sensible learning path
- Start in the MetaEditor with the built-in MQL Wizard to generate a skeleton EA, then read every generated line until you understand it.
- Build the simplest possible strategy (one moving-average cross) and get it trading correctly in the Strategy Tester first.
- Add risk controls — stop-loss, take-profit, position sizing — before adding any cleverness.
- Only then layer in filters, multiple timeframes, or money management.
Bottom line
An EA is just rules plus discipline, expressed in MQL and executed without emotion. Master the OnInit/OnTick/OnDeinit structure, handle orders defensively, respect spread and stops, and prove the thing in the tester and on demo before it ever sees real capital. Start simple — a working one-rule EA you fully understand beats a complex one you don't.
Educational content from the PipFlow staff — not investment advice.
clean
by ai-agent