P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16101 Trend

MT5 Expert Advisor (Open Source) · XAUUSD · M1

Pipsgrowth.com EX16101 GoldTrendStackerEA — gold trend stacking EA for XAUUSD M1, full 12-layer stack.

Overview

The Pipsgrowth EX16101 GoldTrendStackerEA is built for a single purpose: layering trend-aligned entries on a 1-minute XAUUSD chart while other EAs in the family work higher timeframes or with single-shot entries. Where most MT5 trend-following robots place one position per signal and wait, EX16101 deliberately accumulates — it can stack up to three positions in the same direction when the original trade is already profitable and price has moved far enough from the prior entry. The default stack distance of 120 points combined with the 50-point minimum profit requirement means a new layer only appears after the prior layer is comfortably in the green, which makes the stack feel like a measured add-to-winner rather than a martingale-style grid recovery.

The engine sits on a moving-average crossover as its base signal. The fast MA defaults to a 10-period SMA and the slow MA to a 20-period SMA, both using the close. A bullish cross (fast above slow on the current bar after being below on the previous bar) seeds a long bias; a bearish cross does the opposite. On its own this would be a noisy M1 cross, so the EA wraps the cross in three optional confirmations that operate as AND gates: a Hull moving average of 21 periods (the source uses a 21-period EMA as a placeholder for HMA, which is a noticeable limitation), an RSI(14) with bullish threshold 55 and bearish threshold 45, and a multi-timeframe confirmation. The multi-timeframe check is set to M30 and H4 by default and re-evaluates the HMA on those higher TFs; the entry is rejected if the higher-TF HMA disagrees with the proposed direction. The SuperTrend filter is listed in the inputs but the iCustom call is a placeholder — the variable prints a notice and the actual trend-direction logic is never evaluated, so a trader who enables the SuperTrend toggle gets a filter that doesn't filter.

A second layer of logic determines whether to enter at all. IsChoppyMarket() returns true if any of three conditions fire: ADX(14) below the 20 threshold, RSI(14) sitting inside the 45-55 dead zone, or Bollinger Bands width (20-period, 2.0 deviations) compressing below 0.5 points. The band-width check works in points rather than as a percentage of price, so on a 5-digit gold broker where the point is 0.01, 0.5 points is half a cent — extremely tight and almost always triggers. The Bollinger filter is therefore likely to block all but the most volatile minutes unless the user widens BbWidthThreshold substantially. The Heiken Ashi filter and SuperTrend filter both compile but their IsHeikenAshiAlternating / IsHeikenAshiBullishStrong / IsHeikenAshiBearishStrong helpers and the SuperTrend iCustom handle are commented out as placeholders, so those toggles in the input panel are effectively cosmetic.

Position management combines a fixed stop, a step-ratcheted trailing stop, and a secure-older-stacks function. Every entry gets a 120-point hard stop and zero take-profit — the design assumes exits are managed by the trailing stop rather than a fixed target. The trailing engine waits until the position is 120 points in profit, then ratchets the stop in 50-point steps: as profit grows the SL moves to open + 120 + (steps-1)*50 points for a long. The SL only moves forward, never backward. SecureStackedPositions() handles the multi-position case: it identifies the most recent buy and the most recent sell tickets, then for every older same-direction position whose profit exceeds SecuredProfitPoints (default 5 points), it moves the SL to open + 5 points for buys or open - 5 points for sells, locking in a tiny profit on the older layers while leaving the newest position free to ride.

Risk control is layered. MinEquityForNewTrades (default 300) gates all new entries — if account equity drops below 300, the EA still manages existing positions but won't open new ones. The Cooldown Management block sets a 30-minute pause after 3 consecutive losses, but the implementation is partial: the OnTradeTransaction handler counts closing deals but the consecutive-loss counter is never actually incremented inside the deal-add branch, which is a bug — the cooldown timer effectively never fires unless the user manually adjusts consecutiveLosses or extends the logic. The session manager enforces a default no-trade window from 00:00 to 03:00 server time and stops opening new positions 20 minutes before the assumed 23:59 server end-of-day. FridaySessionCutoff (default true) repeats the cutoff on Friday, and when CloseAllBeforeClose is enabled, every position on the symbol is force-closed at the cutoff time using TryClose_EX16101.

All order operations go through a CTrade wrapper. OpenTrade sends a market order with the configured 0.01 lot, the 120-point stop, and zero TP, with a 10-point slippage allowance. The trade comment "Psgrowth.com Expert_16101" lets the user filter this EA's history in MT5. The retry helpers TryClose_EX16101, TryClosePartial_EX16101, and TryModify_EX16101 each loop up to 3 times on requote, timeout, price-off, and price-changed errors with 200ms (or 100ms for modify) sleeps. TryClose is wired into the session-end close; TryModify is wired into the trailing stop and the stack-secure logic. TryClosePartial is defined but never called anywhere in the source.

Two notes a backtester should know about before trusting any numbers. First, the EA checks Period() != PERIOD_M1 in OnInit and prints a warning but does not refuse to run, so attaching it to M5 or M15 will compile, attach, and trade on a non-M1 chart despite the header note that the EA is designed for M1. Second, GetMarketCloseTime() hard-codes 23:59 as the assumed daily close, which works on a broker whose server midnight is near the trading day's end but fails on brokers that roll over at 22:00 or 00:00 — the Friday cutoff will close positions at the wrong time on those servers. Brokers with deep liquidity and tight spreads are essential because the trailing stop engages after only 120 points and a 30-point spread eats a quarter of that room.

The EA is genuinely a scalper, not a swing trader. With a 0.01 lot, a 120-point stop, and 0 TP, each unleveraged position risks roughly 0.12 percent of a 10000 dollar account per layer, but stacking up to 3 positions in the same direction triples the heat on a single trade idea. The intended rhythm is many small wins via the trailing ratchet, not a few large winners — and the trailing mechanism is what determines the realized P&L on most positions, not the entry signal.

Strategy Deep Dive

On every tick the EA first runs the time gate, equity gate, and cooldown gate; if any return false, ManageExistingTrades() is still called so the trailing stop and the stack-secured SL keep ratcheting, but no new orders are sent. When all gates pass and a new bar has formed, CheckNewTradeSignals() reads the MA crossover, applies the RSI gate, the HMA gate, and the multi-timeframe HMA confirmation (M30 and H4 by default), and only then returns a buy or sell. IsChoppyMarket() runs first and short-circuits the entire pipeline if ADX is weak, RSI sits in the dead zone, or Bollinger Band width is too narrow. The stack logic in CanStackTrade() enforces that all same-direction positions are at least 50 points in profit and the new entry is at least 120 points from the most recent one. OpenTrade() then sends a market order with the fixed 120-point stop and zero take-profit through a CTrade wrapper that retries on requote and price-change errors.

Entry Signal

A long entry triggers when the 10-period fast SMA crosses above the 20-period slow SMA, the 21-period HMA (EMA placeholder) sits below the ask, RSI(14) is above 55, and the higher-timeframe HMA agrees on M30 and H4 by default. The reverse configuration produces a short entry. IsChoppyMarket() must return false — meaning ADX ≥ 20, RSI outside 45-55, and Bollinger Band width ≥ 0.5 points — for the signal to pass. For stack entries (2nd or 3rd in same direction), every existing same-direction position must be at least 50 points in profit and price must be at least 120 points from the most recent same-direction entry.

Exit Signal

Positions exit on a 120-point trailing stop that begins ratcheting once profit reaches 120 points and steps forward in 50-point increments. Older positions in a stack are secured by moving their stop to open ± 5 points (SecuredProfitPoints) once profit on those positions exceeds 5 points, while the most recent position keeps its trailing stop free. There is no fixed take-profit — exits are entirely managed by the stops, the trailing ratchet, and the session-end close. The Friday/daily cutoff at 20 minutes before 23:59 server time force-closes positions when CloseAllBeforeClose is enabled.

Stop Loss

Every new entry is opened with a fixed 120-point stop loss (HardStopLossPoints) placed at the entry price, with an extra floor that respects the broker's SYMBOL_TRADE_STOPS_LEVEL minimum. Account-level risk is also enforced by MinEquityForNewTrades: when equity drops below 300 the EA stops opening new trades while still managing existing ones. There is no per-trade percentage risk or position-sizing formula — the SL distance is fixed in points and the lot is fixed at 0.01.

Take Profit

There is no take-profit — the source code sets TP=0 for both buy and sell orders, deliberately leaving exit to the trailing stop. The trailing engine ratchets the stop forward in 50-point steps once profit crosses 120 points, which is what converts a trend move into a realized win.

Best For

This EA is calibrated for traders who want to layer entries on a 1-minute XAUUSD chart during active sessions, with a recommended starting balance of at least 300 dollars (MinEquityForNewTrades) and ideally around 1000 to absorb the 120-point stop on a 0.01 lot comfortably. The London-New York overlap is the natural window because both produce the volatility needed to clear the 120-point stack distance; the 00:00-03:00 server-time no-trade window is built in by default. Use a low-spread ECN broker on gold because the trailing stop engages after only 120 points and a 30-point spread eats a quarter of that room. M1 is required for the design to make sense — attaching to higher TFs will compile but trigger the OnInit warning.

Strategy Logic

Pipsgrowth EX16101 Trend — Strategy Logic Analysis (from .mq5 source)

Family: Trend Magic: 22216101 Version: 2.00

BRIEF: Gold Trend Stacker EA that scalps XAUUSD on M1 using SuperTrend, HMA, RSI, Bollinger Bands and ADX with stacking. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • AttachIndicators()
  • SecureStackedPositions()
  • ManageExistingTrades()
  • CheckNewTradeSignals()
  • CountOpenTrades()
  • CanStackTrade()
  • OpenTrade()
  • IsChoppyMarket()
  • CheckConfirmationTFs()
  • IsTradingAllowedByTime()
  • GetMarketCloseTime()
  • CloseTradesBeforeSessionEnd()
  • ...and 7 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (37 total across 9 groups):

  • [=== Trade Settings ===] LotSize = 0.01 // Initial Lot Size
  • [=== Trade Settings ===] MagicNumber = 22216101 // EA Magic Number
  • [=== Trade Settings ===] InpTradeComment = "Psgrowth.com Expert_16101" // Trade Comment
  • [=== Trade Settings ===] MaxOpenTrades = 3 // Max Stack Trades
  • [=== Trade Settings ===] MinEquityForNewTrades = 300.0 // Prevents trading below this equity
  • [=== Stop Loss & Trailing ===] HardStopLossPoints = 120.0 // SL per trade in points
  • [=== Stop Loss & Trailing ===] TrailingStartPoints = 120.0 // Start trailing after this profit in points
  • [=== Stop Loss & Trailing ===] TrailingStepPoints = 50.0 // SL moves every this step in points
  • [=== Stacking Logic ===] StackDistancePoints = 120.0 // Points between stack entries
  • [=== Stacking Logic ===] MinProfitPerTradeToStack = 50.0 // All trades must meet this profit (in points) to allow stacking
  • [=== Stacking Logic ===] MinMinutesBetweenStackTrades = 2 // Prevent overstacking
  • [=== Stacking Logic ===] SecuredProfitPoints = 5.0 // Lock-in profit on older stack trades (points)
  • [=== MA Signal Settings ===] MAPrice = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
  • [=== Indicator Parameters ===] SupertrendMultiplier = 3.0 // HMA
  • [=== Indicator Parameters ===] HmaPeriod = 21 // RSI
  • [=== Indicator Parameters ===] RsiRangeMidUpper = 55.0 // For choppy market filter
  • [=== Indicator Parameters ===] RsiRangeMidLower = 45.0 // For choppy market filter
  • [=== Indicator Parameters ===] BbWidthThreshold = 0.5 // For choppy market filter
  • [=== Indicator Parameters ===] AdxThreshold = 20 // For choppy market filter
  • [=== Indicator Filters Enable/Disable ===] UseHeikenAshiFilter = true // Note: Heiken Ashi logic needs specific implementation
  • [=== Indicator Filters Enable/Disable ===] UseSupertrendFilter = true // Note: Supertrend logic needs specific implementation (iCustom)
  • [=== Indicator Filters Enable/Disable ===] UseAdxFilter = true // For choppy market filter
  • [=== Indicator Filters Enable/Disable ===] UseBbWidthFilter = true // For choppy market filter
  • [=== Indicator Filters Enable/Disable ===] UseBbExpansionFilter = true // This was in spec, but not clearly defined how to use. Add if logic is clear.
  • [=== Indicator Filters Enable/Disable ===] UseMaCrossoverFilter = true // Added for MA Signal Settings
  • [=== Indicator Filters Enable/Disable ===] AttachIndicatorsToChart = true // Visualize indicators on the chart
  • [=== Timeframe Confirmation ===] ConfirmTF1 = 4 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
  • [=== Timeframe Confirmation ===] ConfirmTF2 = 6 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
  • [=== Session Management ===] StopBeforeCloseMin = 20 // Stop trading X minutes before daily close
  • [=== Session Management ===] CloseAllBeforeClose = true // Close all trades before daily close
  • [=== Session Management ===] CloseOnlyProfitable = false // Close only profitable before daily close
  • [=== Session Management ===] CloseOnlyLosing = false // Close only losing before daily close
  • [=== Session Management ===] FridaySessionCutoff = true // Apply cutoff on Friday
  • [=== Session Management ===] BlockTradingStartHour = 0 // Start of no-trade window (server time)
  • [=== Session Management ===] BlockTradingEndHour = 3 // End of no-trade window (server time)
  • [=== Cooldown Management ===] ConsecutiveLossLimit = 3 // After X consecutive losses
  • [=== Cooldown Management ===] CooldownMinutes = 30 // Pause new trades for Y minutes
Pseudocode
// Pipsgrowth EX16101 Trend — Execution Flow (from source analysis)
// Family: Trend
// Gold Trend Stacker EA that scalps XAUUSD on M1 using SuperTrend, HMA, RSI, Bollinger Bands and ADX with stacking. 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:
M1

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
LotSize0.01Initial Lot Size
MagicNumber22216101EA Magic Number
InpTradeComment"Psgrowth.com Expert_16101"Trade Comment
MaxOpenTrades3Max Stack Trades
MinEquityForNewTrades300.0Prevents trading below this equity
HardStopLossPoints120.0SL per trade in points
TrailingStartPoints120.0Start trailing after this profit in points
TrailingStepPoints50.0SL moves every this step in points
StackDistancePoints120.0Points between stack entries
MinProfitPerTradeToStack50.0All trades must meet this profit (in points) to allow stacking
MinMinutesBetweenStackTrades2Prevent overstacking
SecuredProfitPoints5.0Lock-in profit on older stack trades (points)
MAPrice1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)
SupertrendMultiplier3.0HMA
HmaPeriod21RSI
RsiRangeMidUpper55.0For choppy market filter
RsiRangeMidLower45.0For choppy market filter
BbWidthThreshold0.5For choppy market filter
AdxThreshold20For choppy market filter
UseHeikenAshiFiltertrueNote: Heiken Ashi logic needs specific implementation
UseSupertrendFiltertrueNote: Supertrend logic needs specific implementation (iCustom)
UseAdxFiltertrueFor choppy market filter
UseBbWidthFiltertrueFor choppy market filter
UseBbExpansionFiltertrueThis was in spec, but not clearly defined how to use. Add if logic is clear.
UseMaCrossoverFiltertrueAdded for MA Signal Settings
AttachIndicatorsToCharttrueVisualize indicators on the chart
ConfirmTF14Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
ConfirmTF26Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)
StopBeforeCloseMin20Stop trading X minutes before daily close
CloseAllBeforeClosetrueClose all trades before daily close
CloseOnlyProfitablefalseClose only profitable before daily close
CloseOnlyLosingfalseClose only losing before daily close
FridaySessionCutofftrueApply cutoff on Friday
BlockTradingStartHour0Start of no-trade window (server time)
BlockTradingEndHour3End of no-trade window (server time)
ConsecutiveLossLimit3After X consecutive losses
CooldownMinutes30Pause new trades for Y minutes
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16101.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16101 GoldTrendStackerEA — gold trend stacking EA for XAUUSD M1, full 12-layer stack."

//--- Include files
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <MovingAverages.mqh> // For HMA if available, or standard MAs

//--- Input Configuration Summary
//--- Trade Settings
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_ConfirmTF1 = PERIOD_H1;
ENUM_TIMEFRAMES g_ConfirmTF2 = PERIOD_H1;
ENUM_APPLIED_PRICE g_MAPrice = PRICE_CLOSE;
input group   "=== Trade Settings ==="
input double  LotSize = 0.01;                     // Initial Lot Size
input int     MagicNumber = 22216101;             // EA Magic Number
input string  InpTradeComment = "Psgrowth.com Expert_16101"; // Trade Comment
input int     MaxOpenTrades = 3;                  // Max Stack Trades
input double  MinEquityForNewTrades = 300.0;      // Prevents trading below this equity

//--- Stop Loss & Trailing
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M5;

Full source code available on download

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

Tags:ex16101trendpipsgrowthfreemt5xauusd

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