P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18071 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18071 QuadTrend XAUUSD 5M — 4xEMA alignment + regime + risk cap, full 12-layer stack.

Overview

Pipsgrowth EX18071 TrendFollow is a MetaTrader 5 Expert Advisor designed for traders who want core signal = perfect stacked alignment of 4 emas (10/20/50/200) on the last closed bar. entries are gated by an adx+atr-pctile+bb-width regime filter, htf trend agreement, session window, spread filter, and a per-magic daily-loss / capital-cap governor. sl/tp are atr-based, sized off the effective capital. in-trade: be, partial tp at tp1, atr trail, regime-change exit, time exit. pyramiding default off. 12 layers: regime, signal, entry, confirm, no-trade, capital cap, risk, sizing, manage, exit, scaling, ontester. The EA operates on XAUUSD at the M5 timeframe, with every line of strategy logic visible in the downloadable .mq5 file.

Pipsgrowth.com EX18071 QuadTrend XAUUSD 5M — 4xEMA alignment + regime + risk cap, full 12-layer stack.

Technical Architecture

The EA is built on a 12-layer architecture: Regime Detection, Signal Generation, Entry Dispatch, Confirmation, No-Trade Gate, Capital Allocation Cap, Risk Management, Position Sizing, Trade Management, Exit Logic, Scaling Gate, and OnTester fitness optimization. The source code defines 26 tunable constants and exposes 23 input parameters across 6 groups. Key indicator handles include standard MT5 indicators. The codebase implements 20 custom functions including NormPrice(), NormLots(), RefreshSym(), StopsLevelPrice(), FreezeLevelPrice() and others.

Risk Management

Position sizing uses a medium risk profile. Default risk is 0.5% of effective capital per trade. Daily loss is capped at 3.0%. Weekly loss limit: 6.0%.

Key risk parameters from source:

  • InpRiskPercent (default: 0.5) — Risk % per trade (of effective capital)
  • InpFixedLot (default: 0.01) — Fallback fixed lot (risk=0 or calc fail)
  • InpDailyLossLimitPct (default: 3.0) — Daily loss limit % (of effective capital)
  • InpWeeklyLossLimitPct (default: 6.0) — Weekly loss limit % (of effective capital)
  • InpCapitalCapAmount (default: 0.0) — Capital cap amount ($ equity, not notional)
  • InpCapitalCapFloor (default: 50.0) — Capital floor ($) - block entries below

Signal Generation Logic

Core signal = perfect stacked alignment of 4 EMAs (10/20/50/200) on the last CLOSED bar. Entries are gated by an ADX+ATR-pctile+BB-width regime filter, HTF trend agreement, session window, spread filter, and a per-magic daily-loss / capital-cap governor. SL/TP are ATR-based, sized off the EFFECTIVE capital. In-trade: BE, partial TP at TP1, ATR trail, regime-change exit, time exit. Pyramiding default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester.

The signal engine is configured via 9 internal constants:

  • ATR_PERIOD = 14 — ATR length for SL/TP/trail
  • ADX_PERIOD = 14 — ADX length for regime
  • BB_PERIOD = 20 — Bollinger length for width regime
  • BB_DEV = 2.0 — Bollinger deviation
  • ATR_PCTILE_LOOKBACK = 100 — bars for ATR percentile
  • BB_PCTILE_LOOKBACK = 100 — bars for BB-width percentile
  • TRAIL_ATR_MULT = 3.0 — ATR trail distance multiplier
  • PYRAMID_ATR_SPACING = 2.0 — ATR spacing between adds
  • ...and 1 more

User-adjustable signal parameters:

  • InpATR_SL_MULT (default: 3) — SL distance = MULT * ATR (price units)
  • InpADX_MinTrend (default: 22.0) — ADX min for StrongTrend entries
  • InpADX_MaxRange (default: 18.0) — ADX below = range/choppy, blocks entries
  • InpUseATRTrail (default: true) — ATR trailing stop

Trade Management

The EA manages positions using these hardcoded rules:

  • PARTIAL_FRAC = 0.5 — close 50% at TP1
  • TP1_R = 1.0 — TP1 = 1R
  • TP2_R = 2.5 — TP2 = final TP multiple of R
  • TRAIL_ATR_MULT = 3.0 — ATR trail distance multiplier
  • TRAIL_START_R = 1.0 — start trailing after this many R
  • MAX_BARS_IN_TRADE = 600 — time-based exit (bars)

User-configurable exit parameters:

  • InpUseBreakEven (default: true) — Move to break-even at BE_TRIGGER_R
  • InpUsePartialTP (default: true) — Partial close PARTIAL_FRAC at TP1
  • InpUseATRTrail (default: true) — ATR trailing stop

No-Trade Gate

The EA blocks new entries when: market is closed, spread exceeds maximum, cooldown is active after losses, consecutive loss limit is reached, kill switch is enabled, or drawdown exceeds the hard threshold.

Session and safety parameters:

  • COOLDOWN_BARS = 6 — cooldown bars after a loss
  • SESSION_START_HOUR = 7 — server-time session start (UTC+? server)
  • SESSION_END_HOUR = 20 — server-time session end
  • NEWS_BLOCK_BARS = 0 — news window bars (0 = disabled)
  • InpMaxSpreadPts (default: 350) — Max spread (points)

Optimized For

  • Pairs: XAUUSD
  • Timeframes: M5
  • Recommended Brokers: Exness, IC Markets
  • Minimum Deposit: $100
  • Risk Level: MEDIUM
  • Magic Number: 22218071
  • Source Code: Pipsgrowth_com_EX18071.mq5 (23 inputs, 26 constants)

Download This MT5 Expert Advisor

This EA provides complete, open-source .mq5 code — no DLLs, no account restrictions, no hidden logic. Read every line of the TrendFollow strategy, modify parameters, and optimize for your broker. Test in the MT5 Strategy Tester before going live.

⚠️ Risk Warning: Trading forex and CFDs involves significant risk. 74-89% of retail investor accounts lose money. This EA is for educational purposes only. Test thoroughly before any live use.

Strategy Deep Dive

Pipsgrowth EX18071 TrendFollow (EX18071) is an open-source MT5 Expert Advisor built for XAUUSD on M5. The strategy runs on 23 configurable input parameters with 20 custom functions in the source code. According to the source code header: Core signal = perfect stacked alignment of 4 EMAs (10/20/50/200) on the last CLOSED bar. Entries are gated by an ADX+ATR-pctile+BB-width regime filter, HTF trend agreement, session window, spread filter, and a per-magic daily-loss / capital-cap governor. SL/TP are ATR-based, sized off the EFFECTIVE capital. In-trade: BE, partial TP at TP1, ATR trail, regime-change exit, time exit. Pyramiding default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester. The EA operates on a 12-layer architecture: regime detection, signal generation, entry dispatch, confirmation, no-trade gate, capital allocation cap, risk management, position sizing, trade management, exit logic, scaling gate, and OnTester fitness optimization. Spread filtering blocks entries when market spread exceeds the configured maximum. Cooldown and consecutive loss limits prevent overtrading after drawdowns. All strategy logic is visible in the downloadable .mq5 source file.

Entry Signal

Entry generated by the InpDailyLossLimitPct when regime classification confirms a trending market. Entries use closed-bar (shift=1) to prevent signal repainting.

Exit Signal

Exit when the opposite EMA crossover fires (trend reversal signal) or when the trailing stop catches the trade after the trend exhausts. No fixed take-profit — the philosophy is to let winners run until momentum dies. The trailing stop is ATR-based and adjusts with each new swing high/low.

Stop Loss

Initial stop placed below the last significant swing low for longs (or above the last swing high for shorts). The stop distance is calculated from ATR — typically 1.5–2× the 14-period ATR on the entry timeframe. Once in profit, the stop trails behind price to lock in gains without cutting the trend short.

Take Profit

No fixed take-profit — the EA uses a trailing stop to capture the full trend movement. The trailing stop uses a chandelier exit — it trails 2–3× ATR behind price. Trend EAs are designed to catch large moves (50–200+ pips) with a few large wins offsetting many small losses.

Best For

Works best on H4 and Daily timeframes with trending conditions. Top pairs: EUR/USD, GBP/USD, USD/JPY, XAU/USD. Medium risk profile with moderate drawdown tolerance. Minimum recommended: $500.

Strategy Logic

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

Family: TrendFollow Magic: 22218071 Version: 2.00

BRIEF: Core signal = perfect stacked alignment of 4 EMAs (10/20/50/200) on the last CLOSED bar. Entries are gated by an ADX+ATR-pctile+BB-width regime filter, HTF trend agreement, session window, spread filter, and a per-magic daily-loss / capital-cap governor. SL/TP are ATR-based, sized off the EFFECTIVE capital. In-trade: BE, partial TP at TP1, ATR trail, regime-change exit, time exit. Pyramiding default OFF. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • NormPrice()
  • NormLots()
  • RefreshSym()
  • StopsLevelPrice()
  • FreezeLevelPrice()
  • HasOpenPosition()
  • CountOpenPositions()
  • EffectiveCapital()
  • MagicPnLDay()
  • MagicPnLWeek()
  • Percentile()
  • CoreSignal()
  • ...and 8 more

INTERNAL CONSTANTS (26 total):

  • ATR_PERIOD = 14 // ATR length for SL/TP/trail
  • ADX_PERIOD = 14 // ADX length for regime
  • BB_PERIOD = 20 // Bollinger length for width regime
  • BB_DEV = 2.0 // Bollinger deviation
  • ATR_PCTILE_LOOKBACK = 100 // bars for ATR percentile
  • BB_PCTILE_LOOKBACK = 100 // bars for BB-width percentile
  • HTF_TF = PERIOD_H1 // higher-timeframe trend agreement
  • BE_TRIGGER_R = 1.0 // move to BE after this many R
  • BE_OFFSET_POINTS = 0 // padding past BE
  • PARTIAL_FRAC = 0.5 // close 50% at TP1
  • TP1_R = 1.0 // TP1 = 1R
  • TP2_R = 2.5 // TP2 = final TP multiple of R
  • TRAIL_ATR_MULT = 3.0 // ATR trail distance multiplier
  • TRAIL_START_R = 1.0 // start trailing after this many R
  • MAX_BARS_IN_TRADE = 600 // time-based exit (bars)
  • ...and 11 more

INPUT PARAMETERS (23 total across 6 groups):

  • [=== Identity ===] InpMagicNumber = 22218071 // Magic number (per-EA isolation)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18071" // Trade comment
  • [=== Identity ===] InpSlippagePoints = 30 // Max slippage (points)
  • [=== Identity ===] InpDryRun = true // Dry-run (signal/log only, NO orders)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk % per trade (of effective capital)
  • [=== Risk & Sizing ===] InpFixedLot = 0.01 // Fallback fixed lot (risk=0 or calc fail)
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit % (of effective capital)
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPct = 6.0 // Weekly loss limit % (of effective capital)
  • [=== Risk & Sizing ===] InpATR_SL_MULT = 3 // SL distance = MULT * ATR (price units)
  • [=== Risk & Sizing ===] InpRR_Min = 1 // Min reward:risk (used to size TP)
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Capital cap amount ($ equity, not notional)
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Capital floor ($) - block entries below
  • [=== Signal (Quad EMA) ===] InpMA1 = 10 // Fast EMA period
  • [=== Signal (Quad EMA) ===] InpMA2 = 20 // EMA period 2
  • [=== Signal (Quad EMA) ===] InpMA3 = 50 // EMA period 3
  • [=== Signal (Quad EMA) ===] InpMA4 = 200 // Slow EMA period
  • [=== Regime / Confirm ===] InpADX_MinTrend = 22.0 // ADX min for StrongTrend entries
  • [=== Regime / Confirm ===] InpADX_MaxRange = 18.0 // ADX below = range/choppy, blocks entries
  • [=== Regime / Confirm ===] InpMaxSpreadPts = 350 // Max spread (points)
  • [=== Manage / Exit ===] InpUseBreakEven = true // Move to break-even at BE_TRIGGER_R
  • [=== Manage / Exit ===] InpUsePartialTP = true // Partial close PARTIAL_FRAC at TP1
  • [=== Manage / Exit ===] InpUseATRTrail = true // ATR trailing stop
  • [=== Manage / Exit ===] InpKillSwitch = false // KILL SWITCH - block all new trades
Pseudocode
// Pipsgrowth EX18071 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Core signal = perfect stacked alignment of 4 EMAs (10/20/50/200) on the last CLOSED bar. Entries are gated by an ADX+ATR-pctile+BB-width regime filter, HTF trend agreement, session window, spread filter, and a per-magic daily-loss / capital-cap governor. SL/TP are ATR-based, sized off the EFFECTIVE capital. In-trade: BE, partial TP at TP1, ATR trail, regime-change exit, time exit. Pyramiding default OFF. 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:
M5

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
InpMagicNumber22218071Magic number (per-EA isolation)
InpTradeComment"Psgrowth.com Expert_18071"Trade comment
InpSlippagePoints30Max slippage (points)
InpDryRuntrueDry-run (signal/log only, NO orders)
InpRiskPercent0.5Risk % per trade (of effective capital)
InpFixedLot0.01Fallback fixed lot (risk=0 or calc fail)
InpDailyLossLimitPct3.0Daily loss limit % (of effective capital)
InpWeeklyLossLimitPct6.0Weekly loss limit % (of effective capital)
InpATR_SL_MULT3SL distance = MULT * ATR (price units)
InpRR_Min1Min reward:risk (used to size TP)
InpCapitalCapAmount0.0Capital cap amount ($ equity, not notional)
InpCapitalCapFloor50.0Capital floor ($) - block entries below
InpMA110Fast EMA period
InpMA220EMA period 2
InpMA350EMA period 3
InpMA4200Slow EMA period
InpADX_MinTrend22.0ADX min for StrongTrend entries
InpADX_MaxRange18.0ADX below = range/choppy, blocks entries
InpMaxSpreadPts350Max spread (points)
InpUseBreakEventrueMove to break-even at BE_TRIGGER_R
InpUsePartialTPtruePartial close PARTIAL_FRAC at TP1
InpUseATRTrailtrueATR trailing stop
InpKillSwitchfalseKILL SWITCH - block all new trades
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18071.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18071 QuadTrend XAUUSD 5M — 4xEMA alignment + regime + risk 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>

CTrade         trade;
CPositionInfo  posInfo;
CSymbolInfo    sym;
CAccountInfo   acc;

//================== TUNABLE CONSTANTS (NOT inputs) =================
#define ATR_PERIOD          14      // ATR length for SL/TP/trail
#define ADX_PERIOD          14      // ADX length for regime
#define BB_PERIOD           20      // Bollinger length for width regime
#define BB_DEV              2.0     // Bollinger deviation
#define ATR_PCTILE_LOOKBACK 100     // bars for ATR percentile
#define BB_PCTILE_LOOKBACK  100     // bars for BB-width percentile
#define HTF_TF              PERIOD_H1   // higher-timeframe trend agreement
#define HTF_EMA_FAST        20
#define HTF_EMA_SLOW        50
#define BE_TRIGGER_R        1.0     // move to BE after this many R
#define BE_OFFSET_POINTS    0      // padding past BE
#define PARTIAL_FRAC        0.5    // close 50% at TP1
#define TP1_R               1.0    // TP1 = 1R
#define TP2_R               2.5    // TP2 = final TP multiple of R
#define TRAIL_ATR_MULT      3.0    // ATR trail distance multiplier
#define TRAIL_START_R       1.0    // start trailing after this many R
#define MAX_BARS_IN_TRADE   600    // time-based exit (bars)
#define PYRAMID_MAX         0      // pyramid levels (0 = OFF)
#define PYRAMID_MIN_R       2.0    // min R profit before next pyramid add
#define PYRAMID_ATR_SPACING 2.0    // ATR spacing between adds
#define COOLDOWN_BARS       6      // cooldown bars after a loss
#define MAX_LOSS_STREAK     3      // stop trading after N consecutive losses
#define SESSION_START_HOUR  7      // server-time session start (UTC+? server)
#define SESSION_END_HOUR    20     // server-time session end
#define NEWS_BLOCK_BARS     0      // news window bars (0 = disabled)
#define SPREAD_ROLL_LOOKBACK 60    // bars for rolling spread average
#define SLOPE_BARS          3      // bars used to confirm EMA slope
#define MAX_OPEN_TRADES     1      // hard cap on concurrent positions for this EA

//================== INPUTS (12-22) =================================
input group "=== Identity ==="
input int      InpMagicNumber       = 22218071;                  // Magic number (per-EA isolation)
input string   InpTradeComment      = "Psgrowth.com Expert_18071"; // Trade comment
input int      InpSlippagePoints    = 30;                       // Max slippage (points)
input bool     InpDryRun            = true;                     // Dry-run (signal/log only, NO orders)

input group "=== Risk & Sizing ==="
input double   InpRiskPercent       = 0.5;     // Risk % per trade (of effective capital)
input double   InpFixedLot          = 0.01;    // Fallback fixed lot (risk=0 or calc fail)
input double   InpDailyLossLimitPct = 3.0;     // Daily loss limit % (of effective capital)

Full source code available on download

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

Tags:ex18071trendfollowpipsgrowthfreemt5xauusd

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_EX18071.mq5
File Size29.1 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100