Summary: Gold Glacier EA is an MQL4 expert advisor for XAUUSD that combines multi-timeframe structural bias confirmation, ATR dynamic stops, and adaptive risk management. Designed for H1 stable operation.




Gold Glacier EA is engineered for stable gold trading using a structural analysis approach that mimics institutional order flow detection. The EA identifies key structural breaks on higher timeframes (H4 and H1 alignment) before considering entry, ensuring trades follow the macro direction. A unique "market memory" module tracks consecutive losses and adjusts pause timers accordingly. The EA uses ATR-based dynamic stops that widen during high volatility and tighten when volatility subsides. All trades include fixed profit targets with a trailing stop that activates after minimum profit is achieved.

Recommended Timeframe: H1
Trading Logic:
  • Structural Bias: H4 EMA(200) provides macro directional bias. H1 EMA(50) must align for entry consideration.

  • Breakout Detection: Identify recent swing high/low over the last 20 candles. Price must close beyond these levels.

  • Trend Strength Filter: ADX(14) must exceed 23 to ensure the market is trending.

  • Volatility Guard: Current ATR(14) must not exceed 2.0x the 50-period average ATR.

  • Risk Management: Fixed stop loss at 1.6x ATR(14), take profit at 2.8x ATR. Trailing stop after 1.2x ATR profit.


  • ``mql4
    //+------------------------------------------------------------------+
    //| GoldGlacierEA.mq4 |
    //+------------------------------------------------------------------+
    #property copyright ""
    #property link ""
    #property version "1.00"
    #property strict

    //--- input parameters with comments
    input double LotSize = 0.01; // Fixed lot size (0.01 for XAUUSD)
    input int H4BiasPeriod = 200; // H4 EMA period for macro bias
    input int H1TrendPeriod = 50; // H1 EMA period for trend alignment
    input int StructureLookback = 20; // Bars for swing high/low detection
    input int ADXPeriod = 14; // ADX period for trend strength
    input int ADXThreshold = 23; // Minimum ADX for trending market
    input int ATRPeriod = 14; // ATR period for volatility
    input double ATRMaxMultiplier = 2.0; // Max ATR vs average ATR
    input double ATRStopMultiplier = 1.6; // Stop loss as multiple of ATR
    input double ATRTakeMultiplier = 2.8; // Take profit as multiple of ATR
    input double TrailingStartATR = 1.2; // Trailing activates at profit (x ATR)
    input double TrailingStepATR = 0.5; // Trailing step (x ATR)
    input int MaxConsecutiveLosses = 3; // Max losses before pause
    input int PauseMinutes = 60; // Pause duration after losses
    input int MagicNumber = 202512; // Unique EA identifier
    input int MaxSpread = 35; // Maximum allowed spread in points
    input double DailyLossLimit = 5.0; // Daily loss limit as percentage
    input bool UseFridayClose = true; // Close trades before Friday 21:00 GMT

    //--- global variables
    double dailyStartBalance = 0;
    datetime lastBarTime = 0;
    bool fridayCloseExecuted = false;
    double avgATR = 0;
    double structureHigh = 0;
    double structureLow = 0;
    int consecutiveLosses = 0;
    datetime lastLossTime = 0;

    //+------------------------------------------------------------------+
    //| Expert initialization function |
    //+------------------------------------------------------------------+
    int OnInit()
    {
    dailyStartBalance = AccountBalance();
    lastBarTime = 0;
    fridayCloseExecuted = false;
    avgATR = iATR(Symbol(), PERIOD_H1, ATRPeriod, 1);
    if(avgATR <= 0) avgATR = 250 Point;
    consecutiveLosses = 0;
    return(INIT_SUCCEEDED);
    }

    //+------------------------------------------------------------------+
    //| Expert deinitialization function |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
    Comment("");
    }

    //+------------------------------------------------------------------+
    //| Get structural bias from H4 timeframe |
    //+------------------------------------------------------------------+
    int GetMacroBias()
    {
    double closeH4 = iClose(Symbol(), PERIOD_H4, 1);
    double emaH4 = iMA(Symbol(), PERIOD_H4, H4BiasPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
    if(closeH4 > emaH4) return 1;
    if(closeH4 < emaH4) return -1;
    return 0;
    }

    //+------------------------------------------------------------------+
    //| Check H1 trend alignment |
    //+------------------------------------------------------------------+
    bool IsH1Aligned(int macroBias)
    {
    if(macroBias == 0) return false;
    double closeH1 = iClose(Symbol(), PERIOD_H1, 1);
    double emaH1 = iMA(Symbol(), PERIOD_H1, H1TrendPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);

    if(macroBias == 1) return (closeH1 > emaH1);
    if(macroBias == -1) return (closeH1 < emaH1);
    return false;
    }

    //+------------------------------------------------------------------+
    //| Detect structural break levels (swing high/low) |
    //+------------------------------------------------------------------+
    void DetectStructureLevels()
    {
    int highestIdx = iHighest(Symbol(), PERIOD_H1, MODE_HIGH, StructureLookback, 1);
    int lowestIdx = iLowest(Symbol(), PERIOD_H1, MODE_LOW, StructureLookback, 1);

    if(highestIdx > 0)
    structureHigh = iHigh(Symbol(), PERIOD_H1, highestIdx);
    if(lowestIdx > 0)
    structureLow = iLow(Symbol(), PERIOD_H1, lowestIdx);
    }

    //+------------------------------------------------------------------+
    //| Check ADX trend strength |
    //+------------------------------------------------------------------+
    bool IsTrendStrong()
    {
    double adx = iADX(Symbol(), PERIOD_H1, ADXPeriod, PRICE_CLOSE, MODE_MAIN, 1);
    return (adx >= ADXThreshold);
    }

    //+------------------------------------------------------------------+
    //| Check structural breakout entry |
    //+------------------------------------------------------------------+
    bool CheckStructuralBreakout(int direction, double &entryPrice, double &sl, double &tp, double atr)
    {
    if(direction == 0) return false;

    double close1 = iClose(Symbol(), PERIOD_H1, 1);

    // Bullish breakout: close above structure high with bullish momentum
    if(direction == 1 && structureHigh > 0)
    {
    if(close1 > structureHigh)
    {
    entryPrice = Ask;
    sl = entryPrice - (atr
    ATRStopMultiplier);
    tp = entryPrice + (atr ATRTakeMultiplier);
    return true;
    }
    }
    // Bearish breakout: close below structure low with bearish momentum
    else if(direction == -1 && structureLow > 0)
    {
    if(close1 < structureLow)
    {
    entryPrice = Bid;
    sl = entryPrice + (atr
    ATRStopMultiplier);
    tp = entryPrice - (atr ATRTakeMultiplier);
    return true;
    }
    }
    return false;
    }

    //+------------------------------------------------------------------+
    //| Track consecutive losses for market memory |
    //+------------------------------------------------------------------+
    void TrackTradeResult()
    {
    static int prevTotalOrders = 0;
    static double prevEquity = 0;

    int currentOrders = CountPositions();
    double currentEquity = AccountEquity();

    // Check if a trade just closed
    if(prevTotalOrders > 0 && currentOrders == 0)
    {
    double equityChange = currentEquity - prevEquity;
    if(equityChange < -0.01) // loss occurred (negative change)
    {
    consecutiveLosses++;
    lastLossTime = TimeCurrent();
    }
    else if(equityChange > 0.01) // profit occurred
    {
    consecutiveLosses = 0;
    }
    }

    if(currentOrders > 0)
    prevEquity = currentEquity;

    prevTotalOrders = currentOrders;
    }

    //+------------------------------------------------------------------+
    //| Manage trailing stop for open position |
    //+------------------------------------------------------------------+
    void ManageTrailingStop(double atr)
    {
    for(int i = OrdersTotal()-1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
    {
    double activate = atr
    TrailingStartATR;
    double step = atr TrailingStepATR;
    double newSL = 0;

    if(OrderType() == OP_BUY)
    {
    double profit = Bid - OrderOpenPrice();
    if(profit >= activate)
    {
    newSL = Bid - step;
    if(newSL > OrderStopLoss())
    OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE);
    }
    }
    else if(OrderType() == OP_SELL)
    {
    double profit = OrderOpenPrice() - Ask;
    if(profit >= activate)
    {
    newSL = Ask + step;
    if(newSL < OrderStopLoss() || OrderStopLoss() == 0)
    OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE);
    }
    }
    break;
    }
    }
    }
    }

    //+------------------------------------------------------------------+
    //| Expert tick function |
    //+------------------------------------------------------------------+
    void OnTick()
    {
    // Track trade results for market memory
    TrackTradeResult();

    // Market memory: pause after consecutive losses
    if(consecutiveLosses >= MaxConsecutiveLosses)
    {
    if(TimeCurrent() - lastLossTime < PauseMinutes
    60)
    {
    Comment("Market memory active: ", consecutiveLosses, " consecutive losses. Paused for ",
    (PauseMinutes 60 - (TimeCurrent() - lastLossTime)) / 60, " minutes.");
    return;
    }
    else
    {
    consecutiveLosses = 0;
    }
    }

    // Daily equity protection
    double currentEquity = AccountEquity();
    double lossPercent = (dailyStartBalance - currentEquity) / dailyStartBalance
    100;
    if(lossPercent >= DailyLossLimit)
    {
    Comment("Daily loss limit reached. No new trades.");
    return;
    }

    // Friday close before weekend
    if(UseFridayClose && !fridayCloseExecuted)
    {
    datetime currentTime = TimeCurrent();
    if(TimeDayOfWeek(currentTime) == 5 && TimeHour(currentTime) >= 21)
    {
    CloseAllOrders();
    fridayCloseExecuted = true;
    return;
    }
    if(TimeDayOfWeek(currentTime) != 5)
    fridayCloseExecuted = false;
    }

    // Spread filter
    if(MarketInfo(Symbol(), MODE_SPREAD) > MaxSpread)
    {
    Comment("Spread too high: ", MarketInfo(Symbol(), MODE_SPREAD));
    return;
    }

    // New bar logic (H1)
    if(Time[0] == lastBarTime)
    return;
    lastBarTime = Time[0];

    // Update structure levels on each new bar
    DetectStructureLevels();

    // Manage existing position
    int posCount = CountPositions();
    if(posCount > 0)
    {
    double atr = iATR(Symbol(), PERIOD_H1, ATRPeriod, 1);
    if(atr > 0) ManageTrailingStop(atr);
    return;
    }

    // Get ATR for volatility filtering
    double atr = iATR(Symbol(), PERIOD_H1, ATRPeriod, 1);
    if(atr > 0) avgATR = (avgATR 0.95) + (atr 0.05);

    // Volatility guard: skip if ATR too high
    if(atr > avgATR * ATRMaxMultiplier && avgATR > 0)
    {
    Comment("Volatility too high. ATR: ", atr);
    return;
    }

    // Check ADX trend strength
    if(!IsTrendStrong())
    {
    Comment("ADX below threshold. No strong trend.");
    return;
    }

    // Get macro bias from H4
    int macroBias = GetMacroBias();
    if(macroBias == 0)
    {
    Comment("No clear macro bias on H4.");
    return;
    }

    // Check H1 alignment
    if(!IsH1Aligned(macroBias))
    {
    Comment("H1 not aligned with H4 bias.");
    return;
    }

    // Check structural breakout
    double entryPrice = 0, sl = 0, tp = 0;
    if(CheckStructuralBreakout(macroBias, entryPrice, sl, tp, atr))
    {
    int cmd = (macroBias == 1) ? OP_BUY : OP_SELL;
    int ticket = OrderSend(Symbol(), cmd, LotSize, entryPrice, 5, sl, tp, "Gold Glacier", MagicNumber, 0, clrNONE);
    if(ticket < 0)
    Print("OrderSend failed: ", GetLastError());
    else
    Print("Structural breakout entry opened. Direction: ", cmd==OP_BUY?"BUY":"SELL");
    }
    }

    //+------------------------------------------------------------------+
    //| Count open positions with this MagicNumber |
    //+------------------------------------------------------------------+
    int CountPositions()
    {
    int count = 0;
    for(int i = OrdersTotal()-1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
    count++;
    }
    }
    return count;
    }

    //+------------------------------------------------------------------+
    //| Close all orders for this symbol and magic |
    //+------------------------------------------------------------------+
    void CloseAllOrders()
    {
    for(int i = OrdersTotal()-1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
    {
    if(OrderType() == OP_BUY)
    OrderClose(OrderTicket(), OrderLots(), Bid, 5, clrNONE);
    else if(OrderType() == OP_SELL)
    OrderClose(OrderTicket(), OrderLots(), Ask, 5, clrNONE);
    }
    }
    }
    }
    //+------------------------------------------------------------------+
    ``
    Reference: Original MQL4 code inspired by structural analysis principles from 2025-2026 gold EAs including Gold EA Macro Trend v1 and TRetBO Pro .
    Disclaimer: Gold trading involves significant risk due to high volatility and leverage. This EA is provided as-is without any guarantee of profit. Test thoroughly on a demo account for at least 3 months before live deployment. Past performance does not guarantee future results.