Summary: Gold Trend Harmony EA is a low-risk MQL4 expert advisor for XAUUSD. It uses EMA trend direction, ATR volatility filter, and fixed stop loss/take profit. Suitable for H1 timeframe.




Gold Trend Harmony EA is designed specifically for gold (XAUUSD) with a low-risk, stable operational approach. It incorporates trend filtering, volatility-based entry, and strict money management to adapt to gold's high volatility and frequent reversals. The EA trades only in the direction of the major trend (EMA50) and uses ATR to avoid trading during extreme volatility. Each trade has a fixed stop loss and take profit, with a daily equity protection mechanism.

Recommended Timeframe: H1
Trading Logic:
1. Trend Filter: Price above EMA50 → long only; below → short only.
2. Entry: After trend confirmation, wait for a pullback to EMA50 and a bullish/bearish close.
3. Volatility Guard: ATR(14) > ATR threshold × 20-point average → no new trade.
4. Risk Control: Fixed SL (300 points) and TP (600 points), max 1 trade at a time, daily loss limit 5%.

```mql4
//+------------------------------------------------------------------+
//| GoldTrendHarmonyEA.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 StopLossPoints = 300; // Stop loss in points (300 = 300 pips for gold, 0.01 lot ~ $3 per point)
input int TakeProfitPoints = 600; // Take profit in points (2:1 risk-reward)
input int TrendMAPeriod = 50; // Period of EMA for trend filter
input int ATRPeriod = 14; // Period for ATR volatility indicator
input double ATRMultiplier = 1.5; // ATR threshold multiplier (higher = less trades)
input int MagicNumber = 202411; // Unique EA identifier
input int MaxSpread = 35; // Maximum allowed spread (in points)
input double DailyLossLimit = 5.0; // Daily loss limit in percentage of balance (5%)
input bool UseCloseOnFriday = true; // Close all trades before Friday 21:00

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

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
dailyStartBalance = AccountBalance();
lastBarTime = 0;
isFridayCloseExecuted = 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(UseCloseOnFriday && !isFridayCloseExecuted)
{
datetime currentTime = TimeCurrent();
if(TimeDayOfWeek(currentTime) == 5 && TimeHour(currentTime) >= 21)
{
CloseAllOrders();
isFridayCloseExecuted = true;
return;
}
if(TimeDayOfWeek(currentTime) != 5)
isFridayCloseExecuted = false;
}

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

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

// Check for existing position
if(CountPositions() > 0)
return;

// Trend direction using EMA50
double ema50 = iMA(Symbol(), PERIOD_H1, TrendMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
double close1 = iClose(Symbol(), PERIOD_H1, 1);
double close2 = iClose(Symbol(), PERIOD_H1, 2);

// ATR volatility filter
double atr = iATR(Symbol(), PERIOD_H1, ATRPeriod, 1);
double atrThreshold = ATRMultiplier * 200; // 200 points reference (gold typical point value)
if(atr > atrThreshold)
{
Comment("High volatility, no trade");
return;
}

// Bullish condition: price above EMA50, previous bar close > EMA50, bullish engulf or close > open
bool bullish = (close1 > ema50 && close2 > ema50 && close1 > iOpen(Symbol(), PERIOD_H1, 1));
// Bearish condition: price below EMA50
bool bearish = (close1 < ema50 && close2 < ema50 && close1 < iOpen(Symbol(), PERIOD_H1, 1));

double sl = 0, tp = 0;
int cmd = -1;

if(bullish)
{
cmd = OP_BUY;
sl = SymbolInfoDouble(Symbol(), SYMBOL_BID) - StopLossPoints * Point;
tp = SymbolInfoDouble(Symbol(), SYMBOL_BID) + TakeProfitPoints * Point;
}
else if(bearish)
{
cmd = OP_SELL;
sl = SymbolInfoDouble(Symbol(), SYMBOL_ASK) + StopLossPoints * Point;
tp = SymbolInfoDouble(Symbol(), SYMBOL_ASK) - TakeProfitPoints * Point;
}

if(cmd != -1)
{
int ticket = OrderSend(Symbol(), cmd, LotSize, (cmd==OP_BUY?Ask:Bid), 3, sl, tp, "Gold Harmony EA", MagicNumber, 0, clrNONE);
if(ticket < 0)
Print("OrderSend failed: ", GetLastError());
}
}

//+------------------------------------------------------------------+
//| 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)
{
bool result;
if(OrderType() == OP_BUY)
result = OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrNONE);
else if(OrderType() == OP_SELL)
result = OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrNONE);
}
}
}
}
//+------------------------------------------------------------------+
```
Reference: Original MQL4 code for educational purposes.
Disclaimer: Trading Forex and Gold involves high risk. This EA is provided as-is without any guarantee of profit. Test thoroughly on demo before live trading. Past performance does not guarantee future results.