Summary: Gold Volatility Guard EA is an MQL4 expert advisor for XAUUSD that uses MACD trend filter, multi-tier position scaling (max 3 positions), and equity-based stop loss management. Suitable for H4 timeframe stable operation.




Gold Volatility Guard EA is engineered specifically for XAUUSD with a focus on capital preservation. Unlike aggressive grid systems, this EA employs a disciplined trend-following approach with MACD(12,26,9) confirming trend direction and EMA cross validation. The EA uses a multi-tier position system where each additional tier must meet stricter entry conditions. An equity-based trailing stop protects profits while allowing trend continuation. The EA includes daily loss limits, spread filters, and Friday close mechanisms.

Recommended Timeframe: H4
Trading Logic:
1. Trend Detection: MACD main line above signal line for uptrend; below for downtrend. EMA(20) and EMA(50) cross for additional confirmation.
2. Entry Signal: Price retraces to EMA(50) and closes beyond it in trend direction, with MACD momentum confirmation.
3. Multi-Tier Scaling: Additional positions allowed only when existing position is profitable by 1.5x ATR (max 3 total).
4. Risk Management: ATR-based dynamic stop loss, equity-based trailing, daily loss limit 5%.

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

//--- input parameters with comments
input double BaseLotSize = 0.01; // Base lot size for first position
input int FastEMAPeriod = 20; // Fast EMA period for trend confirmation
input int SlowEMAPeriod = 50; // Slow EMA period for trend filter
input int MACDFast = 12; // MACD fast EMA period
input int MACDSlow = 26; // MACD slow EMA period
input int MACDSignal = 9; // MACD signal line period
input int ATRPeriod = 14; // ATR period for volatility
input double ATRStopMultiplier = 1.5; // Stop loss as multiple of ATR
input double ATRTakeMultiplier = 2.8; // Take profit as multiple of ATR
input double TierProfitThreshold = 1.5; // Profit required (x ATR) to add next tier
input int MaxTiers = 3; // Maximum number of position tiers
input double TrailingStart = 0.8; // Trailing activates at profit (x ATR)
input double TrailingStep = 0.4; // Trailing step (x ATR)
input int MagicNumber = 202421; // 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;
int currentTier = 0;

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

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

//+------------------------------------------------------------------+
//| Get MACD trend direction |
//+------------------------------------------------------------------+
int GetMACDTrend()
{
double macdMain = iMACD(Symbol(), PERIOD_H4, MACDFast, MACDSlow, MACDSignal, PRICE_CLOSE, MODE_MAIN, 1);
double macdSignal = iMACD(Symbol(), PERIOD_H4, MACDFast, MACDSlow, MACDSignal, PRICE_CLOSE, MODE_SIGNAL, 1);
double macdHist = macdMain - macdSignal;

if(macdHist > 0) return 1; // Bullish
if(macdHist < 0) return -1; // Bearish
return 0;
}

//+------------------------------------------------------------------+
//| Check EMA alignment |
//+------------------------------------------------------------------+
int GetEMAAlignment()
{
double emaFast = iMA(Symbol(), PERIOD_H4, FastEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
double emaSlow = iMA(Symbol(), PERIOD_H4, SlowEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
double close = iClose(Symbol(), PERIOD_H4, 1);

bool bullish = (close > emaSlow && emaFast > emaSlow);
bool bearish = (close < emaSlow && emaFast < emaSlow);

if(bullish) return 1;
if(bearish) return -1;
return 0;
}

//+------------------------------------------------------------------+
//| Calculate current tier count for this EA |
//+------------------------------------------------------------------+
int GetCurrentTierCount()
{
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;
}

//+------------------------------------------------------------------+
//| Get average profit per position (in points) |
//+------------------------------------------------------------------+
double GetAverageProfitInATR(double atr)
{
if(atr <= 0) return 0;

double totalProfitPoints = 0;
int count = 0;

for(int i = OrdersTotal()-1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
{
double profitPoints = 0;
if(OrderType() == OP_BUY)
profitPoints = (Bid - OrderOpenPrice()) / Point;
else if(OrderType() == OP_SELL)
profitPoints = (OrderOpenPrice() - Ask) / Point;

totalProfitPoints += profitPoints;
count++;
}
}
}

if(count == 0) return 0;
return (totalProfitPoints / count) * Point;
}

//+------------------------------------------------------------------+
//| Check if we can add another tier |
//+------------------------------------------------------------------+
bool CanAddTier(double atr)
{
int currentCount = GetCurrentTierCount();
if(currentCount >= MaxTiers) return false;
if(currentCount == 0) return true;

double avgProfit = GetAverageProfitInATR(atr);
double requiredProfit = atr * TierProfitThreshold;

return (avgProfit >= requiredProfit);
}

//+------------------------------------------------------------------+
//| Check pullback entry condition |
//+------------------------------------------------------------------+
bool CheckPullbackEntry(int direction, double &entryPrice, double &sl, double &tp, double atr)
{
double emaSlow = iMA(Symbol(), PERIOD_H4, SlowEMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
double close1 = iClose(Symbol(), PERIOD_H4, 1);
double open1 = iOpen(Symbol(), PERIOD_H4, 1);
double low1 = iLow(Symbol(), PERIOD_H4, 1);
double high1 = iHigh(Symbol(), PERIOD_H4, 1);

if(direction == 1) // Long: pullback to EMA50 then close above
{
bool pulledToEMA = (low1 <= emaSlow && close1 > emaSlow);
bool bullishClose = (close1 > open1);
bool belowPreviousHigh = (high1 < iHigh(Symbol(), PERIOD_H4, 2));

if(pulledToEMA && bullishClose && belowPreviousHigh)
{
entryPrice = Ask;
sl = entryPrice - (atr * ATRStopMultiplier);
tp = entryPrice + (atr * ATRTakeMultiplier);
return true;
}
}
else if(direction == -1) // Short: pullback to EMA50 then close below
{
bool pulledToEMA = (high1 >= emaSlow && close1 < emaSlow);
bool bearishClose = (close1 < open1);
bool abovePreviousLow = (low1 > iLow(Symbol(), PERIOD_H4, 2));

if(pulledToEMA && bearishClose && abovePreviousLow)
{
entryPrice = Bid;
sl = entryPrice + (atr * ATRStopMultiplier);
tp = entryPrice - (atr * ATRTakeMultiplier);
return true;
}
}
return false;
}

//+------------------------------------------------------------------+
//| Manage trailing stop for all positions |
//+------------------------------------------------------------------+
void ManageTrailingStop(double atr)
{
if(atr <= 0) atr = avgATR;
double activate = atr * TrailingStart;
double step = atr * TrailingStep;

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 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);
}
}
}
}
}
}

//+------------------------------------------------------------------+
//| Calculate lot size for new tier |
//+------------------------------------------------------------------+
double GetTierLotSize()
{
int tier = GetCurrentTierCount();
if(tier == 0) return BaseLotSize;
return NormalizeDouble(BaseLotSize * (1.0 + tier * 0.2), 2); // Slight increase but controlled
}

//+------------------------------------------------------------------+
//| 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) >= 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 (H4)
if(Time[0] == lastBarTime)
return;
lastBarTime = Time[0];

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

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

// Manage existing positions (trailing stop)
int posCount = GetCurrentTierCount();
if(posCount > 0)
{
ManageTrailingStop(atr);
}

// Check trend direction
int macdTrend = GetMACDTrend();
int emaAlign = GetEMAAlignment();

if(macdTrend == 0 || emaAlign == 0 || macdTrend != emaAlign)
{
Comment("Trend not aligned. MACD: ", macdTrend, " EMA: ", emaAlign);
return;
}

// Check if we can add a new tier
if(!CanAddTier(atr))
{
Comment("Cannot add tier. Profit threshold not met.");
return;
}

// Check entry condition
double entryPrice = 0, sl = 0, tp = 0;
if(CheckPullbackEntry(macdTrend, entryPrice, sl, tp, atr))
{
double lotSize = GetTierLotSize();
int cmd = (macdTrend == 1) ? OP_BUY : OP_SELL;
int ticket = OrderSend(Symbol(), cmd, lotSize, entryPrice, 5, sl, tp, "Volatility Guard", MagicNumber, 0, clrNONE);
if(ticket < 0)
Print("OrderSend failed: ", GetLastError());
else
Print("Tier ", GetCurrentTierCount(), " opened. Direction: ", cmd==OP_BUY?"BUY":"SELL");
}
}

//+------------------------------------------------------------------+
//| 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 institutional trend-following principles for XAUUSD .
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 before live deployment. Past performance does not guarantee future results.