MQL5 Expert Advisor basics for beginners

MQL5 Expert Advisor Basics for Beginners: Build Your First Trading Robot

Chris Market Bull & Keegan Van Dyk··7 min read
a computer screen with a bunch of buttons on it
Photo by Ferenc Almasi on Unsplash

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

If you're a South African trader looking to take your forex and gold (XAUUSD) trading to the next level, learning to code your own Expert Advisor (EA) in MQL5 is a powerful skill. EAs allow you to automate your trading strategies, remove emotional decision-making, and backtest ideas quickly. This guide covers the absolute basics of MQL5 Expert Advisor programming, tailored for beginners with no prior coding experience.

Whether you trade USD/ZAR or gold through brokers like XM (our partner with cashback code 2GSGOLD), understanding how to build an EA gives you an edge. By the end of this article, you'll know the core components of an EA, how to use the MQL5 Wizard, and where to go next to develop your own automated systems.

What is an Expert Advisor?

An Expert Advisor is a program written in MQL5 that runs inside MetaTrader 5. It automatically analyses market data (price, indicators) and can send trade orders to your broker. As the MQL5 documentation explains, every EA starts with a template created by the MQL5 Wizard, which generates three essential event handler functions:

  • OnInit() – runs once when the EA is loaded, used for initial setup (e.g., loading indicators)
  • OnDeinit() – runs when the EA is removed, used for cleanup
  • OnTick() – runs on every price tick; this is where your trading logic lives

These functions respond to events in the terminal. Understanding events is key to building reliable EAs.

The Structure of an EA

When you create a new EA using the MQL5 Wizard, you get a skeleton like this example from MQL5. The wizard asks if you want to include handlers for trade transactions, timer events, chart events, etc. For beginners, it's best to start with a minimal template.

Here's the basic structure:

//+------------------------------------------------------------------+
//|                                                    MyFirstEA.mq5 |
//|                                                      Your Name   |
//+------------------------------------------------------------------+
#property copyright "Your Name"
#property link      "https://www.2gstrading.co.za"
#property version   "1.00"

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   //---
   //---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   //---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   //---
   
  }
//+------------------------------------------------------------------+

Only OnTick() is mandatory. OnInit and OnDeinit are optional but recommended for managing resources.

Key Concepts: Orders, Positions, and Deals

Before writing logic, you must understand the terminology used in MetaTrader 5. The MQL5 article on EA development defines these clearly:

  • Order – a message sent to the server indicating your intent to buy or sell (e.g., market order, pending order).
  • Deal – the actual execution when an order is filled (price, volume, time).
  • Position – an open trade resulting from one or more deals.

Every EA uses the MqlTradeRequest structure to send orders and receives results in MqlTradeResult. You can use synchronous mode (OrderSend()) or asynchronous mode (OrderSendAsync()). Asynchronous mode allows your EA to continue processing while waiting for a server response, which is more efficient.

Building Your First EA: A Simple Moving Average Crossover

One of the most common beginner EAs is a Moving Average crossover. The MQL5 beginner tutorial walks through an EA that uses two MAs and an ADX filter. Here's a simplified version for South African traders:

Step 1: Define Input Parameters

input int MAPeriod = 8;
input double LotSize = 0.01;
input int StopLossPips = 30;
input int TakeProfitPips = 100;

Step 2: Check for New Bar

To avoid multiple signals on the same bar, track the last bar time:

datetime lastBarTime = 0;

void OnTick()
  {
   if(Time[0] == lastBarTime) return;
   lastBarTime = Time[0];
   // Continue with logic
  }

Step 3: Get Moving Average Values

Load the iMA indicator in OnInit() and then use CopyBuffer() in OnTick().

Step 4: Entry Conditions

  • Buy if price closes above MA and MA is rising.
  • Sell if price closes below MA and MA is falling.

Step 5: Send Order

Use MqlTradeRequest and OrderSend() or OrderSendAsync(). Remember to set a magic number to identify your EA's trades.

Important: The example EAs in the MQL5 articles are not suitable for live trading without additional error handling and validation. Always backtest thoroughly.

Using Indicators in Your EA

You can incorporate any built-in or custom indicator. For instance, the IRON2000 indicator from 2GS Trading is a powerful structure analysis tool that could be called from an EA to identify key levels. However, for beginners, start with built-in indicators like Moving Average, RSI, or Bollinger Bands.

Synchronous vs Asynchronous Trading

When you send an order, your EA can either wait for the server response (synchronous) or continue processing (asynchronous). The MQL5 article on EA basics recommends asynchronous for live trading because it prevents the EA from freezing on network delays. The OnTradeTransaction() event handler processes confirmations.

Local Context: South African Traders

South African traders often use offshore brokers like XM (which 2GS Trading partners with) because they offer competitive spreads on USD/ZAR and XAUUSD. When building EAs, ensure your broker's server is MT5-compatible. Also note that the Financial Sector Conduct Authority (FSCA) regulates forex trading in South Africa, but using EAs is legal as long as you comply with broker terms. If you're new to trading strategies, join our mentorship program Project G to learn robust, repeatable setups that can later be automated.

Practical Tips for Beginners

  1. Start with the MQL5 Wizard – it generates error-free code you can modify.
  2. Practice in the Strategy Tester – MetaTrader 5's backtester is excellent for debugging.
  3. Use a demo account – always test on a demo before live.
  4. Learn from the MQL5 community – the MQL5 articles are a goldmine.
  5. Consider a mentor – Project G provides live mentorship that includes strategy development.

Risk Disclosure

This content is for educational purposes only and does not constitute financial advice. Trading forex and Contracts for Difference (CFDs) carries a high level of risk and may result in the loss of your invested capital. Past performance does not guarantee future results. 2GS Trading is not a licensed Financial Services Provider (FSP) under the FSCA. Always seek independent professional advice and never risk more than you can afford to lose.

Frequently Asked Questions

What programming knowledge do I need to write MQL5 EAs?

You don't need to be a professional developer, but you should understand basic concepts like variables, functions, conditions (if-else), and loops. The MQL5 language is similar to C++. If you're new to programming, start with simple logic and use the Wizard heavily.

Can I use MQL5 with South African brokers?

Yes, most brokers that offer MetaTrader 5 accept MQL5 EAs. Brokers like XM (our partner) support automated trading on both demo and live accounts. Always check the broker's policy on algorithmic trading.

Is automated forex trading legal in South Africa?

Yes, automated trading is legal. The FSCA does not prohibit the use of Expert Advisors. However, your EA must comply with the broker's trading rules (e.g., minimum stop loss, maximum lot size).

How do I get started with 2GS Trading?

Visit our website to explore Project G – a live mentorship program covering trading psychology, gold setups, and strategy development. You can also use our IRON2000 indicator to enhance your chart analysis. For XM clients, use cashback code 2GSGOLD when registering.

What are the risks of using an EA?

EAs can lose money if the underlying strategy is flawed or if market conditions change. Technical failures (e.g., internet outage, broker server issues) can also cause losses. Never run an EA on a live account without thorough backtesting and forward testing on a demo.

Can I run multiple EAs on the same account?

Yes, but ensure each EA has a unique magic number to avoid interfering with each other's trades. Also be mindful of margin requirements and broker-imposed limits.

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.

Keegan Van Dyk

Co-Founder & Lead Trader

Co-founder of 2GS Trading focused on precision New York session scalping on NAS100 and Gold. Keegan builds the firm's trading tools and education.

More Trading Insights

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.