Pipsgrowth EX18089 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18089 Gold EMA SuperTrend — EMA crossover + SuperTrend gold scalper, full 12-layer stack.
Overview
EX18089 is a gold-targeted trend-following scalper that requires two independent conditions to agree before any position is opened: a 9-period exponential moving average crossing a 21-period EMA on the previous closed M5 bar, and a manual SuperTrend readout (period 10, multiplier 3.0) pointing in the same direction. The two-condition gate means trend-aligned crosses only — a fresh crossover against the prevailing SuperTrend direction is rejected, and a SuperTrend flip without a fresh EMA cross produces no entry. The result is a low-frequency, high-conviction signal that should not be expected to fire every bar.
The SuperTrend calculation is implemented by hand in CalculateSuperTrend() rather than via iCustom or a built-in handle. Three buffers are pulled per call — highs, lows, closes for HL2, and ATR(10) for band width — and the bands are walked through a classic ratchet: the upper band stays at the maximum of the previous upper band and the new basic upper, the lower band stays at the minimum of the previous lower band and the new basic lower, and the direction (superTrendDirection, stored as +1 or -1) flips only when the prior close breaches one of the bands. Because the ratchet relies on state from the previous bar, the calculation is intentionally restricted to new-bar ticks: OnTick() checks IsNewBar() and only calls RefreshIndicators() and CalculateSuperTrend() when the bar changes. Running the ratchet on every tick would corrupt the recursion — the previous band state is held in static double prevUpper / prevLower and static int prevDir.
The initial stop loss and take profit are both ATR(10)-scaled at the moment of entry. OpenPosition() reads currentATR (refreshed on the new bar) and applies StopLossATRMult = 2 and TakeProfitATRMult = 4, producing a 1:2 risk-to-reward per position by default. A buy at the ask is submitted with SL = ask − 2×ATR and TP = ask + 4×ATR; a sell mirrors. The same ATR value drives the SuperTrend band width, the bracket distances, and the trailing distance, so all three scales move together with volatility — a regime shift in either direction adjusts every layer of the system coherently.
Pyramiding is the strictest part of the design. The default MaxPyramidLevels = 5 allows up to 5 same-direction positions on the same magic, but the gate that has to clear before each new add is unusually tight. First, AllPositionsSecured(SecureProfitPoints = 200) walks every existing same-magic position and confirms that the current stop loss is sitting at least 200 points beyond the open price in the favorable direction — that is, every position already has a SL locked into profit by 20 pips, and no position is still running on its original ATR×2 SL. Second, CheckPyramidOpportunity() requires the most recently opened same-magic position to be in profit by at least MinProfitForAdd = 30 pips. Only when both checks pass does the EA add a 5th level. The size of each pyramid level is GetBaseLot() * PyramidSizeMultiplier, where PyramidSizeMultiplier = 1.0 by default, so all five levels are typically the same size. A daily MaxDrawdownPercent = 5.0 safety sits above all of this as a final backstop.
Trailing runs on every tick from ManageTrailingStops(). The trail distance is currentATR * 1.5 from the current price, and the SL is only ever moved in the favorable direction — the function is a one-way ratchet with no tightening rule and no breakeven step. The TP that was set at entry is never modified by the trailing function. Positions close either at the original 4×ATR target, on a reverse EMA cross (which calls CloseAllPositions() and clears the basket regardless of the pyramid count), or on a server-side stop hit. There is no partial-close logic, no break-even ratchet, and no time-based exit in the code.
Risk sizing uses the proper tick-value formula, not a rough approximation. GetBaseLot() reads SYMBOL_TRADE_TICK_SIZE and SYMBOL_TRADE_TICK_VALUE from the symbol, computes the per-lot loss at the ATR×2 SL distance, and divides the dollar risk (1% of balance) by that loss to get the lot size. The result is floored to the symbol's SYMBOL_VOLUME_STEP and clamped to SYMBOL_VOLUME_MIN. With UseMoneyManagement = false, the lot reverts to FixedLotSize = 0.01. The spread filter is a single line in OpenPosition(): it converts the current spread in points to pips via GetPipSize() and rejects the entry if it exceeds MaxSpreadPips = 3.0 — appropriate for gold where spreads can run higher than FX majors.
There is no OnTester, no news filter, no time-of-day session filter, and no information panel in the chart. The EA will trade through Asian, London, and New York sessions equally, and there is no kill-switch for high-impact news. Three-retry wrappers (TryClose_EX18089, TryClosePartial_EX18089, TryModify_EX18089) handle REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED responses with 200 ms or 100 ms sleeps before giving up. Filling is set to FOK in OnInit(). With a $100 starting balance, a 1% risk per position, and 5 pyramid levels all triggered on 30-pip profits, the EA assumes a minimum of 150 pips of favorable travel on gold to fully load the pyramid — a tighter or more cautious broker margin may not survive a single adverse M5 bar. Backtesting should be done with Every tick based on real ticks to capture the new-bar gating accurately; the bar-driven SuperTrend state in particular cannot be reproduced on Open prices only mode.
Strategy Deep Dive
The EA refreshes its 3 indicator handles — EMA(9), EMA(21), and ATR(10) — only on a new M5 bar, a deliberate choice to preserve the SuperTrend recursion state across ticks. The static double prevUpper, prevLower, and static int prevDir variables inside CalculateSuperTrend() must carry the ratchet logic from bar to bar; running the recalculation on every tick would corrupt the recursion. Entry requires two simultaneous conditions: the EMA cross to have occurred on the closed bar AND the SuperTrend direction to agree, with the 3-pip spread filter running as a final gate inside OpenPosition(). The pyramid gate is the strictest in the design — AllPositionsSecured(200) confirms every existing same-magic position has its SL moved to at least 200 points into profit, then CheckPyramidOpportunity() requires the most recent position to be 30 pips in profit, before a 5th level can be added. Trailing runs every tick at 1.5× ATR(10), one-way only, and the daily 5% drawdown safety sits in MaxDrawdownPercent as the final backstop. There is no news filter, no session filter, no time-stop, and no OnTester — the EA trades any M5 bar the cross and trend agree on, 24/5.
Long entries require fast EMA(9) crossing above slow EMA(21) on the previous closed M5 bar AND SuperTrend direction = +1 (uptrend, period 10, multiplier 3.0). Short entries mirror with the conditions flipped. The two-filter gate is strict — a crossover without trend agreement, or a trend without a fresh cross, produces no signal. The 3-pip spread filter runs inside OpenPosition() and blocks entries when gold spread exceeds the threshold.
A reverse EMA cross on the closed bar calls CloseAllPositions() and clears the entire basket, including all 5 pyramid levels. The trailing stop ratchets the SL to price ± 1.5× ATR(10) every tick once price has moved more than 1.5× ATR past open in the favorable direction, never loosening. Positions also exit at the original 4×ATR target or at a server-side stop hit.
Initial stop loss is ATR(10) × 2 from entry, computed at open time and submitted with the order. ManageTrailingStops() ratchets SL to price −/+ 1.5× ATR(10) every tick once price moves more than 1.5× ATR past open — a one-way ratchet that never loosens and never modifies the TP. A daily 5% drawdown safety cap sits above this as a final backstop.
Initial take profit is ATR(10) × 4 from entry, giving a 1:2 risk-to-reward per position. TP is never modified by the trailing function — it is set once at open and only moves via a server-side fill or an explicit reverse-signal basket close. Each pyramid level carries its own ATR(10) × 4 TP, set when that level opens.
Minimum recommended balance is $100, in line with the EA's 1% risk-per-trade default, though gold's 1:2 R:R per position and 5-level pyramid mean $300–$500 gives the stack enough headroom to actually load the pyramid on a single trend. Best on XAUUSD M5 with a low-spread gold broker (ECN/RAW with sub-$0.30 typical gold spread) — the 3-pip spread filter is gold-friendly but will still block entries during news spikes. Filling must be FOK since the EA hard-codes SetTypeFilling(ORDER_FILLING_FOK) in OnInit(). No session filter is applied, so the EA trades through London, New York, and Asian sessions equally — expect more false crosses in low-volume Asian hours and prefer a wider stop in that window.
Strategy Logic
Pipsgrowth EX18089 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218089
Version: 2.00
BRIEF:
Gold scalper using EMA crossover entries filtered by SuperTrend, with ATR-based SL/TP, safe pyramiding and trailing. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
CalculateSuperTrend()OpenPosition()GetBaseLot()AllPositionsSecured()CheckPyramidOpportunity()ManageTrailingStops()CloseAllPositions()IsReverseSignal()CountPositions()IsNewBar()RefreshIndicators()GetPipSize()- ...and 3 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (10 total across 4 groups):
- [=== Risk Management ===]
RiskPercent=1.0// Risk % per trade - [=== Risk Management ===]
MaxDrawdownPercent=5.0// Daily Max Drawdown % (Safety) - [=== Trade Settings ===]
StopLossATRMult= 2 // Initial SL =ATR* Mult - [=== Trade Settings ===]
TakeProfitATRMult= 4 // TP =ATR* Mult - [=== Pyramiding Settings ===]
MaxPyramidLevels= 5 // aggressive pyramiding for gold - [=== Pyramiding Settings ===]
MinProfitForAdd= 30 // Pips profit before adding - [=== Pyramiding Settings ===]
SecureProfitPoints= 200 //Points(not pips) profit SL must be secured by (20 pips) - [=== Pyramiding Settings ===]
MinEntryDistance= 40 // Pips distance between entries - [=== Pyramiding Settings ===]
PyramidSizeMultiplier=1.0// Add same size or scale down - [=== Filters ===]
MaxSpreadPips=3.0// Gold spread can be higher
// Pipsgrowth EX18089 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Gold scalper using EMA crossover entries filtered by SuperTrend, with ATR-based SL/TP, safe pyramiding and trailing. 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
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| RiskPercent | 1.0 | Risk % per trade |
| MaxDrawdownPercent | 5.0 | Daily Max Drawdown % (Safety) |
| StopLossATRMult | 2 | Initial SL = ATR * Mult |
| TakeProfitATRMult | 4 | TP = ATR * Mult |
| MaxPyramidLevels | 5 | aggressive pyramiding for gold |
| MinProfitForAdd | 30 | Pips profit before adding |
| SecureProfitPoints | 200 | Points (not pips) profit SL must be secured by (20 pips) |
| MinEntryDistance | 40 | Pips distance between entries |
| PyramidSizeMultiplier | 1.0 | Add same size or scale down |
| MaxSpreadPips | 3.0 | Gold spread can be higher |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18089 Gold EMA SuperTrend — EMA crossover + SuperTrend gold scalper, full 12-layer stack."
#include <Trade\Trade.mqh>
input group "=== Identity ==="
input string InpTradeComment = "Psgrowth.com Expert_18089";
input group "=== Risk Management ==="
input bool UseMoneyManagement = true;
input double RiskPercent = 1.0; // Risk % per trade
input double FixedLotSize = 0.01;
input double MaxDrawdownPercent = 5.0; // Daily Max Drawdown % (Safety)
input group "=== Strategy Settings ==="
input int FastEMAPeriod = 9;
input int SlowEMAPeriod = 21;
input ENUM_MA_METHOD MAMethod = MODE_EMA;
input int SuperTrendPeriod = 10;
input double SuperTrendMulti = 3.0;
input group "=== Trade Settings ==="
input int StopLossATRMult = 2; // Initial SL = ATR * Mult
input int TakeProfitATRMult = 4; // TP = ATR * Mult
input int Slippage = 5;
input int MagicNumber = 22218089;
input group "=== Pyramiding Settings ==="
input bool UsePyramiding = true;
input int MaxPyramidLevels = 5; // aggressive pyramiding for gold
input int MinProfitForAdd = 30; // Pips profit before adding
input int SecureProfitPoints = 200; // Points (not pips) profit SL must be secured by (20 pips)
input int MinEntryDistance = 40; // Pips distance between entries
input double PyramidSizeMultiplier = 1.0; // Add same size or scale down
input group "=== Filters ==="
input bool UseSpreadFilter = true;
input double MaxSpreadPips = 3.0; // Gold spread can be higher
CTrade trade;
int handleFastMA, handleSlowMA, handleATR;
double currentATR;
double superTrendUp = 0, superTrendDown = 0;
int superTrendDirection = 0; // 1 = Up, -1 = Down
// Global buffers for SuperTrend calculation
double atrBuffer[];
double highBuffer[], lowBuffer[], closeBuffer[];
int OnInit()
{
handleFastMA = iMA(_Symbol, _Period, FastEMAPeriod, 0, MAMethod, PRICE_CLOSE);
handleSlowMA = iMA(_Symbol, _Period, SlowEMAPeriod, 0, MAMethod, PRICE_CLOSE);
handleATR = iATR(_Symbol, _Period, SuperTrendPeriod); // Use ST period for ATR
if(handleFastMA == INVALID_HANDLE || handleSlowMA == INVALID_HANDLE || handleATR == INVALID_HANDLE)
return(INIT_FAILED);
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.