MQL5 Expert Advisor Basics for Beginners: Build Your First Trading Robot
Not financial advice. 2GS Trading is not a registered Financial Services Provider (FSP) under the FSCA. This article is for general educational purposes only and does not constitute personalised financial advice. Trading forex and CFDs carries a high level of risk and you could lose some or all of your capital. Past performance is not indicative of future results.
Read our full Disclaimer for details.
Introduction
So you want to build your own trading robot? That's exactly what an MQL5 Expert Advisor (EA) does — automates your trading decisions based on pre-defined rules. For beginners, the idea might sound overwhelming, but it's more approachable than you think. This guide covers the MQL5 Expert Advisor basics for beginners, walking you through the core concepts, essential functions, and a simple example you can build right now.
Automated trading is growing fast among South African traders. Whether you trade gold (XAUUSD), forex pairs, or indices, an EA can help you execute trades without sitting at the screen 24/7. But before you rush to deploy an EA on a live account, you need to understand how they work under the hood.
What is an MQL5 Expert Advisor?
An Expert Advisor is a program written in MQL5 that runs inside the MetaTrader 5 (MT5) terminal. It can analyze price data, apply technical indicators, and place trade orders automatically. Think of it as your personal assistant — always watching the markets and executing trades according to your strategy.
Every EA starts with a blank template. The MQL5 Wizard inside MetaTrader 5 can generate this for you. When you create a new Expert Advisor in the terminal (via Navigator → Expert Advisors → Create), you get three main functions:
- OnInit() – runs once when the EA starts (used for initial setup)
- OnDeinit() – runs when the EA is removed (used for cleanup)
- OnTick() – runs on every new price tick (this is where your trading logic lives)
Only OnTick() is mandatory. A minimal EA template looks like this:
//+------------------------------------------------------------------+
//| SimpleEA.mq5 |
//+------------------------------------------------------------------+
input double LotSize = 0.1;
input int StopLoss = 30;
input int TakeProfit = 60;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Your trading logic goes here
}
//+------------------------------------------------------------------+
Key MQL5 Concepts You Need to Know
Before you start coding, master these terms. They appear in every EA you'll write or modify.
Trade Orders
An order is a message sent to the broker's server indicating your intent to buy or sell a specific instrument at a specific price. Orders can be market orders (executed immediately) or pending orders (executed when price reaches a certain level, like Buy Stop or Sell Limit).
Trade Requests (MqlTradeRequest)
To place an order, you fill a structure called MqlTradeRequest. It contains fields like:
action(TRADE_ACTION_DEAL for market orders)symbol(e.g., "XAUUSD")volume(lot size)type(ORDER_TYPE_BUY or ORDER_TYPE_SELL)price(optional for market orders)slandtp(stop loss and take profit)magic(a unique number so your EA can identify its own orders)
Trade Results (MqlTradeResult)
After sending a request, the server responds with an MqlTradeResult structure that tells you if the order was accepted, the deal ticket number, and any error codes.
Positions and Deals
- Position: An open trade (buy or sell). On netting accounts, only one position per symbol is allowed; on hedging accounts, multiple positions can exist.
- Deal: The actual executed trade that appears in your account history.
Building Your First EA: A Simple Moving Average Crossover
Let's build a basic EA that trades when a fast Moving Average crosses above or below a slow one. This is a common starting point to learn EA structure.
Step 1: Define Inputs
Inputs let you adjust the EA without recompiling.
input double LotSize = 0.01;
input int FastMA = 8;
input int SlowMA = 21;
input int StopLoss = 30;
input int TakeProfit = 60;
input int MagicNumber = 12345;
Step 2: Initialize Handles in OnInit
To use indicators, you need to create handle indices.
int fastHandle, slowHandle;
int OnInit()
{
fastHandle = iMA(_Symbol, _Period, FastMA, 0, MODE_SMA, PRICE_CLOSE);
slowHandle = iMA(_Symbol, _Period, SlowMA, 0, MODE_SMA, PRICE_CLOSE);
if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
return(INIT_FAILED);
return(INIT_SUCCEEDED);
}
Step 3: Write the Tick Logic
In OnTick(), copy indicator buffers into arrays, check for crossovers, and send orders.
void OnTick()
{
double fast[], slow[];
ArraySetAsSeries(fast, true);
ArraySetAsSeries(slow, true);
CopyBuffer(fastHandle, 0, 0, 3, fast);
CopyBuffer(slowHandle, 0, 0, 3, slow);
// Check for crossover: fast > slow and previous fast <= slow
if(fast[1] > slow[1] && fast[2] <= slow[2])
{
// Buy signal
if(!PositionExists(MagicNumber))
{
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_DEAL;
req.symbol = _Symbol;
req.volume = LotSize;
req.type = ORDER_TYPE_BUY;
req.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
req.sl = req.price - StopLoss * _Point;
req.tp = req.price + TakeProfit * _Point;
req.magic = MagicNumber;
OrderSend(req, res);
}
}
else if(fast[1] < slow[1] && fast[2] >= slow[2])
{
// Sell signal
if(!PositionExists(MagicNumber))
{
MqlTradeRequest req = {};
MqlTradeResult res = {};
req.action = TRADE_ACTION_DEAL;
req.symbol = _Symbol;
req.volume = LotSize;
req.type = ORDER_TYPE_SELL;
req.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
req.sl = req.price + StopLoss * _Point;
req.tp = req.price - TakeProfit * _Point;
req.magic = MagicNumber;
OrderSend(req, res);
}
}
}
Step 4: Helper Function to Avoid Duplicate Positions
Add a function that checks if a position from this EA already exists.
bool PositionExists(int magic)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
if(PositionGetInteger(POSITION_MAGIC) == magic)
return true;
}
return false;
}
Backtesting Your EA
Never run a new EA on a live account. Use the MT5 Strategy Tester to backtest it on historical data. Adjust inputs like Stop Loss, Take Profit, and lot size to see how they affect performance. Pay attention to the drawdown and profit factor.
For South African traders, backtest on XAUUSD (gold) or ZAR pairs like USDZAR to see how your EA handles local volatility.
Common Mistakes Beginners Make
- Forgetting Magic Numbers: Without a unique magic number, your EA might close orders placed by other EAs or manually.
- Ignoring Server Responses: Always check
res.retcodeafterOrderSend()to handle errors like insufficient margin or symbol not allowed. - No Risk Management: A simple EA might over-trade or risk too much per trade. Always set Stop Loss and position sizing rules.
- Overfitting: Optimizing inputs on too little data can lead to an EA that only works in the backtest but loses in live markets.
Going Beyond the Basics
Once you're comfortable with simple crossovers, explore:
- Pending orders (Buy Stop, Sell Limit) for breakout strategies
- Trailing stops using
PositionModify() - Multi-timeframe analysis (fetch data from a higher timeframe)
- Risk management (fixed fractional or Kelly criterion)
For a structured learning path and live mentorship, check out Project G – a trading education program by Chris Market Bull and Keegan Van Dyk. If you prefer ready-made tools, the IRON2000 TradingView indicator can help you identify high-probability setups manually while you learn EA coding.
Risk Disclosure
This content is for educational purposes only and does not constitute financial advice. Trading forex and CFDs carries a high risk of loss and may not be suitable for all investors. 2GS Trading is not a licensed Financial Services Provider (FSP) under the FSCA. Past performance of any trading system or EA is not indicative of future results. Always test thoroughly on a demo account before live deployment.
Frequently Asked Questions
Do I need programming experience to create an MQL5 Expert Advisor?
Some basic programming knowledge helps, but beginners can start with the MQL5 Wizard templates. Articles like the MQL5.com tutorial provide step-by-step guidance. With practice, you can write simple EAs without prior coding experience.
What is the difference between an Expert Advisor and a custom indicator?
An Expert Advisor can place trades automatically and uses OnTick() to execute trading logic. A custom indicator only draws on the chart (using OnCalculate()) and cannot place orders. You can use an EA that references your custom indicator for entry signals.
How can I test my EA without risking real money?
Use the integrated Strategy Tester in MT5. It simulates historical tick data so you can evaluate performance. Always forward-test on a demo account for at least a few weeks before going live.
What does the Magic Number do in an EA?
The Magic Number is a unique identifier that helps your EA recognize its own orders. Without it, the EA might close or modify orders placed by other EAs or the trader manually, leading to unintended behavior.
Can I use an EA on any broker's MT5 platform?
Yes, EAs are platform-agnostic as long as the broker offers MT5. However, check if the broker allows automated trading, especially on cent accounts or during news events. South African traders using brokers like XM (with the 2GSGOLD cashback code) can run EAs on standard accounts.
How do I handle errors when sending trade orders?
After calling OrderSend(), check res.retcode. Common codes include TRADE_RETCODE_DONE (success) and TRADE_RETCODE_NO_MONEY (insufficient margin). Always include error logging to diagnose issues quickly.
Conclusion
MQL5 Expert Advisor basics for beginners are easier to grasp than most traders think. Start with a simple template, add a crossover strategy, and backtest diligently. The path from beginner to confident EA developer requires patience, but the rewards — automation and consistency — are worth it.
Ready to take your trading to the next level? Join a community of like-minded traders in Project G and learn to build strategies that match your personal risk profile. Or if you want a powerful visual tool first, try IRON2000 to identify setups manually while you master EA coding.
Project G Mentorship
Live trading mentorship with Chris & Keegan.
IRON2000 Indicator
Institutional-grade TradingView indicator.
About the authors
Chris Market Bull
Co-Founder & Lead Trader
Co-founder of 2GS Trading and an intra-day Gold (XAUUSD) specialist. Chris streams live trading every weekday and leads the Project G mentorship.
More Trading Insights
Forex Session Overlaps: Best Trading Windows for South African Traders (2026 Guide)
Discover the best forex session overlaps for South African traders in 2026. Learn which windows offer the highest liquidity, tightest spreads, and most reliable signals — and how to tailor them to SAST.
Stablecoins in Forex and Crypto Trading Explained: A South African Trader’s Guide
Learn how stablecoins like USDT and USDC work in forex and crypto trading, their risks, and how South African traders can use them for faster deposits and market analysis.
MQL5 Expert Advisor Basics for Beginners: Build Your First Trading Robot
Learn the fundamentals of MQL5 Expert Advisor programming for MetaTrader 5. This beginner-friendly guide covers EA structure, the MQL5 Wizard, trade events, and how South African traders can start automating strategies.
Not financial advice. 2GS Trading is not a registered Financial Services Provider (FSP) under the FSCA. This article is for general educational purposes only and does not constitute personalised financial advice. Trading forex and CFDs carries a high level of risk and you could lose some or all of your capital. Past performance is not indicative of future results.
Read our full Disclaimer for details.