Advertisement IC Markets

Scalping XAU/USD (gold) trading strategy

Share, develop, and backtest custom MQL4/MQL5 Expert Advisors, Python data-scraping scripts, trading bots, and automated market alert systems.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

Hi traders,

Genuine institutional complexity in XAU/USD scalping comes not from stacking redundant oscillators, but from synchronizing centralized futures order flow, cross-currency synthetic parity, fractal regime filtering, and asymmetric Anti-Martingale position scaling.

Because retail spot gold is an over-the-counter (OTC) derivative aggregated across fragmented liquidity providers, it frequently lags centralized exchange pricing while suffering abrupt spread expansions during thin liquidity. The 5-Layer Cross-Asset Microstructure & Adaptive Volatility Scalping Architecture (CAM-VSA) exploits those structural inefficiencies while gating out low-expectancy noise.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Recommended broker for automated trading & scalping IC Markets
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

1. Cross-Asset & Basis Lead-Lag Filter (Macro-Micro Synchronization)
Before evaluating any candlestick pattern on spot XAU/USD, the engine validates directional intent across three correlated feeds in real time:

COMEX GC Futures vs. Spot XAU/USD Basis Z-Score:

Centralized COMEX Gold futures (GC) maintain a transparent limit order book that routinely leads OTC broker spot feeds by 50–300 milliseconds during institutional sweeps. Compute the carry-adjusted basis spread every tick:

$$B_t = F_{\text{GC}, t} - S_{\text{XAU}, t} - C_{t,T}$$

where $F_{\text{GC}, t}$ is the front-month COMEX GC mid-price, $S_{\text{XAU}, t}$ is your ECN spot XAU/USD mid-price, and $C_{t,T}$ is the rolling intraday cost-of-carry offset. Calculate a 200-tick rolling Z-score ($Z_B$). Long scalps are permitted only when $Z_B$ is greater than $+1.75$ (futures leading spot upward); short scalps require $Z_B$ to be less than $-1.75$.

2. Triangular Synthetic Gold Parity (XAU/EUR × EUR/USD):

Monitor the triangular residual between direct XAU/USD and synthetic XAU/EUR × EUR/USD. If XAU/USD drops solely because EUR/USD is crashing on a Dollar Index (DXY) spike while XAU/EUR holds firm, suppress short breakout entries—genuine bullion liquidation requires weakness in both USD and EUR terms.

3. US 10-Year Real Yield Impulse Filter:

Track tick momentum on 10-year Treasury futures (ZN). Require inverse tick-correlation between ZN and GC over the trailing 15 minutes before authorizing momentum-continuation scalps.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

2. Regime Classification & Volatility-Gated Execution Windows:

Gold exhibits distinct statistical behavior depending on session depth and order-book density. Rather than running one static rule set all day, classify the market every 5 minutes using a rolling 100-bar Hurst exponent ($H$) paired with the ratio of live ECN spread to 1-minute Average True Range ($\text{ATR}_{14}$)

3. Multi-Timeframe Liquidity Sweep & Order-Flow Trigger

Entries require four sequential confirmations cascading from the M5 structural chart down to COMEX GC footprint delta and 15-second / M1 spot execution:

1.) Map Resting Liquidity Pools (M5):

Mark unmitigated M5 Fair Value Gaps (FVGs), Previous Session Highs/Lows (PDH/PDL), and equal highs/lows where retail stop-loss orders cluster.

2.) Confirm Stop-Sweep Piercing:

Wait for price to breach an M5 liquidity level by $1.50\text{ to }4.00\text{ USD/oz}$ ($15\text{ to }40\text{ ticks}$ on GC). Do not enter on the initial touch; allow resting stop orders to trigger and provide liquidity to institutional counterparties.

3.) Verify Footprint Absorption & CVD Divergence (GC):

4.) Inspect M1 volume footprint delta on COMEX GC: For Long Reversals: Spot XAU/USD prints a lower low beneath the swept level, while GC Cumulative Volume Delta (CVD) prints a higher low, accompanied by a $\ge 2.5\sigma$ passive bid absorption cluster at the wick extreme.For Short Reversals: Spot prints a higher high above resistance while GC CVD prints a lower high with aggressive ask absorption.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

4. Asymmetric Position Sizing & Anti-Martingale Pyramiding

High-frequency gold scalping fails when traders either use static lot sizes across shifting volatility or average down into adverse momentum.

Volatility-Normalized Base Unit ($R_0$):
Size Tranche 1 so that a stop-loss placed $0.5 \times \text{ATR}_{14}(\text{M1})$ beyond the swept liquidity wick equals exactly $1.0\%\text{ to }1.5\%$ of account equity:

Zero-Averaging-Down Rule:

Never add to a losing scalp. If price violates the swept wick, take the controlled $1R$ loss immediately.

Floating-Profit Anti-Martingale Add-On (Tranche 2):

Once Tranche 1 reaches $+1.2R$ in unrealized profit and GC CVD continues expanding in the trade's direction, advance Tranche 1's stop-loss to $+0.25R$ (guaranteeing a net-positive trade) and deploy Tranche 2 at $0.75 \times \text{Lots}_1$. Place Tranche 2's stop at break-even so combined portfolio risk remains strictly below zero while targeting the opposing $\pm 2.0\sigma$ Session VWAP band or the next unmitigated M5 liquidity pool.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

5. Execution Telemetry & Hard Circuit Breakers

To protect against broker execution degradation and regime shifts during live scalping, enforce three automated circuit breakers:

Slippage Drift Halt: Track rolling 5-trade execution slippage on entry and stop fills. If mean slippage exceeds $0.15\text{ USD/oz}$, pause trading for 30 minutes.

Intraday Drawdown Lockout: Terminate the trading session immediately if cumulative intraday loss hits $-3.0R$ or after 3 consecutive base-risk stop-outs.

Feed Latency Watchdog: Measure round-trip quote delta between the reference COMEX GC feed and your ECN spot feed. If feed lag exceeds $40\text{ ms}$, disable basis-dependent entries until synchronization normalizes.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

Decouple the CAM-VSA execution engine into four MQL5 header modules under MQL5/Include/CAM_VSA/ orchestrated by a thin event-driven Expert Advisor in MQL5/Experts/CAM_VSA_Scalper.mq5. Running separate stop-loss levels on Tranche 1 (+0.25R) and Tranche 2 (break-even) requires an ACCOUNT_MARGIN_MODE_RETAIL_HEDGING account so MetaTrader 5 maintains distinct position tickets rather than netting them into a blended average price.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

Module Topology

Types.mqh: Shared enumerations (ESessionRegime, ESignalDirection), configuration structs, and position telemetry DTOs.

CSpreadVolatilityGate.mqh: Owns the M1 $\text{ATR}_{14}$ indicator handle, session-dependent spread-to-ATR ratios, news blackout gates, and rolling slippage/drawdown circuit breakers.

CAtrPositionSizer.mqh: Computes volatility-normalized Tranche 1 volume ($R_0$) using OrderCalcProfit() rather than raw SYMBOL_TRADE_TICK_VALUE metadata, preventing broker misconfigurations on XAUUSD CFD leverage contracts.

CAntiMartingaleManager.mqh: Tracks Tranche 1 and Tranche 2 by individual ticket, enforces the zero-averaging-down rule, advances Tranche 1 stops at $+1.2R$, and triggers the $0.75 \times \text{Lots}_1$ pyramid add-on.

CAM_VSA_Scalper.mq5: Main EA entry point binding tick events, trade transactions, and module lifecycles.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

1. Shared Types & Configuration (Include/CAM_VSA/Types.mqh)

Code: Select all

//+------------------------------------------------------------------+
//|                                                        Types.mqh |
//|                        CAM-VSA XAU/USD Scalping Architecture     |
//+------------------------------------------------------------------+
#pragma once

enum ESessionRegime
  {
   REGIME_ASIAN_MEAN_REV = 0,
   REGIME_LONDON_SWEEP   = 1,
   REGIME_OVERLAP_TREND  = 2,
   REGIME_LOCKOUT        = 3
  };

enum ESignalDirection
  {
   SIGNAL_NONE  = 0,
   SIGNAL_LONG  = 1,
   SIGNAL_SHORT = -1
  };

struct SStrategyConfig
  {
   ulong  magicNumber;
   int    atrPeriod;
   double baseRiskPct;           // e.g., 1.25 (%)
   double slAtrMultiplier;       // 0.50 * ATR14(M1)
   double asianMaxSpreadRatio;   // 0.10 * ATR14
   double activeMaxSpreadRatio;  // 0.12 * ATR14
   double pyramidTriggerR;       // +1.20 R
   double tranche1LockR;         // +0.25 R
   double tranche2LotFactor;     // 0.75 * Lots_1
   double maxMeanSlippageUsd;    // 0.15 USD/oz
   double maxDailyLossR;         // 3.00 R
   int    maxConsecutiveLosses;  // 3
  };

struct STradePlan
  {
   ESignalDirection direction;
   double           entryPrice;
   double           stopLoss;
   double           takeProfit;
   double           oneRDistance;   // Price distance from entry to SL
   double           tranche1Lots;
   double           tranche2Lots;
  };
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

2. Spread, Session & Circuit Breaker Gate (Include/CAM_VSA/CSpreadVolatilityGate.mqh)

This module encapsulates iATR lifecycle management, compares live ECN spread in price terms against M1 $\text{ATR}_{14}$, and enforces intraday drawdown and slippage halts.

Code: Select all

//+------------------------------------------------------------------+
//|                                        CSpreadVolatilityGate.mqh |
//+------------------------------------------------------------------+
#pragma once
#include <Trade\SymbolInfo.mqh>
#include "Types.mqh"

class CSpreadVolatilityGate
  {
private:
   string          m_symbolName;
   CSymbolInfo     m_symbol;
   SStrategyConfig m_cfg;
   int             m_atrHandle;

   double          m_slippageRing[5];
   int             m_slippageCount;
   int             m_slippageIdx;
   datetime        m_slippagePauseUntil;

   double          m_dailyLossR;
   int             m_consecutiveLosses;
   int             m_lastResetDay;
   bool            m_isNewsBlackout;

public:
                     CSpreadVolatilityGate(void) : m_atrHandle(INVALID_HANDLE),
                                                   m_slippageCount(0),
                                                   m_slippageIdx(0),
                                                   m_slippagePauseUntil(0),
                                                   m_dailyLossR(0.0),
                                                   m_consecutiveLosses(0),
                                                   m_lastResetDay(-1),
                                                   m_isNewsBlackout(false) {}

   bool              Init(const string symbol, const SStrategyConfig &cfg)
     {
      m_symbolName = symbol;
      m_cfg        = cfg;
      if(!m_symbol.Name(m_symbolName))
         return(false);

      m_atrHandle = iATR(m_symbolName, PERIOD_M1, m_cfg.atrPeriod);
      return(m_atrHandle != INVALID_HANDLE);
     }

   void              Deinit(void)
     {
      if(m_atrHandle != INVALID_HANDLE)
        {
         IndicatorRelease(m_atrHandle);
         m_atrHandle = INVALID_HANDLE;
        }
     }

   void              SetNewsBlackout(const bool active) { m_isNewsBlackout = active; }

   double            GetM1Atr(void) const
     {
      double buf[1];
      // Use closed bar [1] to prevent intrabar tick jitter in sizing
      if(CopyBuffer(m_atrHandle, 0, 1, 1, buf) != 1)
         return(0.0);
      return(buf[0]);
     }

   double            GetLiveSpreadPrice(void)
     {
      m_symbol.RefreshRates();
      return(m_symbol.Ask() - m_symbol.Bid());
     }

   ESessionRegime    ResolveSessionRegime(void) const
     {
      MqlDateTime dt;
      TimeToStruct(TimeTradeServer(), dt); // Align broker server offset to CET

      if(dt.day_of_year != m_lastResetDay)
         const_cast<CSpreadVolatilityGate*>(this).ResetDailyStats(dt.day_of_year);

      if(m_isNewsBlackout)
         return(REGIME_LOCKOUT);

      int mins = dt.hour * 60 + dt.min;
      if(mins >= 60 && mins < 420)        // 01:00 - 07:00
         return(REGIME_ASIAN_MEAN_REV);
      if(mins >= 480 && mins < 630)       // 08:00 - 10:30
         return(REGIME_LONDON_SWEEP);
      if(mins >= 840 && mins < 1050)      // 14:00 - 17:30
         return(REGIME_OVERLAP_TREND);

      return(REGIME_LOCKOUT);
     }

   void              RecordExecutionSlippage(const double slippageUsd)
     {
      m_slippageRing[m_slippageIdx] = MathAbs(slippageUsd);
      m_slippageIdx   = (m_slippageIdx + 1) % 5;
      m_slippageCount = MathMin(5, m_slippageCount + 1);

      if(m_slippageCount == 5)
        {
         double sum = 0.0;
         for(int i = 0; i < 5; i++)
            sum += m_slippageRing[i];

         if((sum / 5.0) > m_cfg.maxMeanSlippageUsd)
            m_slippagePauseUntil = TimeCurrent() + 1800; // 30-min halt
        }
     }

   void              RecordClosedTradeR(const double realizedR)
     {
      if(realizedR < 0.0)
        {
         m_dailyLossR += MathAbs(realizedR);
         m_consecutiveLosses++;
        }
      else if(realizedR > 0.0)
        {
         m_consecutiveLosses = 0;
        }
     }

   bool              CanOpenNewTrade(string &rejectReason)
     {
      ESessionRegime regime = ResolveSessionRegime();
      if(regime == REGIME_LOCKOUT)
        {
         rejectReason = "Session/News lockout active";
         return(false);
        }

      if(TimeCurrent() < m_slippagePauseUntil)
        {
         rejectReason = "Slippage drift circuit breaker active";
         return(false);
        }

      if(m_dailyLossR >= m_cfg.maxDailyLossR || m_consecutiveLosses >= m_cfg.maxConsecutiveLosses)
        {
         rejectReason = "Intraday drawdown/loss-streak lockout";
         return(false);
        }

      double atr = GetM1Atr();
      if(atr <= 0.0)
        {
         rejectReason = "Invalid M1 ATR reading";
         return(false);
        }

      double spread    = GetLiveSpreadPrice();
      double maxRatio  = (regime == REGIME_ASIAN_MEAN_REV) ? m_cfg.asianMaxSpreadRatio
                                                           : m_cfg.activeMaxSpreadRatio;
      if(spread > (maxRatio * atr))
        {
         rejectReason = StringFormat("Spread/ATR gate exceeded (%.3f > %.3f)", spread, maxRatio * atr);
         return(false);
        }

      return(true);
     }

private:
   void              ResetDailyStats(const int dayOfYear)
     {
      m_lastResetDay      = dayOfYear;
      m_dailyLossR        = 0.0;
      m_consecutiveLosses = 0;
     }
  };
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 7940
Joined: Mon Jul 20, 2026 1:28 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

3. Volatility-Normalized Position Sizer (Include/CAM_VSA/CAtrPositionSizer.mqh)

Uses OrderCalcProfit() to resolve exact account-currency risk per 1.0 lot across the combined stop distance ($\text{Dist}_{\text{SL}} + \text{Spread}_{\text{live}}$), rounding down (MathFloor) to the broker's lot step so risk never exceeds $r_{\text{base}}$.

Code: Select all

//+------------------------------------------------------------------+
//|                                            CAtrPositionSizer.mqh |
//+------------------------------------------------------------------+
#pragma once
#include <Trade\SymbolInfo.mqh>
#include "Types.mqh"

class CAtrPositionSizer
  {
private:
   string          m_symbolName;
   CSymbolInfo     m_symbol;
   SStrategyConfig m_cfg;

public:
   bool              Init(const string symbol, const SStrategyConfig &cfg)
     {
      m_symbolName = symbol;
      m_cfg        = cfg;
      return(m_symbol.Name(m_symbolName));
     }

   bool              BuildTradePlan(const ESignalDirection dir,
                                    const double sweptWickExtreme,
                                    const double m1Atr,
                                    const double targetPrice,
                                    STradePlan &outPlan)
     {
      if(dir == SIGNAL_NONE || m1Atr <= 0.0)
         return(false);

      m_symbol.RefreshRates();
      double ask    = m_symbol.Ask();
      double bid    = m_symbol.Bid();
      double spread = ask - bid;
      double buffer = m_cfg.slAtrMultiplier * m1Atr;

      outPlan.direction = dir;
      if(dir == SIGNAL_LONG)
        {
         outPlan.entryPrice = ask;
         outPlan.stopLoss   = m_symbol.NormalizePrice(sweptWickExtreme - buffer);
         outPlan.takeProfit = m_symbol.NormalizePrice(targetPrice);
        }
      else
        {
         outPlan.entryPrice = bid;
         outPlan.stopLoss   = m_symbol.NormalizePrice(sweptWickExtreme + buffer);
         outPlan.takeProfit = m_symbol.NormalizePrice(targetPrice);
        }

      outPlan.oneRDistance = MathAbs(outPlan.entryPrice - outPlan.stopLoss);
      if(outPlan.oneRDistance <= m_symbol.StopsLevel() * m_symbol.Point())
         return(false);

      // Include live spread in effective risk distance
      double effectiveRiskDist = outPlan.oneRDistance + spread;
      double riskMoney         = AccountInfoDouble(ACCOUNT_EQUITY) * (m_cfg.baseRiskPct / 100.0);

      double lossPerOneLot = 0.0;
      ENUM_ORDER_TYPE calcType = (dir == SIGNAL_LONG) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
      double simulatedSlPrice  = (dir == SIGNAL_LONG) ? (outPlan.entryPrice - effectiveRiskDist)
                                                      : (outPlan.entryPrice + effectiveRiskDist);

      if(!OrderCalcProfit(calcType, m_symbolName, 1.0, outPlan.entryPrice, simulatedSlPrice, lossPerOneLot))
         return(false);

      double absLossPerLot = MathAbs(lossPerOneLot);
      if(absLossPerLot <= 0.0)
         return(false);

      double rawLots1 = riskMoney / absLossPerLot;
      outPlan.tranche1Lots = NormalizeVolume(rawLots1);
      outPlan.tranche2Lots = NormalizeVolume(outPlan.tranche1Lots * m_cfg.tranche2LotFactor);

      return(outPlan.tranche1Lots >= m_symbol.LotsMin());
     }

   double            NormalizeVolume(const double rawLots) const
     {
      double step   = m_symbol.LotsStep();
      double minLot = m_symbol.LotsMin();
      double maxLot = m_symbol.LotsMax();

      if(rawLots < minLot)
         return(0.0);

      double floored = MathFloor(rawLots / step) * step;
      floored = MathMin(maxLot, MathMax(minLot, floored));

      int digits = (int)MathRound(-MathLog10(step));
      return(NormalizeDouble(floored, MathMax(0, digits)));
     }
  };
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply