XAUUSD Gold EA in MQL5 (2026) | ATR, Spread Filter, Session Rules

Build a practical Gold (XAUUSD) Expert Advisor for MetaTrader 5: spread limits, session filters, ATR-based stops, and robust execution logic with clear MQL5 steps.

📖 15 min read

📝 2,926 words

🏷️ MQL5 and Expert Advisors

Share this article:

Build an EA for Gold (XAUUSD) in MQL5: Sizing, Stops, Spread and an ATR Filter

How Should You Build an MT5 EA for Gold (XAUUSD)?

Short answer: an EA for gold must read the symbol from your broker instead of reusing forex numbers. Read the money value of a price move (tick size, tick value, contract size) to size each trade from its stop, the stop and freeze levels to place valid stops, and the volume step to round the lot. Add a spread limit and a volatility filter, use an ATR-based stop, trade one position at a time with no grid and no martingale, and test on real ticks of your broker's XAUUSD before a demo run. This guide shows each step, a no-code version (an RSI rule with an ATR filter in the AlfaTactix Strategy Builder), and the MQL5 it generates.

This page gives procedures, not typical values: gold's contract size, spread and stop level differ between brokers and account types, so every number you need comes from your own terminal. It shows no backtest results.

Part of the MQL5 and Expert Advisors academy.


Why Gold Is Not EURUSD: Read It From Your Broker

WhatRead it withWhy it matters on gold
Contract sizeSYMBOL_TRADE_CONTRACT_SIZEHow many ounces one lot is; it differs between brokers
Tick size and tick valueSYMBOL_TRADE_TICK_SIZE, SYMBOL_TRADE_TICK_VALUEThe money one price step is worth per lot: the base of the lot size
Digits and pointSYMBOL_DIGITS, SYMBOL_POINTA "point" on gold is not a forex pip, so pip-based code is wrong here
Stop and freeze levelSYMBOL_TRADE_STOPS_LEVEL, SYMBOL_TRADE_FREEZE_LEVELThe nearest a stop may be, and the zone where an order cannot be changed
Volume limitsSYMBOL_VOLUME_MIN, SYMBOL_VOLUME_STEP, SYMBOL_VOLUME_MAXThe lot must be a multiple of the step
SpreadSYMBOL_SPREADWider at the daily rollover and in thin hours
Trading hoursThe symbol's sessionsGold CFDs often have a daily break; an order then fails

In MQL5, the price and money properties come from SymbolInfoDouble (opens in a new tab) [1]; the full list of symbol properties [2] explains each one. Without code: in MetaTrader 5, open Market Watch, right-click your gold symbol and choose Specification [3]. Write down the values, because the next sections use them. Integer properties such as the spread and the stop level come from SymbolInfoInteger [4], and the trading hours from SymbolInfoSessionTrade [5].


Lot Size for Gold From Tick Value

Size every trade from its stop, never from a fixed lot:

  • money lost per 1.0 lot at the stop = stop distance ÷ tick size × tick value;
  • lots = the money you risk ÷ that loss, rounded down to the volume step;
  • below the minimum volume, skip the trade rather than round up.

Worked example (an example specification, not a broker quote): if your Specification window shows a tick size of 0.01 and a tick value of 1.00 in your account currency, a stop 5.00 away from the entry is 500 ticks, so 1.0 lot loses 500 at the stop. Risking 1 % of a 10,000 account (100) gives 100 ÷ 500 = 0.2 lots, rounded down to your volume step. With a different contract size the tick value changes, and so does the lot: that is why the EA must read it.

More on position size, daily loss limits and drawdown: EA risk management.


Stops, Spread and Sessions on XAUUSD

Stops. A stop copied from a forex EA in pips means nothing on gold. An ATR multiple sizes the stop from recent volatility: wider when the market moves a lot, tighter when it is calm. Whatever the method, the stop must also clear the stop level plus the spread, or the order is refused with error 10016: see MT5 error 10016.

Spread. Gold's spread changes during the day. Read SYMBOL_SPREAD (opens in a new tab) during the hours your EA trades and set the limit from what you see. A limit tied to volatility, "the spread is at most a share of the ATR", needs no fixed number.

Sessions. Many rule-based gold EAs trade only the London and New York sessions and skip the thin hours and the daily break. Check your broker's trading hours for the symbol before you choose.

Volatility filter. A simple filter that keeps the EA out of flat, quiet markets is "ATR(14) above its 50-bar average"; the builder offers it as the quick filter Skip quiet markets.


No Grid, No Martingale

Many gold EAs sold online add orders as the price moves against them (a grid) or raise the size after a loss (martingale). Both turn a run of ordinary losses into one large loss, and a backtest that ended before that run shows nothing of it. Before you run any gold EA, read its settings for "grid", "step", "multiplier" or "recovery".

The AlfaTactix builder has no grid of orders and no martingale (raising the size after a loss); Tactix Studio says so and builds neither. Studio never sets risk above 10 % of the account per trade.


Build a Gold EA Without Code: RSI Rule and ATR Filter

The AlfaTactix Strategy Builder is a form in 7 steps. One set of rules, built for MQL5 or Pine Script v6: a strategy is built for one platform at a time, and Step 1 switches it. Here is the gold recipe from the demo:

StepWhat you set
1. Information and platformName, MetaTrader 5 (MQL5), market: Metals (gold and silver, such as XAUUSD)
2. TimeframesH1 as the Trading timeframe
3. Entry rulesBuy rule: RSI(14) crosses above its oversold level (30); switch on Sell mirrors Buy: sell when RSI(14) crosses below its overbought level (70)
4. FiltersMarket sessions: London and New York; the quick filter Skip quiet markets (ATR(14) above its 50-bar average); a Spread limit as A share of the ATR where your plan has it
5. ExitsStop loss as an ATR multiple (fixed when the trade opens); Take profit as an R multiple, or Exit by signal
6. Risk and money managementRisk per trade (% of the account); Open positions: 1; a Daily loss limit
7. Review and saveFix the Check list, Save strategy, then Backtest this strategy or Get the code
AlfaTactix Strategy Builder, Step 3 Entry rules: buy when RSI(14) on H1 crosses above its oversold level (30); the sell rule mirrors it
AlfaTactix Strategy Builder, Step 3 Entry rules: buy when RSI(14) on H1 crosses above its oversold level (30); the sell rule mirrors it

Step 3 reads the rule back in plain words: buy when RSI(14) · H1 crosses above its oversold level (30); sell when it crosses below its overbought level (70).

AlfaTactix Strategy Builder, Step 4 Filters: London or New York session open, and ATR(14) above the SMA(50) of ATR(14)
AlfaTactix Strategy Builder, Step 4 Filters: London or New York session open, and ATR(14) above the SMA(50) of ATR(14)

Step 4 shows both filters in the summary: the session, and ATR(14) · H1 above SMA(50) of ATR(14). The spread limit is not on every plan, and the public demo shown here has none.

RSI settings in the builder: Length 2 to 200 (default 14), Overbought level 50 to 100 (default 70), Oversold level 0 to 50 (default 30), Price close by default. The rule "crosses above" is true only on the bar where RSI passes the level. More RSI rules: RSI overbought/oversold EA, no code and the RSI indicator.

A trend version. Keep Steps 4 to 7 and change Step 3 to a moving-average cross, for example EMA(20) crosses above EMA(50): see the MA crossover recipe.

If you prefer to describe the idea in a sentence, Tactix Studio fills the same form: it never writes code, you see every change and save it yourself. More on the form: MT5 EA builder.


What the Generated MQL5 Looks Like

The code generators are fixed programs with no AI model inside: the same strategy document and the same generator release always produce the same file, byte for byte. Every generated file names the generator version in its header. The lines below are copied unchanged from the .mq5 file the generator writes for one of our golden test strategies, "Relative spread", by generator version 1.0.0. It has the same ATR filter as the gold recipe and risks 1 % of equity per trade; // … marks where we skipped lines.

mql5
//| AlfaTactix Strategy Builder v2 - MQL5 Expert Advisor
//| Strategy: Relative spread
// …
//| generator version: 1.0.0
// …
    g_sym.tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
    g_sym.tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
    g_sym.contract_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
    g_sym.volume_min = g_state.volume_min;
    g_sym.volume_step = g_state.volume_step;
    g_sym.volume_max = g_state.volume_max;
    g_sym.stops_level_points = (double)g_state.stops_level_points;
// …
    if(side == ATV2_LONG) // risk_percent
    {
        double risk_cash = equity * 1.0 / 100.0; // base = equity
        if(stop_distance == ATV2_NONE || stop_distance <= 0.0)
            return 0.0; // the risk types need a positive stop distance
        raw = risk_cash / ((stop_distance / g_sym.tick_size) * g_sym.tick_value);
        return ATV2_Fit(raw);
    }
// …
// fit a volume to the symbol: rounded down to the volume step, capped at the maximum, 0.0 (skipped) below the
// minimum or at 0
// …
    g_r_ov2 = ATV2_SerAt(g_atr_1.out_atr, 0); // atr_1.atr
    ATV2_SerPush(g_r_or2, g_r_ov2);
    g_r_ov3 = ATV2_SmaOf(g_r_or2, 50); // SMA(50) of operand 2
// …
    // /filters/items/3/when: cmp
    g_r_n1 = g_r_ov2 != ATV2_NONE && g_r_ov3 != ATV2_NONE && g_r_ov2 > g_r_ov3;

What this shows:

  • The EA reads tick size, tick value, contract size, the volume limits and the stop level from the broker when it starts; nothing is hard-coded.
  • The lot is the formula above: 1 % of equity ÷ (stop distance ÷ tick size × tick value), then rounded down to the volume step and skipped below the minimum.
  • The ATR filter is ATR above its 50-bar SMA, the same as Skip quiet markets.
  • The generated code uses no platform indicator built-ins: every indicator, the ATR included, is written out in the code you download, so you can read it.
  • All 29 golden Expert Advisors compile in MetaEditor with 0 errors and 0 warnings.

How we check the generators: How we test and MQL5 and Pine generators.


Backtest on Your Own XAUUSD Data

In Step 7, Backtest this strategy opens the AlfaTactix backtest, which tests the same rules on the site with your own data. Set it up with the costs of the account you will trade:

  • Costs: the spread, the commission, the slippage in points, and the swap. For metals the triple-swap day is set to Wednesday automatically; change it if your broker uses another day.
  • Mode: "Bars only", "1-minute data inside each bar" (like MT5's "1 minute OHLC") or "Real ticks" (like "Every tick based on real ticks").
  • Length: a run can use any timeframe down to one minute; how many days one run covers depends on your plan (Pricing).

How the engine compares with the MetaTrader 5 tester, and its limits: Backtest engine.

A backtest is hypothetical: it uses past prices and perfect rules. Past results don't predict future results.


Test in the MT5 Strategy Tester

Before a demo run, test the downloaded EA in MetaTrader 5:

  1. Copy the .mq5 file to MQL5/Experts and compile it in MetaEditor (F7).
  2. In the Strategy Tester choose your broker's exact gold symbol (XAUUSD, GOLD or a name with a suffix), H1, and your deposit currency.
  3. Use Every tick based on real ticks when the broker has tick history. The help page on real and generated ticks (opens in a new tab) [6] explains each mode.
  4. Check the Journal for 10016 (stops) and 10014 (volume) errors before you read any result.
  5. Run the same settings on a demo account and compare its spreads and fills with the test.

Full walkthrough: Backtest an EA in the Strategy Tester.


Tune the Gold RSI Recipe After the First Test

Change one setting at a time and test each change on a second stretch of data, so you know which change did what.

What you seeLikely causeWhat to change in the builder
Trade after trade while RSI stays lowThe rule uses is at or below 30, which is true on every bar inside the zoneUse crosses above, or put both in an All of these group: RSI is at or below 30 and crosses above its oversold level
Losses against a strong trendRSI can stay overbought or oversold for hours while gold trendsStricter levels (75 and 25), or a trend condition such as EMA(20) above EMA(50), or a higher timeframe in Step 2
Signals come lateLength 14 reacts slowly to fast gold movesTry a Length of 9 to 11
Stops hit by ordinary noiseThe ATR multiple is too small for the hourStart near 1.5 to 2 × ATR, still beyond the stop level
Entries in thin hoursWhen any of them is open trades either sessionOnly when all are open at the same time keeps only the London and New York overlap

Get the plain 30/70 crossing working first; stacking every condition on day one makes a test impossible to read.

On a funded account. Check that the firm allows XAUUSD and what lot limits it sets, put Step 6's Daily loss limit and Maximum drawdown below the firm's limits, and test with the spread of your account type. If the firm restricts trading around news, its rules say which hours to avoid: Prop firm rules for an EA.


If You Code It Yourself

A hand-written lot function that follows the procedure above:

mql5
// Lots that lose about riskMoney (account currency) if price moves stopDistance (price units) against the trade
double LotsForRisk(const double riskMoney, const double stopDistance)
{
   double tickSize  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double volStep   = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double volMin    = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double volMax    = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   if(tickSize <= 0.0 || tickValue <= 0.0 || volStep <= 0.0 || stopDistance <= 0.0)
      return 0.0;
   double lossPerLot = stopDistance / tickSize * tickValue;          // money lost by 1.0 lot at the stop
   double lots = MathFloor(riskMoney / lossPerLot / volStep) * volStep; // rounded down to the step
   if(lots < volMin)
      return 0.0;                                                   // too small: skip the trade
   return MathMin(lots, volMax);
}

To check the result, OrderCalcProfit() [7] returns the profit or loss of a given volume between two prices in the account currency. If you compute the ATR yourself, iATR() [8] returns a handle to the platform's ATR. Return codes such as 10016 and 10014 are listed under trade return codes (opens in a new tab) [9]. The whole language is in the MQL5 Reference [10].


Troubleshooting

ProblemLikely causeFix
10016 invalid stopsStop or target inside the stop levelRead SYMBOL_TRADE_STOPS_LEVEL; widen the stop (10016 guide)
10014 invalid volumeLot not a multiple of the volume stepRound down to SYMBOL_VOLUME_STEP
10019 not enough moneyThe margin of the lot is above the free marginSize from the stop and risk; check the margin before sending
10018 market closedThe daily break or the weekendTrade only inside the symbol's sessions
Zero trades in a testA spread limit below the spread of the dataCompare the limit with the data's spread

More errors: Common MQL5 EA errors.


A well-known rule with gold in its history. Gold was among the markets the trainees of the channel breakout 20/10 traded in the 1980s, and our library file for it is set up for metals. No source says the rule was made for gold. It needs the Trader plan or higher. Its history and rules.

Next Steps

References: SymbolInfoDouble [1], symbol properties [2], Market Watch [3], SymbolInfoInteger [4], SymbolInfoSessionTrade [5], Real and Generated Ticks [6], OrderCalcProfit [7], iATR [8], trade return codes [9], MQL5 Reference [10].

Frequently Asked Questions

The money value of a price move, the contract size, the number of digits, the stop level and the volume step of gold all differ from a currency pair, and they differ between brokers. An EA that copies EURUSD numbers sizes and places its trades wrongly. Read them at run time with SymbolInfoDouble() and SymbolInfoInteger(), or open Market Watch, right-click XAUUSD and choose Specification.

Measure it instead of copying a number: watch SYMBOL_SPREAD on your account during the hours the EA trades, and set the limit just above the normal value. A limit tied to volatility (the spread as a share of the ATR) follows gold's quieter and busier hours without a fixed number.

Gold's moves in price are larger and change more from hour to hour than a major pair's. A stop of a fixed size is too tight in a busy hour and too wide in a quiet one. A multiple of the ATR scales with recent volatility; check that it still clears the broker's stop level.

Money lost per 1.0 lot at the stop = stop distance ÷ SYMBOL_TRADE_TICK_SIZE × SYMBOL_TRADE_TICK_VALUE. Lots = the money you risk ÷ that loss, rounded down to SYMBOL_VOLUME_STEP; skip the trade below SYMBOL_VOLUME_MIN. The function is in this guide.

Rule-based gold EAs often use H1 or H4, where a bar's range is large next to the spread. On M5 or M15 the costs weigh much more: run the cost checks of the Scalping EA guide first.

No. The builder has no grid of orders and no martingale (raising the size after a loss); Tactix Studio says so and builds neither, and it never sets risk above 10 % of the account per trade.

Yes. In the Strategy Builder choose Metals in Step 1, H1 in Step 2, a rule such as RSI(14) crosses above its oversold level in Step 3, the sessions and "Skip quiet markets" in Step 4, an ATR-multiple stop in Step 5 and risk per trade in Step 6. Step 7 saves it, backtests it on your data and gives the .mq5 file. Try it in the demo.

On H1 XAUUSD, start with Length 14, overbought 70, oversold 30 and the close price, and use "crosses above" or "crosses below" the level so a rule fires once, not on every bar inside the zone. Only after a test, try a Length of 9 to 11 for faster signals or levels of 75 and 25 for fewer trades against a trend, one change at a time.

Only if the firm allows XAUUSD and your settings fit its rules: set the daily loss limit and the maximum drawdown in Step 6 below the firm's limits, keep within its lot limits, and test with your account type's spread. See Prop firm rules for an EA.

The stop or target is closer to the price than the broker's SYMBOL_TRADE_STOPS_LEVEL allows. Read it at run time and keep every stop beyond it: see MT5 error 10016.

References

  1. MetaQuotes, MQL5 Reference. SymbolInfoDouble. https://www.mql5.com/en/docs/marketinformation/symbolinfodouble
  2. MetaQuotes, MQL5 Reference. Symbol Properties. https://www.mql5.com/en/docs/constants/environment_state/marketinfoconstants
  3. MetaQuotes, MetaTrader 5 Help. Market Watch. https://www.metatrader5.com/en/terminal/help/trading/market_watch
  4. MetaQuotes, MQL5 Reference. SymbolInfoInteger. https://www.mql5.com/en/docs/marketinformation/symbolinfointeger
  5. MetaQuotes, MQL5 Reference. SymbolInfoSessionTrade. https://www.mql5.com/en/docs/marketinformation/symbolinfosessiontrade
  6. MetaQuotes, MetaTrader 5 Help. Real and Generated Ticks. https://www.metatrader5.com/en/terminal/help/algotrading/tick_generation
  7. MetaQuotes, MQL5 Reference. OrderCalcProfit. https://www.mql5.com/en/docs/trading/ordercalcprofit
  8. MetaQuotes, MQL5 Reference. iATR. https://www.mql5.com/en/docs/indicators/iatr
  9. MetaQuotes, MQL5 Reference. Return Codes of the Trade Server. https://www.mql5.com/en/docs/constants/errorswarnings/enum_trade_return_codes
  10. MetaQuotes, MQL5 Reference. MQL5 Reference. https://www.mql5.com/en/docs