P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18109 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1

Pipsgrowth.com EX18109 per0 — EMA/MACD/RSI indicator monitor with robustness optimization, full 12-layer stack.

Overview

Pipsgrowth EX18109 TrendFollow is a pullback-in-trend engine built specifically around MT5's Strategy Tester optimization pipeline. Where most MQL5 EAs treat OnTester as a single number to maximize, EX18109 layers in a multi-period decomposition: it tracks per-month P&L, per-month max-drawdown, and a blown-out flag for each calendar month, then passes (or fails) the test result against a bank of seven hard gates before it ever computes a score. The actual trade logic is a clean five-indicator pullback: two EMAs frame the trend, MACD supplies the momentum-cooling trigger, RSI gates the entry to a neutral band, and ATR sizes both the protective stop and the target. Sessions, spread, and account-level risk limits are then layered on top so a great-looking tester score cannot be undermined by a live account on the wrong side of the sun.

The indicator stack is exactly what the input block declares. EMA(21) and EMA(55), both close-based, give the trend frame. A long is only allowed when the close is above both EMAs and within 15 pips of EMA(21) — the EMA_Pullback_Pips input — a price that has pulled back close enough to re-enter the trend without having fallen out of it. MACD(12,26,9) is checked over a 3-bar lookback window for a main-above-signal-to-main-below-signal flip in longs (or the inverse in shorts). The cross is permitted anywhere within that 3-bar window, not only on bar 1, so a cross that the EA missed on the prior bar can still trigger. RSI(14) is gated to a [40, 60] band for longs; for shorts the band is mirrored as [100-60, 100-40], which is mathematically the same interval — the design is symmetry around the RSI 50 midline. ATR(14) then sizes both the stop at 2.0×ATR and the take-profit at 3.0×ATR, which lands at a 1.5:1 reward-to-risk ratio by default.

The CheckEntrySignals() function is the only path that calls OpenBuy() or OpenSell(), and it explicitly checks the open-position count against MaxPositions (=1) before doing so. There is no pyramiding, no in-EA trailing stop, no break-even ratchet, and no partial close — the ATR stop and target are placed server-side at entry and that is the lifecycle of the trade. The retry helpers TryClose_EX18109, TryClosePartial_EX18109, and TryModify_EX18109 — each loops three times with 100-200 ms sleeps on requote, timeout, price-off, or price-changed retcodes — exist in the source but are never called from OnTick, so they are dead code in the current build. Every entry decision happens once per closed bar inside the IsNewBar guard.

Filters and risk gates run in a fixed order inside OnTick. After the IsNewBar() gate, UpdateBalanceTracking() refreshes daily_starting_balance and peak_balance. TrackPeriodPerformance() then walks the monthly buckets when EnableRobustnessOptimization is on, writing each closed-out month into the period_results[] array. CheckRiskLimits() blocks entries when the day's loss has hit 3.0% (DailyLossLimit) or the drawdown from the all-time peak has hit 15% (MaxDrawdownPercent) — a daily-since-midnight and an all-time HWM brake, not a per-trade stop. GetIndicatorValues() pulls 3 bars of indicator data into the buffers. CheckTimeFilters() applies the session block; CheckVolatilityFilters() applies the ATR band (0.5 to 2.0) and the spread cap (2.5 pips). Only after every gate clears does PrintIndicatorSnapshot() log the EMA/MACD/RSI/ATR values and the entry check run.

Session settings default to Asian 00:00 to 09:00 ON, London 07:00 to 16:00 ON, New York 13:00 to 22:00 OFF. That makes EX18109 an Asia-and-London strategy by default — New York is reserved even though most XAUUSD volatility happens in the New York overlap with London. To switch to a London-NY profile, toggle TradeNewYorkSession=true and TradeAsianSession=false. The session block uses minute-of-day arithmetic with a same-day wrap, so an overnight window (start hour > end hour) is handled cleanly without code changes. ValidateSessionInputs() rejects start or end hours outside 0 to 23, or minutes outside 0 to 59, at OnInit.

The OnTester() function is what makes this EA distinctive inside the PipsGrowth family. When EnableRobustnessOptimization is false, OnTester returns STAT_PROFIT — standard behaviour. When true, the EA re-scores the run: it walks period_results[], fails the run with a return of -1.0 if any month has lost more than MaxPeriodLossPercent=20% (blown out), if the share of losing months exceeds MaxLosingPeriodsRatio=40%, if max drawdown breaches MaxDrawdownThreshold=25%, if the trade count is below 30, if the profit factor is below 1.3, or if total profit is non-positive. Only after all six hard gates pass does the scoring begin: profit factor × ProfitFactorWeight=1000 + consistency bonus (1 − losing_months_ratio) × ConsistencyWeight=500 + drawdown headroom × DrawdownWeight=20 + Sharpe ratio × SharpeWeight=100 + profit-percent × 10. The net effect is that the optimizer is pushed toward smooth equity curves with low drawdown rather than raw profit.

Lot sizing is straightforward 1%-of-balance risk: CalculateLotSize(sl_pips) reads RiskPercent=1.0 and converts the SL distance into a contract count using SYMBOL_TRADE_TICK_VALUE, SYMBOL_TRADE_TICK_SIZE, and the symbol's point. The result is floored to the lot step, clamped to [min_lot, max_lot], and rounded to 2 decimals. The slippage setting TradeDeviation=5 is conservative — on a raw-spread ECN account this gives the broker enough room to fill without rejecting. A failed lot-size calculation (returns 0) aborts the order rather than sending a 0-lot ticket.

For backtesting, the expected behaviour on XAUUSD M5 over multi-year data is a moderate trade count — the strategy needs real pullbacks, so do not expect scalper density — with a distribution of small losers and a smaller number of larger winners. Strategy Tester is exactly the workflow this EA was written for: leave EnableRobustnessOptimization=false for a single-pass backtest, flip it on for an optimization pass, and let the seven-gate scorer pick robust parameter sets over multi-month windows. For live trading, run the defaults on a $100 account. MaxDrawdownPercent=15 and DailyLossLimit=3.0 are the real safety net — the 1% per-trade risk plus the 1-position cap means the worst single-day damage is bounded by both the DD brake and the daily-loss brake. Do not run EX18109 on magic number 22218109 alongside any other PipsGrowth EA on the same account, or the position-count check will see both and refuse new entries.

Strategy Deep Dive

OnTick runs once per closed bar via IsNewBar(): it refreshes the daily/peak balance tracker, walks per-month performance buckets if EnableRobustnessOptimization is on, and runs four sequential gates — risk limits (3% daily loss or 15% peak drawdown), indicator pull, session filter (Asian + London ON by default, New York OFF), and volatility (ATR 0.5 to 2.0 plus spread ≤ 2.5 pips). A long setup needs close > both EMA(21) and EMA(55), MACD main crossed below signal somewhere in the last 3 bars, RSI(14) inside [40, 60], and price within EMA_Pullback_Pips=15 of EMA(21) — the EA is hunting for a momentum-cooling dip back into a still-valid trend. Shorts mirror those conditions. The risk layer computes lot size as 1% of balance per SL distance, rounded to the symbol's lot step, and OnTester() applies a multi-period robustness filter — per-month blow-up cap, losing-month ratio, max drawdown, trade count ≥ 30, profit factor ≥ 1.3, positive net — before any weighted score is added. There is no in-trade management, no pyramid, no trailing — every trade is born and dies by the server-side ATR stop and target.

Entry Signal

Longs trigger when close > EMA(21) and close > EMA(55), price is within EMA_Pullback_Pips=15 of EMA(21), MACD(12,26,9) main has crossed below signal within the last 3 bars, and RSI(14) sits inside the [40, 60] band. Shorts mirror the setup with close < both EMAs, MACD main crossing above signal, and the same RSI range flipped as [100-60, 100-40]. The pattern is a momentum-cooling pullback into a still-intact trend, not a breakout. MaxPositions=1 hard-caps pyramiding to zero.

Exit Signal

Each trade is placed with a fixed ATR-based target, an ATR-based stop, and left to run until either the SL or the TP hits. There is no in-EA trailing stop, no break-even ratchet, and no partial close — the server-side stops are the entire exit path. The retry helpers TryClose_EX18109, TryClosePartial_EX18109, and TryModify_EX18109 are declared in the source but never invoked from OnTick. New entries are gated only by CheckEntrySignals; existing positions are not actively managed by the EA.

Stop Loss

Stop is 2.0×ATR(14) in pips, capped at MaxStopLossPips=150. The SL is placed server-side at entry — no in-trade trailing, no break-even move, no partial close. ATR(14) is sampled from the bar the signal fires on.

Take Profit

Take-profit is 3.0×ATR(14) in pips, uncapped. Combined with the 2.0×ATR stop that gives a 1.5:1 reward-to-risk ratio. No trailing, no partial TP — the position runs to the hard TP or the hard SL.

Best For

Recommended on XAUUSD M5 with at least $100 account balance — the 1% per-trade risk and 1-position cap keep drawdown bounded by the 15% peak-DD and 3% daily-loss brakes. Run with default sessions (Asian + London) on a low-spread ECN account such as Exness or IC Markets; flip TradeNewYorkSession=true and TradeAsianSession=false for a London-NY profile. Best suited to the MT5 Strategy Tester optimization workflow with EnableRobustnessOptimization=true — the multi-period OnTester filter is what distinguishes this EA from a plain pullback script. Do not run alongside other PipsGrowth EAs sharing magic 22218109 on the same account.

Strategy Logic

Pipsgrowth EX18109 TrendFollow — Strategy Logic Analysis (from .mq5 source)

Family: TrendFollow Magic: 22218109 Version: 2.00

BRIEF: Indicator monitor with automated execution combining EMA crossover, MACD, RSI, and ATR-based SL/TP. Includes session filters, volatility filters, daily loss/drawdown limits, and robustness optimization settings for OnTester scoring. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • IsNewBar()
  • GetIndicatorValues()
  • ValidateSessionInputs()
  • IsWithinSession()
  • UpdateBalanceTracking()
  • CheckRiskLimits()
  • CheckEntrySignals()
  • CheckLongEntry()
  • CheckShortEntry()
  • CheckTimeFilters()
  • CheckVolatilityFilters()
  • CalculateLotSize()
  • ...and 7 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (10 total across 1 groups):

  • [=== Optimization Settings ===] EnableRobustnessOptimization = false // Enable Robustness Optimization
  • [=== Optimization Settings ===] MaxPeriodLossPercent = 20.0 // Max Loss Per Period (%) - triggers rejection
  • [=== Optimization Settings ===] MaxLosingPeriodsRatio = 40.0 // Max Losing Periods (%) - e.g., 40 = 40% of periods can lose
  • [=== Optimization Settings ===] MaxDrawdownThreshold = 25.0 // Max Drawdown Threshold (%)
  • [=== Optimization Settings ===] MinimumTrades = 30 // Minimum Trades Required
  • [=== Optimization Settings ===] MinProfitFactor = 1.3 // Minimum Profit Factor
  • [=== Optimization Settings ===] ProfitFactorWeight = 1000.0 // Profit Factor Weight in Score
  • [=== Optimization Settings ===] ConsistencyWeight = 500.0 // Consistency Bonus Weight
  • [=== Optimization Settings ===] DrawdownWeight = 20.0 // Drawdown Bonus Weight (per % below max)
  • [=== Optimization Settings ===] SharpeWeight = 100.0 // Sharpe Ratio Weight
Pseudocode
// Pipsgrowth EX18109 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Indicator monitor with automated execution combining EMA crossover, MACD, RSI, and ATR-based SL/TP. Includes session filters, volatility filters, daily loss/drawdown limits, and robustness optimization settings for OnTester scoring. 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

Optimized Brokers:
ExnessIC Markets
Optimized Symbols:
XAUUSD
Optimized Timeframes:
M5H1

How to Install This EA on MT5

  1. 1Download the .mq5 file using the button above
  2. 2Open MetaTrader 5 on your computer
  3. 3Click File → Open Data Folder in the top menu
  4. 4Navigate to MQL5 → Experts and paste the .mq5 file there
  5. 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
  6. 6Drag the EA onto an H4 or Daily chart for best results
  7. 7Configure EMA periods, ADX threshold, and lot size in the dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
EnableRobustnessOptimizationfalseEnable Robustness Optimization
MaxPeriodLossPercent20.0Max Loss Per Period (%) - triggers rejection
MaxLosingPeriodsRatio40.0Max Losing Periods (%) - e.g., 40 = 40% of periods can lose
MaxDrawdownThreshold25.0Max Drawdown Threshold (%)
MinimumTrades30Minimum Trades Required
MinProfitFactor1.3Minimum Profit Factor
ProfitFactorWeight1000.0Profit Factor Weight in Score
ConsistencyWeight500.0Consistency Bonus Weight
DrawdownWeight20.0Drawdown Bonus Weight (per % below max)
SharpeWeight100.0Sharpe Ratio Weight
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18109.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18109 per0 — EMA/MACD/RSI indicator monitor with robustness optimization, full 12-layer stack."

#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>

input group "=== Moving Average Settings ==="
input int    EMA_Fast_Period  = 21;
input int    EMA_Slow_Period  = 55;

input group "=== MACD Settings ==="
input int    MACD_Fast_EMA    = 12;
input int    MACD_Slow_EMA    = 26;
input int    MACD_Signal_SMA  = 9;

input group "=== RSI Settings ==="
input int    RSI_Period       = 14;
input double RSI_Low          = 40.0;
input double RSI_High         = 60.0;

input group "=== ATR Settings ==="
input int    ATR_Period        = 14;
input double ATR_SL_Multiplier = 2.0;
input double ATR_TP_Multiplier = 3.0;

input group "=== Signal Filters ==="
input double EMA_Pullback_Pips = 15.0;

input group "=== Risk Management ==="
input double RiskPercent      = 1.0;
input double MaxStopLossPips  = 150.0;
input int    MaxPositions     = 1;

input group "=== Trade Settings ==="
input bool   EnableTrading    = true;
input int    TradeDeviation   = 5;
input long   MagicNumber      = 22218109;
input string InpTradeComment  = "Psgrowth.com Expert_18109";

input group "=== Session Filters ==="
input bool   EnableSessionFilter     = true;
input bool   TradeAsianSession       = true;
input int    AsianSessionStartHour   = 0;
input int    AsianSessionStartMinute = 0;
input int    AsianSessionEndHour     = 9;
input int    AsianSessionEndMinute   = 0;
input bool   TradeLondonSession      = true;
input int    LondonSessionStartHour  = 7;
input int    LondonSessionStartMinute= 0;
input int    LondonSessionEndHour    = 16;
input int    LondonSessionEndMinute  = 0;
input bool   TradeNewYorkSession     = false;
input int    NewYorkSessionStartHour = 13;
input int    NewYorkSessionStartMinute = 0;
input int    NewYorkSessionEndHour   = 22;
input int    NewYorkSessionEndMinute = 0;

Full source code available on download

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

Tags:ex18109trendfollowpipsgrowthfreemt5xauusd

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

Community

Sign in to contributeSign In

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

File NamePipsgrowth_com_EX18109.mq5
File Size29.2 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100