Summary: Gold Momentum Flow EA is an MQL4 expert advisor for XAUUSD. It uses dual EMA crossover with RSI momentum confirmation and ATR-based stop loss. Suitable for H1 timeframe.




Gold Momentum Flow EA is designed specifically for gold (XAUUSD) to capture medium-term trend movements while managing gold's characteristic volatility spikes. The EA combines dual EMA crossover (fast EMA 12, slow EMA 26) for trend direction, RSI(14) momentum filter to avoid low-momentum fakeouts, and ATR-based dynamic stop loss that widens during high volatility. Each trade includes a trailing stop to lock in profits as the trend develops.

Recommended Timeframe: H1
Trading Logic:
  • Trend Detection: Fast EMA12 crosses above Slow EMA26 for uptrend; opposite for downtrend.

  • Momentum Filter: RSI(14) must be above 50 for long entries or below 50 for short entries.

  • Entry Confirmation: Wait for bar close after crossover with momentum confirmation.

  • Risk Management: Dynamic stop loss at 1.5x ATR, take profit at 3x ATR with trailing stop activation after 1x ATR profit.


  • ``mql4
    //+------------------------------------------------------------------+
    //| GoldMomentumFlowEA.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 per trade)
    input int FastEMAPeriod = 12; // Fast EMA period for trend detection
    input int SlowEMAPeriod = 26; // Slow EMA period for trend detection
    input int RSIPeriod = 14; // RSI period for momentum filter
    input int ATRPeriod = 14; // ATR period for dynamic stop loss
    input double ATRStopMultiplier = 1.5; // Stop loss as multiple of ATR
    input double ATRTakeMultiplier = 3.0; // Take profit as multiple of ATR
    input double TrailingStart = 1.0; // Trailing start in ATR multiples
    input double TrailingStep = 0.5; // Trailing step in ATR multiples
    input int MagicNumber = 202415; // Unique EA identifier
    input int MaxSpread = 30; // Maximum allowed spread in points
    input double DailyLossLimit = 5.0; // Daily loss limit as percentage of balance
    input bool UseFridayClose = true; // Close trades before Friday 20:00 GMT

    //--- global variables
    double dailyStartBalance = 0;
    datetime lastBarTime = 0;
    bool fridayCloseExecuted = false;
    double currentTrailingStop = 0;

    //+------------------------------------------------------------------+
    //| Expert initialization function |
    //+------------------------------------------------------------------+
    int OnInit()
    {
    dailyStartBalance = AccountBalance();
    lastBarTime = 0;
    fridayCloseExecuted = false;
    return(INIT_SUCCEEDED);
    }

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

    //+------------------------------------------------------------------+
    //| Expert tick function |
    //+------------------------------------------------------------------+
    void OnTick()
    {
    // 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) >= 20)
    {
    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];

    // Check existing position
    int posCount = CountPositions();
    if(posCount > 0)
    {
    ManageTrailingStop();
    return;
    }

    // Calculate indicators on closed bar
    double fastEMA = iMA(Symbol(), PERIOD_H1, FastEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
    double slowEMA = iMA(Symbol(), PERIOD_H1, SlowEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
    double fastEMAPrev = iMA(Symbol(), PERIOD_H1, FastEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 2);
    double slowEMAPrev = iMA(Symbol(), PERIOD_H1, SlowEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 2);
    double rsi = iRSI(Symbol(), PERIOD_H1, RSIPeriod, PRICE_CLOSE, 1);
    double atr = iATR(Symbol(), PERIOD_H1, ATRPeriod, 1);

    if(atr <= 0) atr = 200
    Point;

    int cmd = -1;
    double sl = 0, tp = 0;
    double ask = Ask;
    double bid = Bid;

    // Bullish crossover: fast EMA crosses above slow EMA, RSI > 50 for momentum
    if(fastEMAPrev <= slowEMAPrev && fastEMA > slowEMA && rsi > 50)
    {
    cmd = OP_BUY;
    sl = bid - (atr ATRStopMultiplier);
    tp = bid + (atr
    ATRTakeMultiplier);
    }
    // Bearish crossover: fast EMA crosses below slow EMA, RSI < 50 for momentum
    else if(fastEMAPrev >= slowEMAPrev && fastEMA < slowEMA && rsi < 50)
    {
    cmd = OP_SELL;
    sl = ask + (atr ATRStopMultiplier);
    tp = ask - (atr
    ATRTakeMultiplier);
    }

    if(cmd != -1)
    {
    int ticket = OrderSend(Symbol(), cmd, LotSize, (cmd==OP_BUY?ask:bid), 3, sl, tp, "Gold Momentum Flow", MagicNumber, 0, clrNONE);
    if(ticket < 0)
    Print("OrderSend failed: ", GetLastError());
    else
    currentTrailingStop = 0;
    }
    }

    //+------------------------------------------------------------------+
    //| Manage trailing stop for open position |
    //+------------------------------------------------------------------+
    void ManageTrailingStop()
    {
    for(int i = OrdersTotal()-1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
    {
    double atr = iATR(Symbol(), PERIOD_H1, ATRPeriod, 1);
    if(atr <= 0) atr = 200 Point;

    double newSL = 0;
    double trailTrigger = atr
    TrailingStart;

    if(OrderType() == OP_BUY)
    {
    double profitPoints = (Bid - OrderOpenPrice()) / Point;
    if(profitPoints >= trailTrigger / Point)
    {
    newSL = Bid - (atr TrailingStep);
    if(newSL > OrderStopLoss())
    {
    if(OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE))
    Print("Trailing stop updated for BUY #", OrderTicket());
    }
    }
    }
    else if(OrderType() == OP_SELL)
    {
    double profitPoints = (OrderOpenPrice() - Ask) / Point;
    if(profitPoints >= trailTrigger / Point)
    {
    newSL = Ask + (atr
    TrailingStep);
    if(newSL < OrderStopLoss() || OrderStopLoss() == 0)
    {
    if(OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE))
    Print("Trailing stop updated for SELL #", OrderTicket());
    }
    }
    }
    break;
    }
    }
    }
    }

    //+------------------------------------------------------------------+
    //| 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, 3, clrNONE);
    else if(OrderType() == OP_SELL)
    OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrNONE);
    }
    }
    }
    }
    //+------------------------------------------------------------------+
    ``
    Reference: Original MQL4 code for educational purposes.
    Disclaimer: Trading Forex and Gold involves substantial risk of loss. This EA is provided as-is without any warranty of profitability. Always test on a demo account before live deployment. Past performance does not indicate future results.