P
PipsGrowth
OtherOpen Source – Free

Pipsgrowth EX17021 Volatility

MT5 Expert Advisor (Open Source) · XAUUSD · M5

Pipsgrowth.com EX17021 GB10_5_2_updated5 — Adaptive Gaussian Band breakout with 3 strategy modes, full 12-layer stack.

Overview

EX17021 is an envelope-trader that wraps a single ATR(14)-driven band around a fast 10-period EMA on close, then lets the trader pick one of three ways to interact with that band: chase the breakout, chase the breakout and exit at the midline, or fade the band back to the midline. The 'Gaussian' name in the brief is a label, not a kernel — the central line is a plain MODE_EMA / PRICE_CLOSE moving average with Length = 10 bars. The envelope is built on top: upperBand = gaussNow + DistanceMultiplier * ATR(14) and lowerBand = gaussNow - DistanceMultiplier * ATR(14), with DistanceMultiplier = 0.85 out of the box, giving a band roughly 1.7×ATR(14) wide.

A second indicator stack is layered on a different timeframe for trend alignment. TrendFilterTF = 6 resolves to PERIOD_H4 by default, and on that frame the EA plots an EMA(50) on close. The two-band stack is evaluated on the EA's main g_Timeframe (default PERIOD_H1, selectable 1–7 in the inputs), but the HTF EMA cross-check is always read on the trend frame. So a buy breakout on the 1-hour band is only valid if H4 close is above its own 50-EMA, and vice versa for sells. This is the only multi-timeframe filter the EA runs; it does not look at HTF ADX, MACD, or anything else.

Three modes share the same indicator stack but interpret the band differently. StrategyMode_Breakout (default) is a continuation mode: the current bar must close outside the band while the two prior bars closed inside, slope (gaussNow vs gaussPrev) must agree with direction, price must be on the right side of the HTF EMA, and the breakout must travel further than MinBreakDistance * ATR(14) (0.3 × ATR default) past the band. The 'strong candle' filter — body ≥ 60% of candle size — gates the entry one more time, so a doji that pokes through the band is rejected. StrategyMode_BreakoutMeanExit uses the same entry conditions but, on every tick, closes the position the moment price re-crosses the central line in the wrong direction. StrategyMode_MeanReversion ignores the breakout construction entirely; it enters on a single bar's band cross (pricePrev outside, price inside) and closes at the midline. The two mean-touching modes both disable the trailing stop and the breakeven move, so the only exit they will see is the midline or the original SL.

Position management is where the EA does the most work. SL is computed by StopLossOffset(atr), which returns the larger of ATR_MultiplierSL * ATR(14) (1.2 × ATR) and HardSL_Points * _Point (120 points). With UseATR_StopLoss = true the floor dominates most of the time; on quiet pairs the 120-point floor may be the binding number. TP defaults to a flat 160 points (UseATR_TakeProfit = false, FixedTP_Points = 160), and the brief's callout of a 1:1.33 RR comes from this asymmetry. If the user flips UseATR_TakeProfit = true, TP moves to ATR_MultiplierTP * ATR(14) (1.5 × ATR).

For open positions in the two breakout modes, three ratchets run on every tick and the order matters. First, the trailing stop updates SL to bid - slOffset (buy) or ask + slOffset (sell) whenever the new level is better than the current SL — this is a continuous ratchet, not a step. Second, the breakeven move fires once price has travelled one full slOffset in profit: SL is set to entry price, locking the trade flat. Third, the dynamic lock profit runs a discrete dollar ladder: every LockProfitEvery_X_Dollars (default 2 dollars) of unrealized profit, the EA re-anchors the SL to entry + (n * step - buffer) / tickValue * tickSize, so a position with $10 floating locks roughly $8-$9 in price behind the entry. The three mechanisms are designed to stack: trailing gives the first bit of protection, breakeven takes over once the trade is solidly green, and the dollar ladder starts adding a few points of locked profit every additional two dollars. The LockMinusBuffer = 1.0 ensures the lock sits just inside the next dollar mark, which prevents the lock from being immediately tested by spread.

The portfolio side is set up for conservative scaling. MaxOpenTrades = 5 is the ceiling, but OneTradeOnly = true defaults to a single-position configuration. The AllowOnlyProfitableAdditions filter (default true) means that, even if OneTradeOnly is flipped to false, the EA will not add a second position until every open position is showing at least MinProfitPerTradeToAdd = $5. The MaxDrawdownPercent = 10.0 is a hard gate: on every tick, the EA checks 100 * (balance - equity) / balance against this cap and refuses to open new trades when breached. This is the only explicit money-management stop in the EA — there is no daily-loss limit and no per-week reset.

The autotune logic in AutoTuneFilters is small but worth understanding. It reads the current spread and infers the symbol: spreads under 3 points imply a forex pair (pipFactor = 0.0001), wider spreads imply gold or a metals contract (pipFactor = 0.01). minATR is then anchored at 3 × pipFactor, so 0.0003 on EURUSD-class pairs and 0.03 on XAUUSD. This makes the EA portable across the brief's stated range (FX majors and metals) without the user having to swap pip values. The default MinATR = 0.03 matches the gold side; FX users will see the auto-filter drop the floor to 0.0003 once the input is left untouched and UseAutoFilter = true is on.

Order execution itself uses a three-retry scaffold. TryClose_EX17021, TryClosePartial_EX17021, and TryModify_EX17021 each loop up to three times, sleeping 100-200 ms on requote/timeout/price-changed responses and breaking the loop on any other return code. Magic number is fixed at 22217021 and trade.SetTypeFillingBySymbol(_Symbol) lets the broker decide the filling policy. There are no iCustom calls — the three indicator handles are plain iMA and iATR — which keeps the on-chart footprint minimal.

The natural fit is a swing-trader on XAUUSD M5-M15 who wants the band to do the work of locating a regime transition and is comfortable leaving the EA in single-position mode for a session. MeanReversion is for sessions with bounded ranges, Breakout for the same EA when range breaks, BreakoutMeanExit sits between them — it enters like a breakout, exits like a reversion. Backtests will be sensitive to Length, DistanceMultiplier, and TrendEMA more than to any other inputs, because the rest of the management is fixed once OneTradeOnly is chosen.

Strategy Deep Dive

Each tick the EA pulls ATR(14), a 10-period EMA, and a 50-period EMA on a separate trend timeframe (H4 by default) into local buffers via UpdateIndicatorBuffers and UpdatePriceBuffers. It first runs CheckMaxDrawdown against a 10% equity gate, then sizes the band as gaussNow ± 0.85 × ATR, infers pip factor from spread, and compares the current candle's close against the band, slope, HTF EMA, and minimum break distance to decide if a long or short qualifies. For the two breakout modes, the candle body must cover 60% of its range; mean-reversion skips that check. On a valid signal, CloseOpposite flips the position and trade.Buy or trade.Sell opens the new one with SL at StopLossOffset(atr) and TP at FixedTP_Points = 160. After entry, three ratchets run in sequence on every tick: trailing pushes SL to maintain slOffset behind price, breakeven moves SL to entry once price has travelled one full slOffset in profit, and the dynamic lock-profit ladder repositions SL by LockProfitEvery_X_Dollars dollar steps minus a $1 buffer, computed through tickValue/tickSize. All order operations route through the TryClose_EX17021 / TryModify_EX17021 3-retry scaffolds with 100–200 ms backoff on requotes.

Entry Signal

Entry is band-driven and mode-specific. In Breakout (default) and BreakoutMeanExit, a buy needs the prior two closes inside the upper band and the current close outside it, slope up (gaussNow > gaussPrev), close above the H4 EMA(50), breakout distance greater than 0.3 × ATR(14), and a body ≥ 60% of the candle. MeanReversion enters on a single-bar cross back inside the band with no body or slope requirement.

Exit Signal

Exit depends on mode. Breakout positions close on TP (160 points default), trailing ratchet, breakeven, or the dynamic lock-profit ladder. BreakoutMeanExit additionally closes the instant price re-crosses the central EMA. MeanReversion positions close the moment price touches the central line on the right side.

Stop Loss

SL is the larger of 1.2 × ATR(14) and 120 points (default UseATR_StopLoss = true), then optionally ratcheted by trailing, breakeven (triggered after one full slOffset of favorable travel), and a $2-step dynamic lock-profit ladder that pulls SL up by $1 less than each $2 of unrealized profit.

Take Profit

TP defaults to a fixed 160 points (UseATR_TakeProfit = false); flipping that input on moves TP to 1.5 × ATR(14) per position. BreakoutMeanExit and MeanReversion can also exit at the central EMA instead of waiting for TP.

Best For

Single-position swing traders on XAUUSD M5-M15 with a $100 minimum account and a medium risk tolerance. The 10% equity drawdown gate and the $2-step profit-lock ladder make it suitable for prop-firm-style rules. Best run on a low-spread ECN broker, since the spread-based auto-filter (avgSpread < 3) explicitly detects forex vs gold — wider spreads on the same symbol will route the EA to the metals pip factor and may reject more setups.

Strategy Logic

Pipsgrowth EX17021 Volatility — Strategy Logic Analysis (from .mq5 source)

Family: Volatility Magic: 22217021 Version: 2.00

BRIEF: Adaptive Gaussian Band breakout EA supporting three strategy modes: Breakout, BreakoutMeanExit, and MeanReversion. Uses auto-filter, ATR-based SL/TP, trailing stop, breakeven, dynamic lock profit, and drawdown control. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • PrepareBuffer()
  • LogBufferError()
  • LogTradeError()
  • ReleaseIndicator()
  • FreeBuffers()
  • UpdateIndicatorBuffers()
  • UpdatePriceBuffers()
  • InitializeBuffers()
  • PositionExists()
  • CloseOpposite()
  • AutoTuneFilters()
  • CheckMaxDrawdown()
  • ...and 7 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (10 total across 4 groups):

  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_17021" // Trade Comment
  • [=== Identity ===] InpMagicNumber = 22217021 // Magic Number
  • [=== Strategy Settings ===] Timeframe = 0 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
  • [=== Strategy Settings ===] TrendFilterTF = 6 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
  • [=== Trade Management ===] MaxOpenTrades = 5 // Maximum allowed open trades at the same time
  • [=== Trade Management ===] AllowOnlyProfitableAdditions = true // Enable filter
  • [=== Trade Management ===] MinProfitPerTradeToAdd = 5.0 // Minimum $ profit required per existing trade
  • [=== Risk & Exit Controls ===] LockProfitEvery_X_Dollars = 2.0 // Step: every $6 profit
  • [=== Risk & Exit Controls ===] LockMinusBuffer = 1.0 // Lock profit minus $1 buffer
  • [=== Risk & Exit Controls ===] MaxDrawdownPercent = 10.0 // Max drawdown % allowed
Pseudocode
// Pipsgrowth EX17021 Volatility — Execution Flow (from source analysis)
// Family: Volatility
// Adaptive Gaussian Band breakout EA supporting three strategy modes: Breakout, BreakoutMeanExit, and MeanReversion. Uses auto-filter, ATR-based SL/TP, trailing stop, breakeven, dynamic lock profit, and drawdown control. 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 a chart matching the recommended timeframe
  7. 7Configure parameters according to the table on this page
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InpTradeComment"Psgrowth.com Expert_17021"Trade Comment
InpMagicNumber22217021Magic Number
Timeframe0Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
TrendFilterTF6Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
MaxOpenTrades5Maximum allowed open trades at the same time
AllowOnlyProfitableAdditionstrueEnable filter
MinProfitPerTradeToAdd5.0Minimum $ profit required per existing trade
LockProfitEvery_X_Dollars2.0Step: every $6 profit
LockMinusBuffer1.0Lock profit minus $1 buffer
MaxDrawdownPercent10.0Max drawdown % allowed
Source Code (.mq5)Open Source
Pipsgrowth_com_EX17021.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX17021 GB10_5_2_updated5 — Adaptive Gaussian Band breakout with 3 strategy modes, full 12-layer stack."
#include <Trade\Trade.mqh>
CTrade trade;

enum ENUM_StrategyMode
{
   StrategyMode_Breakout = 0,
   StrategyMode_BreakoutMeanExit = 1,
   StrategyMode_MeanReversion = 2
};

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_TIMEFRAMES g_Timeframe = PERIOD_H1;
ENUM_TIMEFRAMES g_TrendFilterTF = PERIOD_H1;
input group "=== Identity ==="
input string InpTradeComment = "Psgrowth.com Expert_17021";    // Trade Comment
input ulong  InpMagicNumber  = 22217021;                       // Magic Number

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_TIMEFRAMES g_Timeframe = PERIOD_H1;
ENUM_TIMEFRAMES g_TrendFilterTF = PERIOD_H1;
input group "=== Strategy Settings ==="
input ENUM_StrategyMode StrategyMode = StrategyMode_Breakout;
input bool   UseAutoFilter       = true;
input int    Length              = 10;
input double DistanceMultiplier  = 0.85;
input int Timeframe = 0; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
input int TrendFilterTF = 6; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
input int    TrendEMA            = 50;

Full source code available on download

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

Tags:ex17021volatilitypipsgrowthfreemt5xauusd

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_EX17021.mq5
File Size22.5 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyOther
Risk LevelMedium Risk
Timeframes
M5
Currency Pairs
XAUUSD
Min. Deposit$100