MT4 Tutorials / Trading Platforms · August 12, 2026 0

MT4 EA Development for Beginners: Build Your First XAUUSD Automated Trading Robot

Building your first Expert Advisor (EA) for MetaTrader 4 is easier than you think. Even if you have zero programming experience, you can learn MQL4 basics and create a working automated trading system in a weekend. This step-by-step guide walks you through building a complete XAUUSD trading EA — from installation to backtesting to live deployment.

MT4 EA Development Tutorial Beginner

What Is an EA (Expert Advisor)?

An Expert Advisor is an automated trading program that runs on the MetaTrader platform. It’s written in MQL4 (for MT4) or MQL5 (for MT5), and it can:

  • Analyze charts and indicators automatically
  • Open and close trades without manual input
  • Manage positions (stop loss, take profit, trailing stops)
  • Run 24/7 without you needing to watch the screen
  • Execute trading rules with perfect discipline

According to Finance Magnates 2026 report, over 45% of retail forex traders now use EAs or automated trading in some form. For XAUUSD specifically, EAs are especially popular because gold trades around the clock and systematic strategies work well with its trend-and-range patterns.

Prerequisites

Before you start building, you’ll need:

  • **MetaTrader 4 platform** — download from your broker (ECMarkets offers MT4 with tight XAUUSD spreads)
  • **MetaEditor** — included with MT4, this is where you write MQL4 code
  • **Basic understanding of trading** — you should know what stop loss, take profit, and indicators are
  • **Patience** — programming has a learning curve, but MQL4 is beginner-friendly

You don’t need a computer science degree. Many successful EA developers started with zero programming experience.

Setting Up Your Development Environment

Step 1: Install MT4 and Open MetaEditor

  • Download and install MT4 from your broker
  • Open MT4 and log in (demo account is fine for development)
  • Press F4 or click Tools → MetaQuotes Language Editor to open MetaEditor

MetaEditor is the built-in IDE for writing MQL4 code. It has syntax highlighting, debugging tools, and a built-in compiler.

Step 2: Create a New EA

In MetaEditor:

  • Click File → New
  • Select “Expert Advisor (template)”
  • Name it `FirstXAUUSDEA`
  • Click Next, Next, Finish

You’ll see a template with basic structure. Let’s understand it before modifying it.

MQL4 Basics: The 5 Core Functions

Every EA has a standard structure with these key functions:

1. OnInit() — Initialization

“`

int OnInit() { // Runs once when the EA is attached to a chart // Set up indicators, validate inputs return(INIT_SUCCEEDED); }

“`

2. OnDeinit() — Deinitialization

“`

void OnDeinit(const int reason) { // Runs once when the EA is removed or chart changes // Clean up resources }

“`

3. OnTick() — Main Logic

“`

void OnTick() { // Runs on every price tick (every time bid/ask changes) // This is where your trading logic goes }

“`

For most simple EAs, 90% of your code goes in `OnTick()`.

4. Input Parameters

These are settings you can adjust without editing the code:

“`

input double LotSize = 0.01; // Trading lot size input int StopLoss = 100; // Stop loss in points input int TakeProfit = 200; // Take profit in points input int FastMA = 10; // Fast moving average period input int SlowMA = 20; // Slow moving average period

“`

5. Key Built-in Functions

  • `iMA()` — Moving average value
  • `OrderSend()` — Open a new position
  • `OrderClose()` — Close a position
  • `OrdersTotal()` — Count open orders
  • `Point` — Current instrument’s point value
  • `Ask` / `Bid` — Current prices

Building Your First XAUUSD EA: Moving Average Crossover

We’ll build a simple but functional EA that trades the golden cross / death cross pattern on XAUUSD:

  • Buy when fast MA crosses above slow MA
  • Sell when fast MA crosses below slow MA
  • Fixed stop loss and take profit
  • Only one position at a time

Full Code

“`mql4

//+——————————————————————+ //| FirstXAUUSDEA.mq4 | //| Simple MA Crossover EA | //+——————————————————————+ #property copyright “Dongyi Trading” #property link “https://dongyitrade.com” #property version “1.00” #property strict

//— Input Parameters input double LotSize = 0.01; // Lot size input int FastMAPeriod = 10; // Fast MA period input int SlowMAPeriod = 30; // Slow MA period input int StopLossPips = 100; // Stop loss in pips (XAUUSD: 100 pips = $1) input int TakeProfitPips = 200; // Take profit in pips input int MagicNumber = 12345; // EA magic number

//+——————————————————————+ //| Expert initialization function | //+——————————————————————+ int OnInit() { // Check if we have enough parameters if(FastMAPeriod >= SlowMAPeriod) { Print(“Error: Fast MA period must be less than Slow MA period”); return(INIT_PARAMETERS_INCORRECT); }

Print(“XAUUSD MA Crossover EA initialized”); return(INIT_SUCCEEDED); }

//+——————————————————————+ //| Expert deinitialization function | //+——————————————————————+ void OnDeinit(const int reason) { Print(“EA removed from chart”); }

//+——————————————————————+ //| Expert tick function | //+——————————————————————+ void OnTick() { // Only trade if there are no open positions for this EA if(HasOpenPositions()) return;

// Get MA values double fastCurrent = iMA(_Symbol, _Period, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 0); double fastPrev = iMA(_Symbol, _Period, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1); double slowCurrent = iMA(_Symbol, _Period, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 0); double slowPrev = iMA(_Symbol, _Period, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);

// Check for bullish crossover (buy signal) if(fastPrev < slowPrev && fastCurrent > slowCurrent) { OpenBuyOrder(); }

// Check for bearish crossover (sell signal) if(fastPrev > slowPrev && fastCurrent < slowCurrent) { OpenSellOrder(); } }

//+——————————————————————+ //| Check if we have open positions | //+——————————————————————+ bool HasOpenPositions() { for(int i = 0; i < OrdersTotal(); i++) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if(OrderSymbol() == _Symbol && OrderMagicNumber() == MagicNumber) { return(true); } } } return(false); }

//+——————————————————————+ //| Open buy order | //+——————————————————————+ void OpenBuyOrder() { double sl = Ask – StopLossPips * Point; double tp = Ask + TakeProfitPips * Point;

int ticket = OrderSend(_Symbol, OP_BUY, LotSize, Ask, 3, sl, tp, “XAUUSD MA Crossover Buy”, MagicNumber, 0, clrGreen);

if(ticket > 0) { Print(“Buy order opened. Ticket: “, ticket, ” Price: “, Ask); } else { Print(“Buy order failed. Error: “, GetLastError()); } }

//+——————————————————————+ //| Open sell order | //+——————————————————————+ void OpenSellOrder() { double sl = Bid + StopLossPips * Point; double tp = Bid – TakeProfitPips * Point;

int ticket = OrderSend(_Symbol, OP_SELL, LotSize, Bid, 3, sl, tp, “XAUUSD MA Crossover Sell”, MagicNumber, 0, clrRed);

if(ticket > 0) { Print(“Sell order opened. Ticket: “, ticket, ” Price: “, Bid); } else { Print(“Sell order failed. Error: “, GetLastError()); } } //+——————————————————————+

“`

Understanding the Code

Let me break down the key parts:

  • **Input parameters** at the top are adjustable from MT4 without editing code
  • **OnInit()** validates that fast MA is less than slow MA
  • **OnTick()** runs on every price tick, checks for crossovers
  • **HasOpenPositions()** ensures we only have one trade at a time
  • **OpenBuyOrder() / OpenSellOrder()** execute the trades with SL/TP

Compiling and Testing

  • In MetaEditor, press F7 to compile
  • If there are no errors, you’ll see “0 errors, 0 warnings”
  • Go back to MT4, find your EA in the Navigator panel
  • Drag it onto a XAUUSD chart
  • Adjust settings in the Inputs tab
  • Click OK — your EA is now running!

Backtesting Your EA

Before risking real money, always backtest your EA extensively.

How to Use the Strategy Tester

  • In MT4, press Ctrl+R or click View → Strategy Tester
  • Select your EA from the Expert Advisor dropdown
  • Select XAUUSD as the symbol
  • Select timeframe (e.g., H1 or D1)
  • Set the date range (at least 1-2 years of data)
  • Set model to “Every tick” for most accurate results
  • Click Start

What to Look for in Backtest Results

Warning: Over-Optimization

Metric Good Caution Bad
Total profit Positive Breakeven Negative
Profit factor >1.5 1.0-1.5 <1.0
Max drawdown <20% 20-35% >35%
Win rate >50% 40-50% <40%
Number of trades >100 30-100 <30

A common beginner mistake is curve-fitting — tweaking parameters until the EA looks amazing on historical data but fails in live trading. To avoid this:

  • Test across multiple time periods (out-of-sample testing)
  • Don’t optimize too many parameters at once
  • Forward-test on demo before going live
  • Use walk-forward analysis if possible

Adding Advanced Features

Once you have a basic EA working, here are features to add:

1. Trailing Stop

“`

void TrailingStop() { for(int i = 0; i < OrdersTotal(); i++) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if(OrderSymbol() == _Symbol && OrderMagicNumber() == MagicNumber) { if(OrderType() == OP_BUY) { double newSL = Bid - TrailingStopPips * Point; if(newSL > OrderStopLoss() && Bid – OrderOpenPrice() > TrailingStopPips * Point) { OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0); } } // Similarly for sell orders… } } } }

“`

2. Filter by Time of Day

“`

bool IsTradingHours() { int hour = Hour(); // Only trade during London + NY sessions if(hour >= 8 && hour <= 20) return true; return false; }

“`

3. ATR-Based Stop Loss

“`

double atr = iATR(_Symbol, _Period, 14, 0); double stopDistance = atr * 2; // 2x ATR

“`

4. Multiple Position Management

  • Partial close at take profit
  • Breakeven stop after certain profit
  • Grid scaling logic

Common Beginner Mistakes

Mistake 1: Over-optimizing to historical data

As mentioned earlier, this is the #1 reason EAs fail in live trading. Keep it simple — fewer parameters means less overfitting risk.

Mistake 2: Not using a magic number

The magic number identifies which trades belong to your EA. Without it, your EA might interfere with manual trades or other EAs on the same chart.

Mistake 3: Ignoring slippage in backtesting

Backtests use perfect fills. In real trading, you’ll have slippage, especially during news events. Always account for at least 1-2 pips of expected slippage.

Mistake 4: Setting lot size too high

Beginners often use 0.1 or 1.0 lot for testing without considering account size. Always start small (0.01) and scale up carefully.

Mistake 5: Running EAs on your home computer

If your computer turns off or loses internet, your EA stops trading. Use a VPS (virtual private server) for 24/7 reliability. Many brokers including ECMarkets offer free VPS for qualifying clients.

Going Live: Checklist

Before putting real money on the line:

  • [ ] Backtested for at least 1 year on multiple time periods
  • [ ] Forward-tested on demo for 1-3 months
  • [ ] Profit factor above 1.5 in both backtest and forward test
  • [ ] Max drawdown under 25%
  • [ ] You understand the strategy logic (it’s not just a black box)
  • [ ] You’re using a VPS for 24/7 uptime
  • [ ] You start with small lot sizes (0.01)
  • [ ] You have a plan for when the EA underperforms

Frequently Asked Questions

Do I need programming experience to build an EA?

No, but it helps. MQL4 is a C-like language that’s relatively beginner-friendly. If you understand basic trading concepts and are willing to learn, you can build simple EAs within a week. Start with examples from the MQL4 documentation and modify them — that’s how most people learn. For more complex strategies, you might want to hire a developer or use a no-code EA builder.

How much does it cost to build an EA?

If you build it yourself, it’s free — just your time. If you hire a developer, simple EAs cost $50-$200, medium complexity EAs cost $200-$500, and complex strategies can cost $500-$2,000+. The MQL5 community marketplace has thousands of free and paid EAs. But always test thoroughly before using any EA with real money.

What’s the best EA strategy for XAUUSD?

There’s no “best” strategy — it depends on your risk tolerance and market conditions. Popular approaches for XAUUSD include: moving average crossover (trend following), grid trading (range markets), Bollinger Band mean reversion, and breakout strategies. The important thing is that the strategy logic makes sense to you and performs well in backtests across different market environments.

Can I run multiple EAs on the same account?

Yes, but you need to be careful. Each EA should have its own unique magic number so they don’t interfere with each other. Also, consider the combined risk — if you have 5 EAs each risking 2%, that’s 10% total risk, which might be more than you intended. Start with one EA, understand its behavior, then add more carefully.

Do I need a VPS to run an EA?

For any serious EA trading, yes, you need a VPS. If your home computer turns off, loses internet, or MT4 crashes, your EA stops trading and you could miss entries or exits. A VPS runs 24/7 in a data center close to your broker’s servers for minimal latency. Many brokers including ECMarkets offer free VPS for clients with sufficient deposit or trading volume.


🎯 Run Your EAs on ECMarkets

ECMarkets ECN: MT4/MT5 + tight XAUUSD spreads from 0.0 pips + free VPS.
Perfect for EA trading — low cost, fast execution, 24/7 reliability. Minimum deposit $1,000.

🔥 Open via exclusive link for 30% rebate on all trading costs!

Open Account with 30% Rebate →

Telegram: @DongyiTrade