Home › FX Trading School › Pro
Building Your First Expert Advisor: MQL Basics
Building your first Expert Advisor is the point where trading strategy meets code — where the rule-based system you sketched out in Module 12 (Systems: Rule-Based Strategy Design) stops living in a notebook and starts executing on a live chart. This lesson covers the MQL basics you need to write, compile, and test a genuinely simple EA, without pretending automation removes risk or guarantees results.
We're not writing a full trading system here. We're writing the smallest possible EA that actually works, so you understand every line before you add complexity.
What an Expert Advisor Actually Is
An Expert Advisor (EA) is a program written in MQL4 or MQL5 that runs inside MetaTrader and can read price data, calculate conditions, and place or manage trades automatically. It's not magic — it's a set of instructions that fires on every new price tick or new bar, depending on how you write it.
Before touching code, be clear on what an EA can and can't do:
- It can execute your exact rules consistently, without hesitation or fatigue
- It can monitor multiple conditions simultaneously across timeframes
- It cannot adapt to conditions you haven't coded for
- It cannot guarantee profitability — a badly designed EA will lose money efficiently and quickly
- It will keep trading a broken strategy exactly as instructed, which is why testing matters more than enthusiasm
This is also where broker choice starts to matter practically, not just theoretically. Your EA's execution depends on server type, and Pepperstone's MetaTrader server list, for instance, separates MT4 and MT5 environments — you need to know which one you're coding for before you start.
MQL4 vs MQL5: Which Language to Learn
MQL4 and MQL5 look similar on the surface — both are C-like languages purpose-built for MetaTrader — but they're not interchangeable.
| Feature | MQL4 | MQL5 | |---|---|---| | Platform | MetaTrader 4 | MetaTrader 5 | | Syntax strictness | More forgiving | Stricter, requires explicit typing | | Order system | Simple order functions | Object-oriented trade classes | | Backtesting | Single-currency, simpler | Multi-currency, more realistic | | Community libraries | Very large, older | Growing, more modern |
Practical advice: check what your broker actually offers before committing time to one language. IG runs its own proprietary platform alongside MetaTrader access, while Pepperstone offers both MT4 and MT5 servers depending on account type — so the "right" language depends on where you'll actually deploy the EA, not just personal preference.
The Three Core Blocks Every EA Needs
Every MQL program is built around three event-handling functions. Learn these before anything else.
1. OnInit() — runs once when the EA is attached to a chart. Use it to set up variables, check symbol properties, or validate settings. 2. OnTick() — runs every time a new price tick arrives. This is where your actual trading logic lives: checking conditions and placing or closing orders. 3. OnDeinit() — runs once when the EA is removed. Use it to clean up, log a final message, or release any resources.
A minimal skeleton looks like this conceptually:
- OnInit: confirm the symbol has enough historical bars, set a magic number for order identification
- OnTick: check if a new bar has formed, check your entry condition, check if a position already exists, place or hold
- OnDeinit: print a simple "EA removed" comment for your own log
Resist the urge to add stop-loss logic, trailing stops, or multiple indicators at this stage. Get a single entry and single exit working reliably first.
Writing Your First Simple Rule in Code
Say your Module 12 strategy rule was: "buy when the 20-period moving average crosses above the 50-period moving average, on a new bar." In MQL, that becomes:
- Declare two moving average handles (fast and slow) in OnInit
- In OnTick, check
IsNewBar()logic so you don't recalculate on every single tick - Copy the current and previous MA values into arrays
- Compare: if fast MA was below slow MA on the previous bar and is now above it, that's your cross
- If no position is open, send a buy order with a fixed lot size
Keep the lot size fixed for your first build — no percentage risk, no dynamic sizing. That's a Module 14 topic. Right now you're proving the mechanism works, not optimising it.
Compiling, Debugging and Common Errors
Once written, press F7 in MetaEditor to compile. Errors will appear in the "Errors" tab — read them literally; MQL error messages are usually specific about the line and the problem.
Common first-time errors:
- Undeclared variable — you used a name before declaring its type
- Wrong array indexing — MQL price arrays are typically indexed from the most recent bar backward; get this backwards and your logic silently breaks
- Missing semicolon — the classic C-family typo
- Order send failed — often a lot size, stops level, or symbol permissions issue rather than a syntax problem
Don't skip warnings even if the EA compiles. A warning about an unused variable is harmless; a warning about implicit type conversion can hide real bugs.
Testing Before You Trust It
This is non-negotiable. Use MetaTrader's Strategy Tester to run your EA over historical data first, then move to a demo account for forward testing in real time.
Be honest about what backtesting can't tell you:
- Historical spread and slippage models are simplified compared to live execution
- Broker-specific fills, requotes, and swap charges vary — this is exactly why PipTax's cost tool exists, so you can compare realistic cost assumptions before scaling up
- Past price action never guarantees future performance, however clean your backtest curve looks
Run any new EA on a demo account for weeks, not days, and log every trade manually alongside the EA's own results so you can spot discrepancies early.
Where This Fits in Your Trading Education
Building your first Expert Advisor is a milestone, not a finish line. You've moved from a written rule set to working code that executes it — but the discipline that got you here (clear rules, defined risk, honest testing) matters more than the automation itself. Before deploying anything with real capital, revisit your broker's actual execution costs using the audit tool, and cross-check server and platform details on the brokers comparison page. Module 14 builds on this foundation with position sizing and risk management inside your EA — the part that decides how much of your account is ever actually at stake.
Key takeaways
- Building your first Expert Advisor means turning a rule-based strategy (from Module 12) into code that MetaTrader can execute automatically
- MQL4 and MQL5 share similar structure but MQL5 has stricter syntax and more built-in functions — check which your broker's server supports before you start
- Every EA needs three core blocks: OnInit (setup), OnTick (the trading logic), and OnDeinit (cleanup) — get these right before adding complexity
- Always backtest and forward-test on a demo account first; spreads, commissions and slippage assumptions in the Strategy Tester can differ from live conditions
- Use the PipTax cost tool to check real trading costs on your chosen broker before letting any EA trade live money
- Keep your first EA simple — one entry rule, one exit rule, fixed lot size — and only add features once you understand why each line of code exists
Frequently asked questions
- Do I need to know how to code to build an Expert Advisor?
- You need basic programming logic — variables, if/then conditions, loops — but not a computer science degree. MQL4 and MQL5 are simplified, C-like languages built specifically for trading. Most traders learn enough in a few weeks of practice to build simple rule-based EAs.
- Should I learn MQL4 or MQL5 first?
- Check which platform version your broker's servers actually run — Pepperstone, for example, offers both MT4 and MT5 servers, and IG runs its own platform alongside MetaTrader options. MQL5 is the more modern language and worth learning if you're starting fresh, but MQL4 still dominates older strategy libraries.
- Can I just buy an EA instead of building one?
- You can, but you won't understand its logic, risk controls, or failure modes. This module exists so you can read, adapt and eventually build your own — which matters far more once markets shift away from whatever conditions the EA was built for.
- Will my EA work the same live as it does in backtesting?
- Not necessarily. Backtests often use simplified spread and slippage models. Always forward-test on a demo account, and use a live cost comparison via the PipTax cost tool so you know your actual spread and commission before going live.
- What's the biggest mistake beginners make with their first EA?
- Overcomplicating it. Adding multiple indicators, trailing stops, and news filters before you've verified the basic entry/exit logic works reliably just makes bugs harder to find. Start minimal.
- Is automated trading less risky than manual trading?
- No — it removes emotional decision-making but not market risk. An EA will follow its rules faithfully even into a losing streak or a broken market regime. Automation changes how you lose money, not whether you can.