Summary: Gold Pure Trend EA is a trend-only MQL4 expert advisor for XAUUSD. Uses dual EMA crossover with ADX confirmation and dynamic ATR stop loss. Suitable for H1 timeframe.
Gold Pure Trend EA implements a disciplined pure trend-following strategy designed specifically for gold's characteristic trending behavior. The EA avoids counter-trend entries, mean reversion, or grid systems. It uses dual EMA crossover (fast 20, slow 50) as primary trend signal, ADX(14) above 25 to confirm trend strength, and dynamic ATR-based stop loss that adapts to volatility. A trailing stop locks in profits during extended trends. Only one position is allowed at a time, with daily loss protection and Friday close.
Recommended Timeframe: H1
Trading Logic:
1. Trend Signal: Fast EMA(20) crosses above Slow EMA(50) for uptrend; opposite for downtrend.
2. Trend Strength Confirmation: ADX(14) must be above 25 to filter out ranging markets.
3. Entry: On crossover completion (bar close), enter in the direction of the crossover.
4. Exit: Initial stop loss at 1.8x ATR, take profit at 3.5x ATR. Trailing stop activates after profit reaches 1.5x ATR.
```mql4
//+------------------------------------------------------------------+
//| GoldPureTrendEA.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 lots)
input int FastMAPeriod = 20; // Fast EMA period for trend signal
input int SlowMAPeriod = 50; // Slow EMA period for trend signal
input int ADXPeriod = 14; // ADX period for trend strength filter
input int ADXThreshold = 25; // Minimum ADX value to allow trading
input int ATRPeriod = 14; // ATR period for dynamic stop loss
input double ATRStopMultiplier = 1.8; // Stop loss as multiple of ATR
input double ATRTakeMultiplier = 3.5; // Take profit as multiple of ATR
input double TrailingStart = 1.5; // Trailing activates after profit (x ATR)
input double TrailingStep = 0.8; // Trailing step (x ATR)
input int MagicNumber = 202418; // 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;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
dailyStartBalance = AccountBalance();
lastBarTime = 0;
fridayCloseExecuted = false;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Comment("");
}
//+------------------------------------------------------------------+
//| 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 trailTrigger = atr * TrailingStart;
double trailStep = atr * TrailingStep;
if(OrderType() == OP_BUY)
{
double profit = Bid - OrderOpenPrice();
if(profit >= trailTrigger)
{
double newSL = Bid - trailStep;
if(newSL > OrderStopLoss())
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE);
}
}
else if(OrderType() == OP_SELL)
{
double profit = OrderOpenPrice() - Ask;
if(profit >= trailTrigger)
{
double newSL = Ask + trailStep;
if(newSL < OrderStopLoss() || OrderStopLoss() == 0)
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE);
}
}
break;
}
}
}
}
//+------------------------------------------------------------------+
//| 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)
{
double atr = iATR(Symbol(), PERIOD_H1, ATRPeriod, 1);
if(atr > 0) ManageTrailingStop(atr);
return;
}
// Calculate indicators on closed bar
double fastEMA = iMA(Symbol(), PERIOD_H1, FastMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
double slowEMA = iMA(Symbol(), PERIOD_H1, SlowMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
double fastEMAPrev = iMA(Symbol(), PERIOD_H1, FastMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 2);
double slowEMAPrev = iMA(Symbol(), PERIOD_H1, SlowMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 2);
double adx = iADX(Symbol(), PERIOD_H1, ADXPeriod, PRICE_CLOSE, MODE_MAIN, 1);
double atr = iATR(Symbol(), PERIOD_H1, ATRPeriod, 1);
if(atr <= 0) atr = 150 * Point;
// Trend strength filter
if(adx < ADXThreshold)
{
Comment("ADX below threshold: ", adx);
return;
}
int cmd = -1;
double sl = 0, tp = 0;
double ask = Ask;
double bid = Bid;
// Bullish crossover: fast EMA crosses above slow EMA
if(fastEMAPrev <= slowEMAPrev && fastEMA > slowEMA)
{
cmd = OP_BUY;
sl = bid - (atr * ATRStopMultiplier);
tp = bid + (atr * ATRTakeMultiplier);
}
// Bearish crossover: fast EMA crosses below slow EMA
else if(fastEMAPrev >= slowEMAPrev && fastEMA < slowEMA)
{
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 Pure Trend", 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)
{
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.