Pipsgrowth EX18116 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M15, H4
Pipsgrowth.com EX18116 QuantumGold — multi-timeframe EMA trend confluence + dynamic lot sizing, full 12-layer stack.
Overview
EX18116 QuantumGold is a 126-line MQL5 Expert Advisor that trades gold by demanding the same trend to be visible on three timeframes simultaneously before it will commit a single position. The file declares itself part of the TrendFollow family and proposes XAUUSD on M15 (with H1 and H4 confirmation candles), although the same skeleton is portable to any symbol for which the broker supplies continuous tick data. Magic 22218116 marks every order, and the trade comment is always suffixed with Psgrowth.com Expert_18116 Buy or Sell so the position is unambiguous in the terminal journal.
The indicator stack is intentionally narrow. Three Exponential Moving Averages of period 50 are created in OnInit — hM15_EMA, hH1_EMA, and hH4_EMA — each applied to PRICE_CLOSE. A single Average True Range of period 14, sampled on H1, supplies the stop distance. There is no RSI, no ADX, no MACD, no Bollinger envelope, and no dashboard panel. The OnInit routine registers the four handles, the OnDeinit releases them, and that is the entire housekeeping footprint. Indicator lookups happen once per closed bar, and the function reads exactly one bar of data from each handle using CopyBuffer(..., 1, 1, buf), so the signal is by construction a closed-bar, non-repainting decision.
The entry rule is the file's defining feature. When InpMTFConfirm is true (the default), a long entry requires bid > M15 EMA(50) AND bid > H1 EMA(50) AND bid > H4 EMA(50); a short entry requires the symmetric three-way violation on the bid side. When InpMTFConfirm is false, the multi-timeframe guard collapses to a single condition against the H1 EMA. The price-level check — comparing bid directly against each EMA value — is the kind of alignment test that fires late in an established trend and rarely on counter-trend re-entries, which is precisely the bias a gold swing trader is usually trying to manufacture.
Stop loss and take profit are sized from the ATR(14) read on the H1 timeframe at the same time the EMAs are sampled. The stop is ATR * 1.5, the take profit is SL * 2.0, which locks in a hard 1:2 reward-to-risk ratio on every order. Both protective prices are sent to the broker with the order and are then maintained by the trailing module. The lot size is calculated by CalcLot(double sl), which uses the formula lot = max(0.01, (balance * InpRiskPct/100) / (sl/ts * tickValue)), where InpRiskPct defaults to 1.0 percent of the current balance. This is a textbook risk-percent-of-balance sizer with a hard floor of 0.01 lots, normalized to two decimals. There is no compounding equity curve, no Kelly fraction, and no maximum-lot cap, so a trader who wants to cap exposure on larger accounts has to do it via InpRiskPct itself.
Position management is the ManageTrailing() function, called every tick before any new entry is considered. It walks PositionsTotal() from the end of the list, filters by POSITION_MAGIC == InpMagicNumber and POSITION_SYMBOL == _Symbol, and then computes a candidate stop as bid - InpTrailingStop * _Point for a buy and ask + InpTrailingStop * _Point for a sell. The new stop is only accepted if it is past the open price (i.e. the trade is in profit) AND it is tighter than the existing stop. Each accepted modification is sent through TryModify_EX18116, which retries up to three times on TRADE_RETCODE_REQUOTE, TRADE_RETCODE_TIMEOUT, TRADE_RETCODE_PRICE_OFF, or TRADE_RETCODE_PRICE_CHANGED, sleeping 100 ms between attempts. InpTrailingStop defaults to 40 points (4 pips on a 5-digit gold quote), so the stop tightens every 40 points of favorable movement and never loosens.
The file is single-position by design. HasTrade() is called before any entry block; if any position with the matching magic and symbol exists, the EA simply returns for that bar. There is no pyramiding, no scaling-in, no hedge layer, and no partial take-profit. The two retry helpers TryClose_EX18116 and TryClosePartial_EX18116 are declared in the source but are never referenced from the live code path — they are scaffolding kept in case the EA is later extended to do basket closes or partial exits. The only retry wrapper actually invoked is TryModify_EX18116.
The risk guard that does run is the daily loss cap. On the first tick after the server clock hits 00:00, the EA records dayStartBalance = AccountInfoDouble(ACCOUNT_BALANCE) and updates lastDay. On every tick afterward, it computes (dayStartBalance - equity) / dayStartBalance * 100 and returns immediately if that loss reaches InpMaxDailyLoss percent, which defaults to 3.0. This is a start-of-day balance check rather than a peak-equity drawdown check, so a strong early profit does not raise the threshold — only the open-of-day figure matters. When the cap is hit, the EA continues to call ManageTrailing() on existing positions but stops opening new ones, which is the right asymmetry for a session pause.
Other claimed layers in the file's header comment are not implemented in the body. There is no OnTester function, no regime classifier, no capital cap input, no news filter, no session filter, no ATR-volatility filter, no pyramid, no breakeven, and no dashboard. The header advertises the full twelve-layer stack as a marketing summary, but the executable code is closer to a five-piece system: trend confluence, ATR-based stop, 1:2 R:R target, percent-risk sizing, and a 40-point trailing stop with a 3 percent daily loss circuit breaker.
For a backtest, the practical consequences are: each trade needs roughly 0.5× ATR of room in the stop, so the EA prefers XAUUSD sessions where 1.5× the H1 ATR is at least a few dollars — which is just the Asia/London overlap and the first half of New York. The single-position constraint means the equity curve will be a series of separate round-trips rather than overlapping grids, and the lack of a breakeven step means losing trades are typically closed by the trailing stop only when the structure has clearly turned. Testers should expect the win rate to be modest and the average winner to be twice the average loser, which is the only sustainable combination for a 1:2 R:R with a 1 percent risk budget.
Strategy Deep Dive
Three EMA(50) handles (M15/H1/H4) and a single H1 ATR(14) are created in OnInit; every tick first checks for a new bar, resets the daily balance if the server clock has rolled to 00:00, then enforces a 3% daily loss guard that returns early if (dayStartBalance - equity)/dayStartBalance*100 >= InpMaxDailyLoss. ManageTrailing() is called next and walks positions filtered by magic 22218116 and the chart symbol, tightening each stop to ± InpTrailingStop * _Point only when the new stop is past the open price and tighter than the current SL, retrying failed modifications through TryModify_EX18116 (3×100ms). HasTrade() then short-circuits the rest of the tick if any open position already exists, enforcing a one-position-at-a-time regime. The signal block copies one bar back from each EMA and the ATR, computes SL = ATR*1.5 and TP = SL*2.0, sizes the lot with CalcLot (1% of balance / (sl/ts * tickValue), floored at 0.01), and fires a single trade.Buy or trade.Sell with the comment suffixed by Buy/Sell. The other advertised layers (regime classifier, OnTester, capital cap, news filter, session filter, dashboard) are absent from the body.
A long entry requires bid > M15 EMA(50) AND bid > H1 EMA(50) AND bid > H4 EMA(50) on a closed bar; a short entry is the symmetric three-way violation on the bid side. When InpMTFConfirm is set to false, the multi-timeframe guard collapses to a single condition against the H1 EMA(50). The signal is sampled once per closed M15 bar via CopyBuffer(..., 1, 1, ...) and is therefore non-repainting.
Exits are managed entirely by the broker-side stop and take profit, with no in-code exit logic other than the trailing stop. ManageTrailing() runs on every tick and tightens the protective stop to bid ± InpTrailingStop * _Point whenever the new stop is in profit and tighter than the current SL; it does not close positions outright. The two TryClose* retry helpers declared in the source are never invoked from the active path.
Stop loss is ATR(14) on H1 × 1.5, computed at the moment the entry fires and sent to the broker with the order. After that, the stop is ratcheted by ManageTrailing() to bid - 40 * _Point (BUY) or ask + 40 * _Point (SELL) whenever the trade is in profit, never loosening.
Take profit is SL × 2.0, locking a hard 1:2 reward-to-risk ratio on every order. It is sent to the broker with the entry and never adjusted by ManageTrailing() (the trailing function only modifies the SL).
Best deployed on XAUUSD M15 with at least $100 of balance (the floor enforced by the 0.01-lot minimum in CalcLot), although the 1% risk budget benefits from a larger account so that 1.5× the H1 ATR fits inside the available margin. The trailing stop is a 40-point fixed step, so a low-spread broker is preferable — ECN/RAW with sub-pip typical spread on gold keeps the trail honest. The 3% daily loss guard assumes a session that is open during the Asia/London overlap and the first half of New York, which is when XAUUSD ATR is most often wide enough to honor the SL and most often trending, which is what the three-EMA confluence filter is looking for. Single-position construction means this is a swing-trend tool, not a portfolio diversification building block.
Strategy Logic
Pipsgrowth EX18116 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218116
Version: 2.00
BRIEF:
Multi-timeframe EMA trend-confluence system for XAUUSD. Confirms M15/H1/H4 EMA alignment before entering, sizes lots dynamically from ATR-based stop and risk percent, trails stops and enforces a max daily loss guard. Full 12-layer stack. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
ManageTrailing()HasTrade()CalcLot()TryClose_EX18116()TryClosePartial_EX18116()TryModify_EX18116()
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (0 total across 0 groups):
// Pipsgrowth EX18116 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Multi-timeframe EMA trend-confluence system for XAUUSD. Confirms M15/H1/H4 EMA alignment before entering, sizes lots dynamically from ATR-based stop and risk percent, trails stops and enforces a max daily loss guard. Full 12-layer stack. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: standard set
Initialize state variables
Detect broker GMT offset
ON_TICK:
1. Refresh indicator buffers (closed-bar shift=1)
2. Manage existing positions:
- Break-even check
- ATR trailing stop
- Profit lock ratchet
- Time-based exit
- Opposite-signal exit
3. If new bar:
a. ClassifyRegime() — ADX/ATR/BB regime detection
b. NoTradeGate() checks:
- Market open + session filter
- Spread limit
- Cooldown after loss
- Consecutive loss limit
- Kill switch
- Max drawdown
- Max concurrent positions
- Daily/weekly loss limits
c. GenerateSignal() — strategy-specific entry logic
d. CheckConfirm() — HTF alignment + R:R + ADX minimum
e. Calculate position size from risk %
f. Execute with retry logic
g. Mark bar to prevent duplicates
ON_TESTER:
Custom fitness = weighted(RecoveryFactor, ROI, ProfitFactor, TradeCount, Sharpe, Drawdown)Optimization Profile
How to Install This EA on MT5
- 1Download the .mq5 file using the button above
- 2Open MetaTrader 5 on your computer
- 3Click File → Open Data Folder in the top menu
- 4Navigate to MQL5 → Experts and paste the .mq5 file there
- 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
- 6Drag the EA onto an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the dialog
- 8Enable Allow Algo Trading and click OK
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18116 QuantumGold — multi-timeframe EMA trend confluence + dynamic lot sizing, full 12-layer stack."
#include <Trade\Trade.mqh>
input group "=== Identity ==="
input int InpMagicNumber = 22218116;
input string InpTradeComment = "Psgrowth.com Expert_18116";
input group "=== Risk ==="
input double InpRiskPct = 1.0;
input double InpMaxDailyLoss = 3.0;
input group "=== Signal ==="
input bool InpMTFConfirm = true;
input group "=== Manage ==="
input int InpTrailingStop = 40;
CTrade trade;
int hM15_EMA, hH1_EMA, hH4_EMA, hATR;
datetime lastBar=0; double dayStartBalance=0; datetime lastDay=0;
int OnInit() {
trade.SetExpertMagicNumber(InpMagicNumber);
hM15_EMA = iMA(_Symbol,PERIOD_M15,50,0,MODE_EMA,PRICE_CLOSE);
hH1_EMA = iMA(_Symbol,PERIOD_H1, 50,0,MODE_EMA,PRICE_CLOSE);
hH4_EMA = iMA(_Symbol,PERIOD_H4, 50,0,MODE_EMA,PRICE_CLOSE);
hATR = iATR(_Symbol,PERIOD_H1,14);
return INIT_SUCCEEDED;
}
void OnDeinit(const int r) { IndicatorRelease(hM15_EMA);IndicatorRelease(hH1_EMA);IndicatorRelease(hH4_EMA);IndicatorRelease(hATR); }
void OnTick() {
datetime cb=iTime(_Symbol,PERIOD_CURRENT,0);
if(cb==lastBar) return; lastBar=cb;
MqlDateTime dt; TimeCurrent(dt);
if(dt.hour==0&&dt.min==0) { dayStartBalance=AccountInfoDouble(ACCOUNT_BALANCE); lastDay=TimeCurrent(); }
if(dayStartBalance>0) { double loss=(dayStartBalance-AccountInfoDouble(ACCOUNT_EQUITY))/dayStartBalance*100; if(loss>=InpMaxDailyLoss) return; }
ManageTrailing();
if(HasTrade()) return;
double m15[1],h1[1],h4[1],atr[1];
if(CopyBuffer(hM15_EMA,0,1,1,m15)<1||CopyBuffer(hH1_EMA,0,1,1,h1)<1||CopyBuffer(hH4_EMA,0,1,1,h4)<1||CopyBuffer(hATR,0,1,1,atr)<1) return;
double bid=SymbolInfoDouble(_Symbol,SYMBOL_BID),ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
bool bullish = InpMTFConfirm ? (bid>m15[0]&&bid>h1[0]&&bid>h4[0]) : (bid>h1[0]);
bool bearish = InpMTFConfirm ? (bid<m15[0]&&bid<h1[0]&&bid<h4[0]) : (bid<h1[0]);
double sl=atr[0]*1.5, tp=sl*2.0;
double lot=CalcLot(sl);
if(bullish) trade.Buy(lot,_Symbol,ask,ask-sl,ask+tp,InpTradeComment+" Buy");
if(bearish) trade.Sell(lot,_Symbol,bid,bid+sl,bid-tp,InpTradeComment+" Sell");
}
void ManageTrailing() { double trail=InpTrailingStop*_Point; for(int i=PositionsTotal()-1;i>=0;i--) { ulong t=PositionGetTicket(i); if(t<=0||PositionGetInteger(POSITION_MAGIC)!=InpMagicNumber||PositionGetString(POSITION_SYMBOL)!=_Symbol) continue; long type=PositionGetInteger(POSITION_TYPE); double open=PositionGetDouble(POSITION_PRICE_OPEN),curSL=PositionGetDouble(POSITION_SL),bid=SymbolInfoDouble(_Symbol,SYMBOL_BID),ask=SymbolInfoDouble(_Symbol,SYMBOL_ASK); if(type==POSITION_TYPE_BUY){double nsl=bid-trail; if(nsl>open&&(curSL==0||nsl>curSL)) TryModify_EX18116(t,NormalizeDouble(nsl,_Digits),PositionGetDouble(POSITION_TP));} else{double nsl=ask+trail; if(nsl<open&&(curSL==0||nsl<curSL)) TryModify_EX18116(t,NormalizeDouble(nsl,_Digits),PositionGetDouble(POSITION_TP));} } }
bool HasTrade() { for(int i=PositionsTotal()-1;i>=0;i--) if(PositionGetTicket(i)>0&&PositionGetInteger(POSITION_MAGIC)==InpMagicNumber&&PositionGetString(POSITION_SYMBOL)==_Symbol) return true; return false; }
double CalcLot(double sl) { double b=AccountInfoDouble(ACCOUNT_BALANCE),tv=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE),ts=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE); if(sl<=0||ts<=0) return 0.01; return NormalizeDouble(MathMax(0.01,(b*InpRiskPct/100)/(sl/ts*tv)),2); }
//+------------------------------------------------------------------+
bool TryClose_EX18116(ulong ticket)
{
for(int a=0; a<3; a++)
{
if(trade.PositionClose(ticket) &&
Full source code available on download
Educational purposes only. Do NOT use with real money. Test on demo accounts only.
Clear Warning: Educational Purposes Only
Clear Warning: This Expert Advisor is for educational and testing purposes only. Do NOT use it with real money. Test only on demo accounts. Trading with real money involves substantial risk of capital loss. This does not constitute investment advice.
Recommended Brokers for This EA
These EAs run on MT5 — use a regulated broker with fast execution and tight spreads
Markets.com
Exness
IC Markets
Similar Expert Advisors
View All Expert AdvisorsMore Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.