Pipsgrowth EX18011 TrendFollow
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX18011 TrendStackingEA — 4-vote trend consensus, regime gate, capital cap, full 12-layer stack.
Overview
Pipsgrowth EX18011 TrendStackingEA is a 4-vote trend consensus engine that fires only when enough independent momentum indicators point the same way on a closed bar. The default voting threshold is 3 out of 4 possible bullish or bearish votes (InpSignalVotes = 3). The four votes come from: (1) a triple-EMA stack (EMA-21 above EMA-50 above EMA-200 for a buy vote, inverted for sell), (2) MACD histogram direction (histogram above zero and rising, or below zero and falling), (3) RSI-14 sitting on the bullish side of the InpRSIBullZone / InpRSIBearZone thresholds (52/48 by default), and (4) ADX-14 with DI+ above DI- (or the reverse). All four sub-signals look at the last completed bar, never the live one, so the EA never re-paints.
The signal is then filtered by a 6-state market regime classifier. DetectRegime() reads ADX, a 100-bar ATR percentile rank, and a 50-bar Bollinger Bands width ratio. Strong trend triggers above ADX 30, weak trend above ADX 20, compress when ATR percentile is below 30% and BB width is below 0.75x its 50-bar mean, expand when ATR percentile is above 70% or BB width exceeds 1.30x its mean, and breakout when a single bar moves more than 10% relative to the prior close. Entries are blocked in REG_RANGE and REG_COMPRESS; they are allowed in the other four states. This is the gate that prevents the EA from buying flat chop and from chasing quiet markets.
Confirmation requires three things beyond the trend vote. First, the H1 EMA-50 must agree with the trade direction (price must close above it for buys, below it for sells) when InpRequireHTF = true. Second, the bar timestamp must fall inside the 07:00 to 20:00 server-time window and outside weekends. Third, the live spread must be below InpMaxSpreadPts = 50 points relative to a 100-tick rolling average, with a 3x ceiling relative to the recent average. There is also a hard news window block at 12:30 server time ±30 minutes that pauses entries around the US session open.
Risk is sized off g_effCapital, which is min(InpCapitalCapAmount, equity) if a capital cap is set, otherwise full equity, minus today's realized PnL. The 0.5% risk-per-trade default (InpRiskPercent = 0.5) is applied to that effective capital and divided by per-lot risk at the stop distance. A InpCapitalCapFloor = 50 floor blocks any new entries below $50 effective capital. Daily loss is capped at 3% of effective capital and weekly loss at 6%. After 3 consecutive losses the EA goes into a cooldown for InpCooldownLosses bars. Maximum concurrent positions on the same symbol-magic pair is 1 by default, which keeps the strategy single-exposure per symbol.
Position management has three ratchets, all of them opt-in via the EXIT/MANAGE group. Once profit reaches 1R, the break-even function moves the stop to entry plus 5 pips (DEF_BE_OFFSET_PIPS = 5.0) on a one-shot basis. At the same 1R trigger, a partial close of 50% of the position volume fires once per ticket. After that, an ATR trailing stop kicks in at 2.5x ATR (DEF_TRAIL_ATR_MULT = 2.5) and only ratchets forward in 5-pip steps, so the broker's stop-level constraints are not violated. Take profit is set at 2.0R from entry (DEF_TP_RR = 2.0) and is never moved. A minimum R/R of 1.2 (DEF_MIN_RR = 1.2) is enforced in the signal layer so that the EA only takes trades where the projected reward at the ATR stop exceeds the minimum ratio.
Pyramiding is wired in but disabled by default (InpPyramidOn = false). When enabled, the EA may add up to 3 positions (DEF_PYRAMID_MAX = 3) on the same symbol-magic pair, but only if every existing position is in profit and price has moved at least 1.5x ATR beyond the most recent entry. A per-bar duplicate-entry guard in CanEnterNewBar() plus MarkEntered() ensures only one new position opens per signal bar.
Operational defaults match the rest of the family. InpDryRun = true makes the EA log intended orders to the journal instead of sending them; this is the safest way to verify the configuration on a new symbol. The InpKillSwitch master switch short-circuits all entries if flipped on. Order sends go through OpenTrade() with a 2-attempt loop and 500ms backoff on requote/price-changed/time-out. Modifications and partials go through TryModify_EX18011, TryClosePartial_EX18011, and TryClose_EX18011, each of which retries up to 3 times with 200ms or 100ms backoff depending on the retcode.
Backtesting in the MT5 Strategy Tester is biased by a custom OnTester() fitness function. It returns (netProfit * profitFactor) / (1 + relativeDrawdownPercent), floored at 30 trades so that short sample periods do not produce optimisable scores. The expected behaviour in a walk-forward: a 6-state regime filter that cuts about 40% of trend signals during flat periods, a 4-vote consensus that further cuts the false-positive rate, and a 1:2 risk-reward with a 50% partial and a trailing stop that lets runners run when the regime stays trending.
In live deployment the EA shows the same behaviour as the source: conservative entry frequency (often only 1-2 trades per session on a 5-minute chart on XAUUSD), strict risk caps, and visible regime transitions in the journal. The minimum recommended balance is $100, but the effective capital model means that a $50 floor and a 0.5% risk per trade keep drawdown bounded even on small accounts. Run the EA on a 5-minute or 30-minute chart (default InpSignalTF = 4 is M30), with an ECN or low-spread broker, and disable InpDryRun only after the live configuration has been verified in the Strategy Tester.
Strategy Deep Dive
Each tick the EA refreshes the symbol and tracks today's and this week's realized PnL, then iterates over open positions to apply break-even, 50% partial, and the ATR trail. On a new bar of the configured signal timeframe it runs DetectRegime() to classify the market into one of six states, runs NoTradeBlock() against the capital floor, cooldown, daily/weekly loss limits, terminal trade permission, and the 12:30 news window, then collects four trend votes in TrendSignal() (EMA stack, MACD histogram, RSI side, ADX/DI). If at least InpSignalVotes votes agree and ConfirmOK() passes the H1-EMA, session, and spread checks, the trade is sized off the effective capital and sent via OpenTrade(). The full flow is logged on the first bar of every block, so regime transitions and confirm failures are visible in the journal without needing the chart.
EX18011 fires a long or short entry when at least 3 of 4 trend votes agree on a closed bar: EMA(21) > EMA(50) > EMA(200) stack side, MACD histogram direction, RSI(14) vs InpRSIBullZone/InpRSIBearZone, and ADX(14) DI+ vs DI-. Confirmation requires the H1 EMA(50) agreement, the bar time to fall inside 07:00-20:00 server time on a weekday, spread below 50 points relative to a 100-tick rolling average, and a regime that is not RANGE or COMPRESS. The minimum projected R/R must clear 1.2.
Exit is layered: take profit sits at 2R from entry and is never moved. At 1R profit, break-even moves the stop to entry +5 pips and a 50% partial close fires once per ticket. After that an ATR trailing stop at 2.5x ATR with 5-pip steps takes over. Pyramiding (default off) can add up to 3 positions when every existing position is in profit and price has moved at least 1.5x ATR beyond the last entry.
Initial stop is 2.0x ATR(14) on the signal timeframe, with a StopsLevelPrice floor to satisfy the broker's minimum stop distance, and a PipsToPrice(50) fallback if ATR is unavailable. The break-even function then moves the stop to entry +5 pips once profit reaches 1R on a one-shot basis, and the ATR trail (2.5x ATR, 5-pip steps) ratchets the stop forward for the remainder of the trade.
Take profit is set at 2.0x the initial risk distance (1:2 R/R) and never moved, so the projected reward is at least twice the initial stop. A minimum R/R of 1.2 is enforced before the order is sent, and the partial close at 1R secures half the position before the trailing stop takes over.
Best deployed on XAUUSD and FX majors (EURUSD, GBPUSD, USDJPY) on a 5-minute to 1-hour chart with the default M30 signal timeframe, on an ECN or low-spread broker where the 50-point spread cap and the 3x rolling-average ceiling are not constantly violated. Minimum recommended balance is $100, with a $50 effective-capital floor baked into the EA; the 0.5% risk-per-trade default works for prop-firm accounts but should be lowered to 0.25% for accounts below $500. Run it on a weekday between 07:00 and 20:00 server time, and keep InpDryRun = true for the first 24-48 hours of any new symbol.
Strategy Logic
Pipsgrowth EX18011 TrendFollow — Strategy Logic Analysis (from .mq5 source)
Family: TrendFollow
Magic: 22218011
Version: 2.00
BRIEF:
ADX/ATR-pct/BB-width regime gate -> 4-vote trend-stack signal (EMA-stack side + MACD hist + RSI side + ADX-DI) on the last CLOSED bar, confirmed by HTF-EMA(50), min R/R, session & spread. In-trade: BE @R, 50% partial, ATR trail, regime exit. Pyramid after profit, default OFF. Capital-allocation-cap is applied to every risk dollar computation. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
ADXATRBB- Fast
- Slow
- Trnd
RSIMACDHTF
KEY FUNCTIONS:
NormPrice()NormVol()PipsToPrice()StopsLevelPrice()InSession()EffectiveCapital()TodayRealized()TrackRealizedStamps()WeekRealized()CountOpenThis()BufferOK()RegimeAllowsEntry()- ...and 19 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (25 total across 8 groups):
- [===
IDENTITY===]InpMagic=22218011// Magic number (222+expert id) - [===
IDENTITY===]InpComment= "Psgrowth.com Expert_18011" // Trade comment - [===
IDENTITY===]InpSignalTF= 4 //Timeframe(1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Signal timeframe - [===
IDENTITY===]InpSignalVotes= 3 // Min trend votes to fire (1..4) - [===
RISK&SIZING===]InpRiskPercent=0.5// Risk per trade (%) of effective capital - [===
RISK&SIZING===]InpDailyLossLimit=3.0// Max daily loss (%) of effective capital - [===
RISK&SIZING===]InpWeeklyLossLimit=6.0// Max weekly loss (%) of effective capital - [===
RISK&SIZING===]InpMaxConcurrent= 1 // Max concurrent positions (this symbol+magic) - [===
RISK&SIZING===]InpCooldownLosses= 3 // Cooldown after N consecutive losses (bars) - [===
RISK&SIZING===]InpSlippagePts= 30 // Order slippage (points) - [===
RISK&SIZING===]InpUseATRSL=true//ATR-basedSL(else pips) - [===
CAPITAL CAP===]InpCapitalCapAmount=0.0// Cap amount (real-money equity $) - [===
CAPITAL CAP===]InpCapitalCapFloor=50.0// Floor: block new entries below - [===
SIGNAL===]InpRSIBullZone=52.0//RSIbullish side threshold - [===
SIGNAL===]InpRSIBearZone=48.0//RSIbearish side threshold - [===
SIGNAL===]InpADXMin=20.0// MinADXto count vote - [===
CONFIRM===]InpRequireHTF=true// RequireHTF-EMAagreement - [===
CONFIRM===]InpMaxSpreadPts=50.0// Max spread (points) - [===
CONFIRM===]InpUseSession=true// Use session filter - [===
EXIT/MANAGE===]InpUseBreakEven=true// Use break-even at R - [===
EXIT/MANAGE===]InpUsePartial=true// 50% partial atTP1 - [===
EXIT/MANAGE===]InpUseATRTrail=true//ATRtrailing - [===
PYRAMID===]InpPyramidOn=false// Pyramid after profit (defaultOFF) - [===
OPS===]InpDryRun=true// Dry-run (no live orders) - [===
OPS===]InpKillSwitch=false// Master kill switch
// Pipsgrowth EX18011 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// ADX/ATR-pct/BB-width regime gate -> 4-vote trend-stack signal (EMA-stack side + MACD hist + RSI side + ADX-DI) on the last CLOSED bar, confirmed by HTF-EMA(50), min R/R, session & spread. In-trade: BE @R, 50% partial, ATR trail, regime exit. Pyramid after profit, default OFF. Capital-allocation-cap is applied to every risk dollar computation. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: ADX, ATR, BB, Fast, Slow, Trnd, RSI, MACD, HTF
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 |
|---|---|---|
| InpMagic | 22218011 | Magic number (222+expert id) |
| InpComment | "Psgrowth.com Expert_18011" | Trade comment |
| InpSignalTF | 4 | Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Signal timeframe |
| InpSignalVotes | 3 | Min trend votes to fire (1..4) |
| InpRiskPercent | 0.5 | Risk per trade (%) of effective capital |
| InpDailyLossLimit | 3.0 | Max daily loss (%) of effective capital |
| InpWeeklyLossLimit | 6.0 | Max weekly loss (%) of effective capital |
| InpMaxConcurrent | 1 | Max concurrent positions (this symbol+magic) |
| InpCooldownLosses | 3 | Cooldown after N consecutive losses (bars) |
| InpSlippagePts | 30 | Order slippage (points) |
| InpUseATRSL | true | ATR-based SL (else pips) |
| InpCapitalCapAmount | 0.0 | Cap amount (real-money equity $) |
| InpCapitalCapFloor | 50.0 | Floor: block new entries below |
| InpRSIBullZone | 52.0 | RSI bullish side threshold |
| InpRSIBearZone | 48.0 | RSI bearish side threshold |
| InpADXMin | 20.0 | Min ADX to count vote |
| InpRequireHTF | true | Require HTF-EMA agreement |
| InpMaxSpreadPts | 50.0 | Max spread (points) |
| InpUseSession | true | Use session filter |
| InpUseBreakEven | true | Use break-even at R |
| InpUsePartial | true | 50% partial at TP1 |
| InpUseATRTrail | true | ATR trailing |
| InpPyramidOn | false | Pyramid after profit (default OFF) |
| InpDryRun | true | Dry-run (no live orders) |
| InpKillSwitch | false | Master kill switch |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX18011 TrendStackingEA — 4-vote trend consensus, regime gate, capital cap, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Trade\DealInfo.mqh>
//============================ CONSTANTS ============================
#define DEF_FAST_MA 21
#define DEF_SLOW_MA 50
#define DEF_TREND_MA 200
#define DEF_RSI_PERIOD 14
#define DEF_MACD_FAST 12
#define DEF_MACD_SLOW 26
#define DEF_MACD_SIGNAL 9
#define DEF_ADX_PERIOD 14
#define DEF_ATR_PERIOD 14
#define DEF_BB_PERIOD 20
#define DEF_BB_DEV 2.0
#define DEF_ATR_PCT_BARS 100
#define DEF_HTF_TF PERIOD_H1
#define DEF_HTF_EMA_PERIOD 50
#define DEF_REGIME_STRONG_ADX 30.0
#define DEF_REGIME_WEAK_ADX 20.0
#define DEF_REGIME_EXPAND 1.30
#define DEF_REGIME_COMPRESS 0.75
#define DEF_BREAKOUT_RATIO 1.10
#define DEF_ATR_SL_MULT 2.0
#define DEF_TP_RR 2.0
#define DEF_BE_OFFSET_PIPS 5.0
#define DEF_TRAIL_ATR_MULT 2.5
#define DEF_TRAIL_STEP_PIPS 5.0
#define DEF_PARTIAL1_R 1.0
#define DEF_PARTIAL1_PCT 50.0
#define DEF_PYRAMID_SPACING_ATR 1.5
#define DEF_PYRAMID_MAX 3
#define DEF_MIN_RR 1.2
#define DEF_MAX_SPREAD_MULT 3.0
#define DEF_SESSION_START "07:00"
#define DEF_SESSION_END "20:00"
#define DEF_NEWS_BLOCK_MIN 30
#define DEF_SLIP_RETRY_MS 500
#define DEF_PARTIAL_MIN_PCT 30.0
enum ENUM_REGIME
{
REG_STRONG_TREND, // StrongTrend
REG_WEAK_TREND, // WeakTrend
REG_RANGE, // Range
REG_COMPRESS, // Compress
REG_EXPAND, // Expand
REG_BREAKOUT // Breakout
};
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.