P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18040 TrendFollow

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX18040 GB10OOO — Gaussian EMA + ATR band breakout trend EA, full 12-layer stack.

Overview

EX18040 is a single-pair trend-following EA that only fires when three independent filters agree on the same bar. Its core is a Gaussian-style EMA(10) on close, drawn with two parallel ATR(14) envelopes spaced at 0.85×ATR on each side; a long setup requires the previous bar's close to print above the upper band, while a short setup requires the close to print below the lower band. That band break alone is not enough — the entry is rejected unless Heikin-Ashi color and an inline SuperTrend(3.0, ATR14) read the same direction on the same bar. The three-way gate produces a binary confidence score of 100% when aligned, 0% when not, so the EA only ever attempts an order with full agreement rather than partial confidence tiers.

Before any signal logic runs, the EA calls ClassifyRegime(), which returns one of four states. StrongTrend requires ADX(14) ≥ 22 and the current ATR to be in the top 50% of the last 50 bars — the rare, high-energy state. WeakTrend fires when ADX ≥ 18 but the volatility percentile condition is not met. Range is the low-volatility quiet regime (ADX < 18 and ATR percentile < 40%). Everything else is Choppy, and a Choppy label on the live tick is a hard block on new entries. WeakTrend, Range, and StrongTrend are all valid trading contexts; only Choppy is filtered out.

A separate confirmation step in HTFTrendAgrees() adds a higher-timeframe agreement test. The EA builds a 50-period EMA on H1 and only allows longs when the H1 close prints above that EMA and shorts when the H1 close prints below it. The HTF selector input is exposed (InpHTFTimeframe) but with a default of 8 the mapped timeframe always resolves to H1. This decouples the trade from the noise of the 5-minute chart without requiring a multi-timeframe indicator stack on every tick.

The trade itself is sized off the original ATR(14): stop-loss is 1.8×ATR, take-profit is 3.0×ATR, which gives roughly a 1:1.67 R:R. The lot is computed by CalcLot() from 0.5% of effective capital divided by the per-lot loss at that stop distance, with a per-symbol volume clamp against the broker's lot step, min and max. Effective capital is the smaller of account equity and InpCapitalCapAmount if that input is set; with the default of 0.0, the cap is disabled and equity is used directly. A $50 capital floor (InpCapitalCapFloor) blocks new entries when equity is too small to make the math meaningful. Margin requirement is pre-checked via OrderCalcMargin before the order is sent; if free margin is insufficient, the entry is silently skipped.

Order execution has a single retry path. If the broker returns REQUOTE, PRICE_OFF, or TIMEOUT, the EA re-sends the order once at the latest market price. Other retcodes are logged and the entry is dropped. Filling mode is auto-detected per symbol via SetTypeFillingBySymbol, and slippage tolerance is set to 20 points. InpDryRun=true is the default; in dry-run mode the EA prints the full would-be trade line to the journal — direction, confidence, lot, prices, ATR, margin — but never sends an order, which is useful for shadow-testing on a live account.

Risk gates are checked in NoTradeReason(). They include the global InpKillSwitch (halts all new entries), the capital floor, the spread ceiling (default 60 points), the broker-server session window (8:00 to 20:00 by default), weekends, the per-magic max-open-trade cap (3), and a daily realized-loss check of 3% of effective capital. The daily PnL is computed by RealizedPnLToday(), which scans the deal history for trades that match both the EA's magic number and the current symbol and sums profit, swap, and commission. The check is magic-scoped, so a manual trade on the same account does not count against the EA's daily loss budget.

Open-position management is driven by ManagePositions(). The first rule is a one-shot break-even at 1R: once price has moved one full stop-distance in favour of the trade, the stop is ratcheted to open + StopsLevelPrice (or open - StopsLevelPrice for shorts), locking in zero-risk on the remainder of the trade. The second rule is an ATR trail at 1.5×ATR(14), applied forward-only — the trail can move up on a long but never down. The third rule is a 50% partial close at half the TP distance, which fires only if the remaining volume stays at or above 2× the symbol's minimum lot. The fourth rule is an HTF-flip exit: each tick, the EA re-evaluates the H1 close against the H1 EMA(50); if the trend direction on the higher timeframe has reversed, the position is closed immediately via TryClose_EX18040(). This is the dominant exit logic on slow trend days, where the band-break signal itself may not appear for a long time. TryClose/Modify/Partial each use a 3-attempt retry loop with 200ms sleep on requote-class retcodes, and 100ms on modify.

The OnTester custom criterion is (net * profit_factor) / (1 + max(drawdown_percent, 1.0)), with a hard floor of 30 trades — strategies that don't reach the minimum sample size return 0.0 and are excluded from the optimizer's ranking. Because the formula multiplies net profit by profit factor and divides by drawdown, it rewards both absolute return and consistency, and penalizes the curve shapes that look great on net profit alone but have a deep mid-backtest drawdown.

EX18040 is built to trade XAUUSD on M5 with a $100 minimum deposit, but the inputs are broker-portable to any symbol. The defaults assume a single-symbol setup with one position opened per signal, three concurrent trades max, and a per-day 3% loss budget. On a small account the capital floor becomes the binding constraint before the loss limit does. The dry-run default is intentional: the EA is meant to be observed in the journal for at least a few sessions before live orders are enabled.

Strategy Deep Dive

On each tick the EA first refreshes effective capital and scans the deal history to compute the day's realized PnL for its own magic number, then calls ClassifyRegime() to read ADX(14), ATR(14), and Bollinger Band width on the M5 chart. A 50-bar ATR percentile is computed inline to decide between StrongTrend, WeakTrend, Range, and Choppy. If the regime is Choppy, new entries are blocked; otherwise the EA calls CoreSignal(), which checks the closed-bar close against the Gaussian EMA(10) ± 0.85×ATR(14) band, then runs the inline 12-bar Heikin-Ashi reconstruction and the inline 50-bar SuperTrend walk on the same bar. All three must agree. HTFTrendAgrees() then verifies the H1 close vs the H1 EMA(50). Only after that does the lot get computed from 0.5% of effective capital divided by per-lot stop loss, and only then does TryEntry() send the order — with one retry on requote-class retcodes, a margin pre-check, and InpDryRun gating the actual submission. Once positions are open, ManagePositions() runs every tick: 1R break-even, 1.5×ATR forward-only trail, 50% partial close at half the TP distance, and an HTF-flip exit that re-reads the H1 trend and closes the trade immediately if it has reversed.

Entry Signal

EX18040 enters on the closed bar when three conditions align: the prior bar's close is outside the Gaussian EMA(10) ± 0.85×ATR(14) band, Heikin-Ashi direction (inline, 12-bar reconstruction) is bullish or bearish, and the inline SuperTrend(3.0, ATR14) over a 50-bar walk agrees. The entry is also blocked when the regime classifier returns Choppy, and the higher-timeframe H1 EMA(50) must agree with the trade direction (close[1] vs EMA on H1). A duplicate-bar guard prevents two entries on the same closed bar.

Exit Signal

EX18040 closes positions through four exit paths. A one-shot break-even at 1R moves the stop to open ± StopsLevelPrice once price has moved one full stop-distance in favor. A 50% partial close fires at half the TP distance, leaving the runner under the original TP. An ATR(14) trail at 1.5×ATR moves the stop forward only, never backward. The dominant exit is an HTF-flip: each tick the EA re-evaluates the H1 close against the H1 EMA(50), and closes the position immediately if the higher-timeframe trend has reversed.

Stop Loss

Stop-loss is fixed at 1.8×ATR(14) at entry and floored to the broker's StopsLevelPrice when the calculated distance is too tight. A one-shot break-even then moves the stop to open ± StopsLevelPrice once price has moved 1R in favor, and a 1.5×ATR(14) forward-only trail takes over for the rest of the trade.

Take Profit

Take-profit is set at 3.0×ATR(14) at entry, which combined with the 1.8×ATR stop gives roughly a 1:1.67 risk-to-reward ratio. A 50% partial close fires at half the TP distance (≈1.5×ATR) so the runner has a smaller effective TP distance but a better-than-breakeven cushion if the trail takes over.

Best For

EX18040 is best suited to a single XAUUSD M5 chart on a low-spread ECN or RAW account, with a recommended minimum balance of $100 (the capital floor). The 8:00–20:00 broker-server session window keeps the EA inside the London and New York overlap, where gold volatility and ADX readings are most consistent. A broker with SetTypeFillingBySymbol support and tight stops-level handling is required; exotic symbols and high-spread cent accounts will be filtered out by the 60-point spread ceiling. The default InpDryRun=true is the recommended starting state — observe the journal for at least one full trading day before switching to live orders.

Strategy Logic

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

Family: TrendFollow Magic: 22218040 Version: 2.00

BRIEF: Gaussian EMA + ATR band breakout confirmed by inline Heikin-Ashi color and inline SuperTrend side. Layered upgrade adds ADX/ATR-pct/BB-width regime gate, HTF EMA agreement, ATR-based SL/TP, one-shot break-even + ATR trail, partial TP, session/spread/no-trade filters, capital-allocation cap (effective_capital used everywhere), per-magic daily-loss tracking, kill switch, dry-run, custom OnTester criterion. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • NormPrice()
  • StopsLevelPrice()
  • ValidBuf()
  • ClampVolume()
  • CountOpenPositions()
  • RealizedPnLToday()
  • HeikinAshiDir()
  • SuperTrendDir()
  • CoreSignal()
  • HTFTrendAgrees()
  • MinRRok()
  • NoTradeReason()
  • ...and 6 more

INTERNAL CONSTANTS (1 total):

  • EA_COMMENT = InpTradeComment // +------------------------------------------------------------------+

INPUT PARAMETERS (22 total across 6 groups):

  • [] InpTradeComment = "Psgrowth.com Expert_18040" // Order comment
  • [=== Strategy & Signal ===] InpLength = 10 // Gaussian EMA period (bars)
  • [=== Strategy & Signal ===] InpDistanceMultiplier = 0.85 // ATR band distance multiplier (x)
  • [=== Strategy & Signal ===] InpATRPeriod = 14 // ATR period for bands/trail (bars)
  • [=== Strategy & Signal ===] InpSuperTrendMult = 3.0 // SuperTrend ATR multiplier (x)
  • [=== Strategy & Signal ===] InpHTFTimeframe = 8 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend timeframe
  • [=== Regime Filter ===] InpADXPeriod = 14 // ADX period (bars)
  • [=== Regime Filter ===] InpADXStrongTrendMin = 22.0 // ADX min for StrongTrend gate
  • [=== Regime Filter ===] InpATRPctLookback = 50 // ATR percentile lookback (bars)
  • [=== Risk & Sizing ===] InpCapitalCapAmount = 0.0 // Capital cap amount ($, real money equity)
  • [=== Risk & Sizing ===] InpCapitalCapFloor = 50.0 // Capital floor; block new entries below ($)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective capital)
  • [=== Risk & Sizing ===] InpDailyLossLimitPercent = 3.0 // Daily loss limit (% of effective capital)
  • [=== Trade Management ===] InpMaxOpenTrades = 3 // Max concurrent open trades (count)
  • [=== Trade Management ===] InpSLATRmult = 1.8 // Stop-loss distance (x ATR)
  • [=== Trade Management ===] InpTPATRmult = 3.0 // Take-profit distance (x ATR)
  • [=== Trade Management ===] InpTrailATRmult = 1.5 // ATR trailing distance (x ATR)
  • [=== Execution & Operational ===] InpMaxSpreadPoints = 60 // Max allowed spread (points)
  • [=== Execution & Operational ===] InpSessionStartHour = 8 // Session start hour (broker server time)
  • [=== Execution & Operational ===] InpSessionEndHour = 20 // Session end hour (broker server time)
  • [=== Execution & Operational ===] InpDryRun = true // Dry-run: log signals, do NOT send orders
  • [=== Execution & Operational ===] InpKillSwitch = false // Kill switch: halt all new entries
Pseudocode
// Pipsgrowth EX18040 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// Gaussian EMA + ATR band breakout confirmed by inline Heikin-Ashi color and inline SuperTrend side. Layered upgrade adds ADX/ATR-pct/BB-width regime gate, HTF EMA agreement, ATR-based SL/TP, one-shot break-even + ATR trail, partial TP, session/spread/no-trade filters, capital-allocation cap (effective_capital used everywhere), per-magic daily-loss tracking, kill switch, dry-run, custom OnTester criterion. 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
InpTradeComment"Psgrowth.com Expert_18040"Order comment
InpLength10Gaussian EMA period (bars)
InpDistanceMultiplier0.85ATR band distance multiplier (x)
InpATRPeriod14ATR period for bands/trail (bars)
InpSuperTrendMult3.0SuperTrend ATR multiplier (x)
InpHTFTimeframe8Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend timeframe
InpADXPeriod14ADX period (bars)
InpADXStrongTrendMin22.0ADX min for StrongTrend gate
InpATRPctLookback50ATR percentile lookback (bars)
InpCapitalCapAmount0.0Capital cap amount ($, real money equity)
InpCapitalCapFloor50.0Capital floor; block new entries below ($)
InpRiskPercent0.5Risk per trade (% of effective capital)
InpDailyLossLimitPercent3.0Daily loss limit (% of effective capital)
InpMaxOpenTrades3Max concurrent open trades (count)
InpSLATRmult1.8Stop-loss distance (x ATR)
InpTPATRmult3.0Take-profit distance (x ATR)
InpTrailATRmult1.5ATR trailing distance (x ATR)
InpMaxSpreadPoints60Max allowed spread (points)
InpSessionStartHour8Session start hour (broker server time)
InpSessionEndHour20Session end hour (broker server time)
InpDryRuntrueDry-run: log signals, do NOT send orders
InpKillSwitchfalseKill switch: halt all new entries
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18040.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18040 GB10OOO — Gaussian EMA + ATR band breakout trend EA, full 12-layer stack."

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>

#define EA_MAGIC      22218040
input string InpTradeComment = "Psgrowth.com Expert_18040"; // Order comment
#define EA_COMMENT    InpTradeComment

//+------------------------------------------------------------------+
//| INPUTS (22 total, grouped)                                        |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M5;
      case 3: return PERIOD_M15;
      case 4: return PERIOD_M30;
      case 5: return PERIOD_H1;
      case 6: return PERIOD_H4;
      case 7: return PERIOD_D1;
      default: return PERIOD_H1;
   }
}

ENUM_APPLIED_PRICE MapAppliedPriceInt(int ap)
{
   switch(ap)
   {
      case 1: return PRICE_CLOSE;
      case 2: return PRICE_OPEN;
      case 3: return PRICE_HIGH;
      case 4: return PRICE_LOW;
      case 5: return PRICE_MEDIAN;
      case 6: return PRICE_TYPICAL;
      case 7: return PRICE_WEIGHTED;
      default: return PRICE_CLOSE;
   }
}
ENUM_TIMEFRAMES g_InpHTFTimeframe = PERIOD_H1;
input group "=== Strategy & Signal ==="
input int              InpLength              = 10;      // Gaussian EMA period (bars)
input double           InpDistanceMultiplier  = 0.85;    // ATR band distance multiplier (x)
input int              InpATRPeriod           = 14;      // ATR period for bands/trail (bars)
input double           InpSuperTrendMult      = 3.0;     // SuperTrend ATR multiplier (x)
input int InpHTFTimeframe = 8; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // HTF trend timeframe

ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;

Full source code available on download

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

Tags:ex18040trendfollowpipsgrowthfreemt5xauusd

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