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

Re: Scalping XAU/USD (gold) trading strategy

Post by PTScalper »

4. Anti-Martingale Pyramiding Manager (Include/CAM_VSA/CAntiMartingaleManager.mqh)

Tracks active tickets, rejects any signal when a campaign is already open (enforcing zero averaging down), and invokes CTrade::PositionModify(ticket, sl, tp) by explicit ticket ID so Tranche 1 and Tranche 2 retain independent stop levels.

Code: Select all

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

class CAntiMartingaleManager
  {
private:
   string          m_symbolName;
   SStrategyConfig m_cfg;
   CTrade          m_trade;
   CPositionInfo   m_posInfo;
   CSymbolInfo     m_symbol;

   ulong           m_tranche1Ticket;
   ulong           m_tranche2Ticket;
   bool            m_pyramidDeployed;
   STradePlan      m_activePlan;

public:
                     CAntiMartingaleManager(void) : m_tranche1Ticket(0),
                                                    m_tranche2Ticket(0),
                                                    m_pyramidDeployed(false) {}

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

      m_trade.SetExpertMagicNumber(m_cfg.magicNumber);
      m_trade.SetDeviationInPoints(15);
      m_trade.SetTypeFillingBySymbol(m_symbolName);

      RecoverOpenCampaign();
      return(true);
     }

   bool              HasActiveCampaign(void)
     {
      SyncTicketLifecycle();
      return(m_tranche1Ticket != 0 || m_tranche2Ticket != 0);
     }

   bool              ExecuteTranche1(const STradePlan &plan, double &outSlippageUsd)
     {
      // Hard rule: never average down or stack while a campaign is live
      if(HasActiveCampaign())
         return(false);

      bool sent = (plan.direction == SIGNAL_LONG)
                  ? m_trade.Buy(plan.tranche1Lots, m_symbolName, 0.0, plan.stopLoss, plan.takeProfit, "CAM_T1")
                  : m_trade.Sell(plan.tranche1Lots, m_symbolName, 0.0, plan.stopLoss, plan.takeProfit, "CAM_T1");

      if(!sent || m_trade.ResultRetcode() != TRADE_RETCODE_DONE)
         return(false);

      double fillPrice   = m_trade.ResultPrice();
      outSlippageUsd     = MathAbs(fillPrice - plan.entryPrice);
      m_activePlan       = plan;
      m_activePlan.entryPrice = fillPrice;
      m_pyramidDeployed  = false;

      // Resolve position ticket by order/deal
      RecoverOpenCampaign();
      return(m_tranche1Ticket != 0);
     }

   void              ManageActiveCampaign(const bool cvdStillConfirming)
     {
      SyncTicketLifecycle();
      if(m_tranche1Ticket == 0 || m_pyramidDeployed)
         return;

      if(!m_posInfo.SelectByTicket(m_tranche1Ticket))
         return;

      double openPrice    = m_posInfo.PriceOpen();
      double currentPrice = m_posInfo.PriceCurrent();
      double oneR         = m_activePlan.oneRDistance;
      if(oneR <= 0.0)
         return;

      double unrealizedR = (m_activePlan.direction == SIGNAL_LONG)
                           ? (currentPrice - openPrice) / oneR
                           : (openPrice - currentPrice) / oneR;

      // Trigger pyramid at +1.2R when order flow remains aligned
      if(unrealizedR >= m_cfg.pyramidTriggerR && cvdStillConfirming)
        {
         double lockedSl = (m_activePlan.direction == SIGNAL_LONG)
                           ? m_symbol.NormalizePrice(openPrice + m_cfg.tranche1LockR * oneR)
                           : m_symbol.NormalizePrice(openPrice - m_cfg.tranche1LockR * oneR);

         // 1. Lock +0.25R on Tranche 1 BEFORE adding Tranche 2
         if(!m_trade.PositionModify(m_tranche1Ticket, lockedSl, m_posInfo.TakeProfit()))
            return;

         // 2. Deploy Tranche 2 (0.75 * Lots_1) with immediate Break-Even SL
         if(m_activePlan.tranche2Lots >= m_symbol.LotsMin())
           {
            m_symbol.RefreshRates();
            double t2Entry = (m_activePlan.direction == SIGNAL_LONG) ? m_symbol.Ask() : m_symbol.Bid();
            double t2Sl    = m_symbol.NormalizePrice(t2Entry);

            bool sent2 = (m_activePlan.direction == SIGNAL_LONG)
                         ? m_trade.Buy(m_activePlan.tranche2Lots, m_symbolName, 0.0, t2Sl, m_posInfo.TakeProfit(), "CAM_T2")
                         : m_trade.Sell(m_activePlan.tranche2Lots, m_symbolName, 0.0, t2Sl, m_posInfo.TakeProfit(), "CAM_T2");

            if(sent2 && m_trade.ResultRetcode() == TRADE_RETCODE_DONE)
              {
               m_pyramidDeployed = true;
               RecoverOpenCampaign();
              }
           }
        }
     }

private:
   void              SyncTicketLifecycle(void)
     {
      if(m_tranche1Ticket != 0 && !m_posInfo.SelectByTicket(m_tranche1Ticket))
         m_tranche1Ticket = 0;
      if(m_tranche2Ticket != 0 && !m_posInfo.SelectByTicket(m_tranche2Ticket))
         m_tranche2Ticket = 0;

      if(m_tranche1Ticket == 0 && m_tranche2Ticket == 0)
         m_pyramidDeployed = false;
     }

   void              RecoverOpenCampaign(void)
     {
      m_tranche1Ticket = 0;
      m_tranche2Ticket = 0;

      for(int i = PositionsTotal() - 1; i >= 0; i--)
        {
         if(!m_posInfo.SelectByIndex(i))
            continue;
         if(m_posInfo.Symbol() != m_symbolName || m_posInfo.Magic() != m_cfg.magicNumber)
            continue;

         string cmt = m_posInfo.Comment();
         if(StringFind(cmt, "CAM_T1") == 0)
            m_tranche1Ticket = m_posInfo.Ticket();
         else if(StringFind(cmt, "CAM_T2") == 0)
           {
            m_tranche2Ticket  = m_posInfo.Ticket();
            m_pyramidDeployed = true;
           }
        }
     }
  };
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 »

5. Expert Advisor Orchestrator (Experts/CAM_VSA_Scalper.mq5)

Code: Select all

//+------------------------------------------------------------------+
//|                                              CAM_VSA_Scalper.mq5 |
//+------------------------------------------------------------------+
#include <CAM_VSA\Types.mqh>
#include <CAM_VSA\CSpreadVolatilityGate.mqh>
#include <CAM_VSA\CAtrPositionSizer.mqh>
#include <CAM_VSA\CAntiMartingaleManager.mqh>

input ulong  InpMagicNumber        = 20261129; // Magic Number
input int    InpAtrPeriod          = 14;       // M1 ATR Period
input double InpBaseRiskPct        = 1.25;     // Tranche 1 Equity Risk (%)
input double InpSlAtrMult          = 0.50;     // SL Buffer (x M1 ATR)
input double InpAsianSpreadRatio   = 0.10;     // Max Asian Spread / ATR
input double InpActiveSpreadRatio  = 0.12;     // Max London-NY Spread / ATR
input double InpPyramidTriggerR    = 1.20;     // Pyramid Trigger (+R)
input double InpTranche1LockR      = 0.25;     // Tranche 1 SL Lock (+R)
input double InpTranche2LotFactor  = 0.75;     // Tranche 2 Size Multiplier
input double InpMaxMeanSlippageUsd = 0.15;     // 5-Trade Slippage Halt ($)
input double InpMaxDailyLossR      = 3.00;     // Daily Max Loss (R)
input int    InpMaxConsecLosses    = 3;        // Max Consecutive Losses

CSpreadVolatilityGate  g_gate;
CAtrPositionSizer      g_sizer;
CAntiMartingaleManager g_manager;
SStrategyConfig        g_cfg;

int OnInit(void)
  {
   if(AccountInfoInteger(ACCOUNT_MARGIN_MODE) != ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
     {
      Print("CAM-VSA requires a Hedging account to isolate Tranche 1 and Tranche 2 stops.");
      return(INIT_FAILED);
     }

   g_cfg.magicNumber          = InpMagicNumber;
   g_cfg.atrPeriod            = InpAtrPeriod;
   g_cfg.baseRiskPct          = InpBaseRiskPct;
   g_cfg.slAtrMultiplier      = InpSlAtrMult;
   g_cfg.asianMaxSpreadRatio  = InpAsianSpreadRatio;
   g_cfg.activeMaxSpreadRatio = InpActiveSpreadRatio;
   g_cfg.pyramidTriggerR      = InpPyramidTriggerR;
   g_cfg.tranche1LockR        = InpTranche1LockR;
   g_cfg.tranche2LotFactor    = InpTranche2LotFactor;
   g_cfg.maxMeanSlippageUsd   = InpMaxMeanSlippageUsd;
   g_cfg.maxDailyLossR        = InpMaxDailyLossR;
   g_cfg.maxConsecLosses      = InpMaxConsecLosses;

   if(!g_gate.Init(_Symbol, g_cfg) ||
      !g_sizer.Init(_Symbol, g_cfg) ||
      !g_manager.Init(_Symbol, g_cfg))
      return(INIT_FAILED);

   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   g_gate.Deinit();
  }

void OnTick(void)
  {
   // 1. Manage open Anti-Martingale campaign first
   if(g_manager.HasActiveCampaign())
     {
      bool cvdAligned = EvaluateOrderFlowAlignment();
      g_manager.ManageActiveCampaign(cvdAligned);
      return;
     }

   // 2. Enforce session, spread-to-ATR, and circuit-breaker gates
   string rejectReason;
   if(!g_gate.CanOpenNewTrade(rejectReason))
      return;

   // 3. Evaluate liquidity sweep + mMSS trigger
   double sweptWick = 0.0, targetVwap = 0.0;
   ESignalDirection sig = EvaluateLiquiditySweepSignal(sweptWick, targetVwap);
   if(sig == SIGNAL_NONE)
      return;

   // 4. Size Tranche 1 and execute
   STradePlan plan;
   if(!g_sizer.BuildTradePlan(sig, sweptWick, g_gate.GetM1Atr(), targetVwap, plan))
      return;

   double fillSlippage = 0.0;
   if(g_manager.ExecuteTranche1(plan, fillSlippage))
      g_gate.RecordExecutionSlippage(fillSlippage);
  }

void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
   if(trans.type != TRADE_TRANSACTION_DEAL_ADD || trans.symbol != _Symbol)
      return;

   if(!HistoryDealSelect(trans.deal))
      return;

   if(HistoryDealGetInteger(trans.deal, DEAL_MAGIC) != (long)g_cfg.magicNumber)
      return;

   if(HistoryDealGetInteger(trans.deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
     {
      double profit   = HistoryDealGetDouble(trans.deal, DEAL_PROFIT);
      double swap     = HistoryDealGetDouble(trans.deal, DEAL_SWAP);
      double comm     = HistoryDealGetDouble(trans.deal, DEAL_COMMISSION);
      double netUsd   = profit + swap + comm;
      double oneRUsd  = AccountInfoDouble(ACCOUNT_EQUITY) * (g_cfg.baseRiskPct / 100.0);

      if(oneRUsd > 0.0)
         g_gate.RecordClosedTradeR(netUsd / oneRUsd);
     }
  }

//--- Signal stubs to wire to your COMEX GC / FVG / mMSS feed adapter
bool EvaluateOrderFlowAlignment(void) { return(true); }

ESignalDirection EvaluateLiquiditySweepSignal(double &sweptWick, double &targetPrice)
  {
   return(SIGNAL_NONE);
  }
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 »

Key Implementation Safeguards

Zero-Slippage Break-Even Floor on Tranche 2: Because raw ECN execution incurs round-turn commission and spread, add m_symbol.Ask() - m_symbol.Bid() plus commission-equivalent points to t2Sl if your broker rejects zero-distance PositionModify calls within SYMBOL_TRADE_STOPS_LEVEL.

Session Clock Offset: ResolveSessionRegime() reads TimeTradeServer(). If your broker runs on UTC+2/+3 (EET/EEST, standard for Raw ECN gold feeds) rather than CET, shift the minute thresholds by +60 minutes.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Shadow Trader
Posts: 6294
Joined: Wed Sep 09, 2026 5:19 pm

Re: Scalping XAU/USD (gold) trading strategy

Post by Shadow Trader »

There's a lot packed into this, and the parts that stand out as most practical to me are the circuit breakers at the end. A slippage halt, a daily loss lockout in R and a check on feed lag are the kind of rules that protect an account regardless of whether the entry logic has an edge, and plenty of systems skip them entirely.

A few questions about the earlier layers, because they're where I'd want to see some testing before trusting the whole stack.

On the COMEX basis filter: the GC front month trades above spot by the cost of carry, and that carry term changes as expiry approaches and jumps when the active contract rolls. How is the roll handled in the z-score, so a contract switch doesn't read as a sudden basis dislocation? And is the 50 to 300 millisecond lead something that shows up in data from a retail ECN feed, or is it closer to what you'd see with co-located exchange access? From a retail terminal, the round trip to the broker alone can eat most of that window.

On the Hurst regime filter: a 100-bar Hurst estimate on M1 or M5 data is quite noisy, and the value can swing around 0.5 without the market actually changing character. Did you look at how often the regime label flips from one 5-minute check to the next? If it flips a lot, the filter might be adding randomness rather than removing it.

On the anti-martingale add-on: adding Tranche 2 at +1.2R makes sense in that you never add to a loser, but it does mean the largest exposure sits at the point where a reversal costs the most. It would be interesting to see the same trades run with and without Tranche 2 to see whether the add-on improves expectancy or mainly makes the equity curve swing wider.

Lastly, with five layers and four sequential confirmations, how many trades does the full filter actually let through per week? With that many conditions, the sample can get small quickly, and it becomes hard to tell whether the results reflect the logic or a handful of lucky sessions. Would be good to hear how you tested it.
Post Reply