Gold Fusion EA is engineered specifically for gold (XAUUSD) to deliver low-risk, stable returns by adapting to gold's high volatility and frequent reversal characteristics. The EA employs a multi-timeframe approach: the H4 chart determines the primary trend direction (EMA50), while the H1 chart looks for pullback entry signals (RSI divergence and candlestick confirmation). An adaptive ATR-based stop loss and trailing stop mechanism locks in profits while volatility expands. The EA also includes spread protection, daily equity drawdown limits, and Friday close-out to avoid weekend gaps.
Recommended Timeframe: H1 (chart attached to H1, but uses H4 data automatically)
Trading Logic:
``
mql4
//+------------------------------------------------------------------+
//| GoldFusionEA.mq4 |
//+------------------------------------------------------------------+
#property copyright ""
#property link ""
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Input parameters with detailed comments |
//+------------------------------------------------------------------+
input double LotSize = 0.01; // Fixed lot size (0.01 recommended)
input int H4TrendMAPeriod = 50; // EMA period on H4 for trend filter
input int H1RSIPeriod = 14; // RSI period on H1 for divergence
input int H1ATRPeriod = 14; // ATR period on H1 for volatility filter
input double VolatilityMinRatio = 0.8; // Min ATR ratio (current/avg) to trade
input double VolatilityMaxRatio = 1.6; // Max ATR ratio (current/avg) to trade
input int StopLossPips = 250; // Fixed stop loss in points (250 = 25 pips)
input double StopLossATRMultiplier = 1.2; // Dynamic stop = ATR this (takes larger of fixed/dynamic)
input int TakeProfitPips = 500; // Take profit in points (50 pips)
input int TrailingStartPips = 350; // Trailing activates after profit (points)
input int TrailingStepPips = 80; // Trailing step distance (points)
input double DailyLossLimit = 4.0; // Daily loss limit as % of balance
input int MaxSpread = 35; // Maximum allowed spread in points
input bool CloseOnFriday = true; // Close all trades before Friday 20:00 GMT
input int MagicNumber = 202419; // Unique EA identifier
//+------------------------------------------------------------------+
//| Global variables |
//+------------------------------------------------------------------+
double dailyStartBalance = 0;
datetime lastH1BarTime = 0;
bool fridayCloseDone = false;
double avgATR_H1 = 0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
dailyStartBalance = AccountBalance();
lastH1BarTime = 0;
fridayCloseDone = false;
avgATR_H1 = iATR(Symbol(), PERIOD_H1, H1ATRPeriod, 1);
if(avgATR_H1 <= 0) avgATR_H1 = 200 Point;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Comment("");
}
//+------------------------------------------------------------------+
//| Calculate ATR moving average (rolling) |
//+------------------------------------------------------------------+
double UpdateAvgATR()
{
double currentATR = iATR(Symbol(), PERIOD_H1, H1ATRPeriod, 1);
if(currentATR > 0)
avgATR_H1 = (avgATR_H1 0.95) + (currentATR 0.05);
return currentATR;
}
//+------------------------------------------------------------------+
//| Detect RSI divergence (bullish or bearish) |
//+------------------------------------------------------------------+
int DetectRSIDivergence()
{
// Get RSI values for last 3 bars on H1
double rsi[3];
double price[3];
for(int i = 1; i <= 3; i++)
{
rsi[i-1] = iRSI(Symbol(), PERIOD_H1, H1RSIPeriod, PRICE_CLOSE, i);
price[i-1] = iClose(Symbol(), PERIOD_H1, i);
}
// Bullish divergence: price makes lower low, RSI makes higher low
if(price[0] < price[1] && price[1] < price[2] && rsi[0] > rsi[1] && rsi[1] > rsi[2])
return 1; // Bullish divergence
// Bearish divergence: price makes higher high, RSI makes lower high
if(price[0] > price[1] && price[1] > price[2] && rsi[0] < rsi[1] && rsi[1] < rsi[2])
return -1; // Bearish divergence
return 0; // No divergence
}
//+------------------------------------------------------------------+
//| Check engulfing candlestick pattern on H1 |
//+------------------------------------------------------------------+
bool IsEngulfing(int direction)
{
double open1 = iOpen(Symbol(), PERIOD_H1, 1);
double close1 = iClose(Symbol(), PERIOD_H1, 1);
double open2 = iOpen(Symbol(), PERIOD_H1, 2);
double close2 = iClose(Symbol(), PERIOD_H1, 2);
if(direction == 1) // Bullish engulfing
{
return (close2 < open2) && (close1 > open1) && (close1 > open2) && (open1 < close2);
}
else if(direction == -1) // Bearish engulfing
{
return (close2 > open2) && (close1 < open1) && (close1 < open2) && (open1 > close2);
}
return false;
}
//+------------------------------------------------------------------+
//| H4 trend direction (1 = up, -1 = down, 0 = neutral) |
//+------------------------------------------------------------------+
int GetH4Trend()
{
double ema50 = iMA(Symbol(), PERIOD_H4, H4TrendMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
double close1 = iClose(Symbol(), PERIOD_H4, 1);
if(close1 > ema50) return 1;
if(close1 < ema50) return -1;
return 0;
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Daily drawdown protection
double equity = AccountEquity();
double lossPct = (dailyStartBalance - equity) / dailyStartBalance 100;
if(lossPct >= DailyLossLimit)
{
Comment("Daily loss limit ", DailyLossLimit, "% reached. Trading paused.");
return;
}
// Friday close-out (avoid weekend gap)
if(CloseOnFriday && !fridayCloseDone)
{
datetime now = TimeCurrent();
if(TimeDayOfWeek(now) == 5 && TimeHour(now) >= 20)
{
CloseAllOrders();
fridayCloseDone = true;
Comment("All positions closed for weekend.");
return;
}
if(TimeDayOfWeek(now) != 5)
fridayCloseDone = false;
}
// Spread protection
int spread = (int)MarketInfo(Symbol(), MODE_SPREAD);
if(spread > MaxSpread)
{
Comment("Spread too high: ", spread);
return;
}
// New H1 bar check
if(Time[0] == lastH1BarTime)
return;
lastH1BarTime = Time[0];
// Manage existing positions (trailing stop)
if(CountPositions() > 0)
{
ManageTrailingStop();
return;
}
// Update ATR and volatility filter
double currentATR = UpdateAvgATR();
double atrRatio = currentATR / avgATR_H1;
if(atrRatio < VolatilityMinRatio || atrRatio > VolatilityMaxRatio)
{
Comment("Volatility filter: ATR ratio = ", DoubleToString(atrRatio,2), " out of range [",VolatilityMinRatio,",",VolatilityMaxRatio,"]");
return;
}
// Get H4 trend direction
int trendDir = GetH4Trend();
if(trendDir == 0)
{
Comment("No clear trend on H4. Waiting.");
return;
}
// Detect RSI divergence
int divDir = DetectRSIDivergence();
if(divDir == 0)
{
Comment("No RSI divergence detected.");
return;
}
// Check if divergence aligns with trend
if((trendDir == 1 && divDir == -1) || (trendDir == -1 && divDir == 1))
{
Comment("Divergence opposes H4 trend. Skip.");
return;
}
// Confirm with engulfing candle
if(!IsEngulfing(divDir))
{
Comment("No confirming engulfing candle.");
return;
}
// Calculate dynamic stop loss
int fixedStop = StopLossPips;
int dynamicStop = (int)(currentATR / Point StopLossATRMultiplier);
int finalStop = MathMax(fixedStop, dynamicStop);
double sl = 0, tp = 0;
int cmd = -1;
double ask = Ask;
double bid = Bid;
if(divDir == 1) // Long signal
{
cmd = OP_BUY;
sl = bid - finalStop Point;
tp = bid + TakeProfitPips Point;
}
else if(divDir == -1) // Short signal
{
cmd = OP_SELL;
sl = ask + finalStop Point;
tp = ask - TakeProfitPips Point;
}
if(cmd != -1)
{
int ticket = OrderSend(Symbol(), cmd, LotSize, (cmd==OP_BUY?ask:bid), 3, sl, tp, "Gold Fusion", MagicNumber, 0, clrNONE);
if(ticket < 0)
Print("OrderSend error: ", GetLastError());
}
}
//+------------------------------------------------------------------+
//| Trailing stop management |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
for(int i = OrdersTotal()-1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
{
double newSL = 0;
if(OrderType() == OP_BUY)
{
double profitPoints = (Bid - OrderOpenPrice()) / Point;
if(profitPoints >= TrailingStartPips)
{
newSL = Bid - TrailingStepPips Point;
if(newSL > OrderStopLoss())
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE);
}
}
else if(OrderType() == OP_SELL)
{
double profitPoints = (OrderOpenPrice() - Ask) / Point;
if(profitPoints >= TrailingStartPips)
{
newSL = Ask + TrailingStepPips Point;
if(newSL < OrderStopLoss() || OrderStopLoss() == 0)
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE);
}
}
break;
}
}
}
}
//+------------------------------------------------------------------+
//| Count open positions |
//+------------------------------------------------------------------+
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 EA |
//+------------------------------------------------------------------+
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: Gold trading carries significant risk due to high volatility. This EA is provided "as is" without any guarantee of profitability. Always test on a demo account for at least 2 months before live deployment. Past performance does not guarantee future results.