P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16062 Trend

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

Pipsgrowth.com EX16062 P — Adaptive multi-confirmation EA, full 12-layer stack.

Overview

Adaptive confluence engine built around a five-signal weighted voting system, where the Adaptive Moving Average (AMA) carries the heaviest weight and a self-tuning sensitivity knob rescales the confirmation threshold in response to recent win/loss streaks. EX16062 is not a single-indicator trend follower — it is a layered scoring model that adapts the entry bar based on what the market has just been doing.

The five signal sources and their weights in GetMarketSignal() are fixed at the source level: AMA = 0.4, RSI = 0.2, MACD = 0.2, Stochastic = 0.1, and a price-action trend filter (SMA(5) vs SMA(20)) = 0.1. Each component casts a discrete -1, 0, or +1 vote, and the EA enters long when the weighted sum crosses above +0.5 * adaptiveSensitivity and short when it falls below -0.5 * adaptiveSensitivity. That sensitivity is not a static input — it is a runtime variable (adaptiveSensitivity, default 0.5, clamped to the [0.3, 1.0] band) that drifts up by 0.1 after three consecutive wins and down by 0.1 after two consecutive losses. The practical effect: the EA tightens its confirmation requirements when it is losing and loosens them when it is winning. A long stretch of profitable trades will let a barely-confirmed AMA crossover through, while a losing stretch demands three or four components to agree before any new position is sized.

The AMA itself runs with AMA_Period=14, AMA_FastEMA=2, AMA_SlowEMA=30, and the entry fires when price crosses the AMA line in either direction (current bid above AMA[0] while previous close was below AMA[1] for longs, and the mirror for shorts). The RSI layer is not a generic 30/70 — it is volatility-adjusted. The EA computes volatilityRatio = currentATR / averageATR(3) and shifts the overbought threshold up by (volatilityRatio - 1) * 10 * adaptiveSensitivity and the oversold threshold down by the same amount. In a high-ATR regime, RSI must run more extreme to register a buy or sell vote; in a quiet session, ordinary 30/70 excursions are sufficient. MACD is a standard 12/26/9 line-vs-signal crossover; Stochastic is a fixed 20/80 zone reading on the %K line with no smoothing for an overbought/oversold vote. The trend filter uses two simple moving averages that are computed on the fly inside the EA — period 5 and period 20 — and contribute a directional vote, not an entry trigger.

Position management is a strict one-position-per-symbol model. The OnTick block reads the current market signal, and if the signal conflicts with the open position, EX16062 first deletes any pending orders via ClosePendingOrders(), then closes the opposing position with CloseAllPositions() before opening the new direction. There is no grid, no martingale, and no averaging — the EA does not tolerate two positions in flight at once, and it does not build a basket. On a signal that matches the open direction, the EA does nothing new (the existing trade continues to manage itself).

The stop loss and take profit are ATR-driven, not fixed-pip. SLMultiplier=1.0 and TPMultiplier=2.0 mean SL = ATR(14) * 1.0 and TP = ATR(14) * 2.0, giving a fixed 1:2 reward-to-risk at the moment of entry regardless of where ATR is sitting. A 50-point ATR pair gets a 50/100 stop/target; a 200-point ATR pair gets a 200/400 stop/target. Lot sizing is risk-based: CalculateLotSize() divides RiskPercent * balance by stopLossPoints * tickValue, then rounds down to the broker's SYMBOL_VOLUME_STEP and clamps inside SYMBOL_VOLUME_MIN / SYMBOL_VOLUME_MAX. With RiskPercent=1.0 on a $100 account, a 100-point SL would size to roughly 0.01 lot on a $10/pip pair and 0.10 lot on a $1/pip pair.

The trailing stop is mechanical and runs from ManagePositions() on every tick. After the position has moved TrailingStart=15 points in profit, the EA shifts the stop by TrailingStep=5 points behind the new bid (for longs) or above the new ask (for shorts). The check is newSL > currentSL for buys and newSL < currentSL || currentSL == 0 for sells, so the ratchet is unidirectional and will never move the stop against the position. The trailing stop only modifies the SL; it does not touch TP. A position can still run to its original 2x ATR target while the stop is being ratcheted behind it.

The risk stack is conservative for a 25-input EA. IsSafeToTrade() runs four gates before any signal evaluation: equity must stay above MinEquityPercent=95% of the starting balance (otherwise the EA calls CloseAllPositions() and prints a hard stop), realized daily P&L must not have hit MaxDailyLossPercent=3%, trades opened today must be below MaxTradesPerDay=5, and the active session must contain the current server hour. If any gate fails, the EA returns false and the tick is a no-op. There is no kill switch or recovery — once the daily loss trips or the equity floor trips, the EA flattens and sits out for the rest of the day (the counters reset at the next date rollover in UpdateDailyCounters()).

The session filter is a simple hour-of-day window. SessionStartHour=2 and SessionEndHour=16 define the tradeable band (server time), which the source comments as "London session start" to "New York session end." IsInTradingSession() correctly handles a window that crosses midnight via an OR branch, although the defaults do not require that branch. The news filter is a simplification — IsNewsTime() returns true when the current time is within 30 minutes of 08:00 or 13:00 server time, which the source labels as the London and New York opens. It is not connected to an economic calendar feed; high-impact data releases outside those two fixed windows are not filtered, and the windows themselves are timezone-sensitive to the broker's server clock.

The CloseAllPositions(), ClosePendingOrders(), and trailing updates all build their own MqlTradeRequest / MqlTradeResult structures inline and check result.retcode == TRADE_RETCODE_DONE before logging success or the human-readable error string from GetTradeErrorDescription(). Three retry helpers (TryClose_EX16062, TryClosePartial_EX16062, TryModify_EX16062) are also defined for wrapper-based operations with 200ms backoff on requotes, timeouts, and stale prices — but they are not called from OnTick() or from the close / modify / partial-close paths above. They are dormant wrappers and would only matter if a future code path invoked them; for now the only paths that touch the broker are the inline OrderSend() calls in OpenBuyOrder(), OpenSellOrder(), CloseAllPositions(), ClosePendingOrders(), and TrailingStop().

The OnTester() hook is not implemented in this source — no custom fitness function is present. The strategy is meant to be optimized via MetaTrader's standard parameter sweep over the indicator periods and risk percentages, not a custom objective. The fill policy is the broker's default, since the EA never sets request.type_filling explicitly. On netting accounts the EA may issue market orders with no type_filling override, which works on ECN and classic hedging servers but can fail on some exchange-style symbols that require ORDER_FILLING_FOK or ORDER_FILLING_IOC.

For live deployment, the EA is hard-coded to one position at a time on _Symbol, so a $100 minimum-deposit account with RiskPercent=1.0 is workable, although the source comment "max 2% for $100 account" suggests the developer expects a 1-2% risk band on the smallest accounts. The trailing stop and ATR-driven SL scale with volatility, so on a quiet range-bound XAUUSD session the stops will be tight, and during a news-driven spike the stops will widen on the next entry. The adaptive sensitivity knob will also ratchet the threshold down after a 2-loss streak, which means losing days will produce more signals, not fewer — a deliberate bias toward "try again sooner." The two retry helper functions are present but unused, so any session-level slippage handling beyond the inline OrderSend() checks has to be added externally.

Strategy Deep Dive

EX16062 runs a five-signal weighted scoring model on every tick: AMA(14) crossover, RSI(14) with volatility-shifted 30/70 bands, MACD(12,26,9) crossover, Stochastic(14,3) zone reading, and an SMA(5)-vs-SMA(20) trend filter. The combined signal must beat +/-0.5 * adaptiveSensitivity to fire, and that sensitivity climbs by 0.1 after three consecutive wins and drops by 0.1 after two consecutive losses — clamped to [0.3, 1.0]. The risk stack (IsSafeToTrade()) gates everything: equity must stay above 95% of the initial balance, daily P&L must not exceed 3% of balance, today's trade count must be under 5, the current server hour must fall inside the 02:00–16:00 session window, and the time must not be within 30 minutes of 08:00 or 13:00 (the simplified news-avoidance check). On a fresh signal that conflicts with the open position, the EA first deletes pending orders, then closes the opposite position, then opens the new direction. The trailing stop activates at 15 points of profit and ratchets the stop by 5 points behind bid/ask on every favorable tick.

Entry Signal

The EA opens a long when the weighted vote of five adaptive indicators (AMA crossover, volatility-adjusted RSI, MACD crossover, Stochastic extremes, and SMA(5) vs SMA(20) trend) exceeds +0.5 * adaptiveSensitivity and a short when the sum falls below -0.5 * adaptiveSensitivity. The AMA carries a 0.4 weight, MACD and RSI each 0.2, and Stochastic and the SMA trend each 0.1. Single position per symbol: a conflicting signal first closes the opposing position and deletes pending orders, then opens the new direction.

Exit Signal

Exit fires on the opposite-direction signal from GetMarketSignal() — when the weighted sum crosses zero with a fresh cross, the EA closes the open position and flips. The trailing stop activates at TrailingStart=15 points of profit and ratchets the stop by TrailingStep=5 points behind price on every tick that prints new favorable price action. If the equity protection trips (below MinEquityPercent=95% of initial balance) or the daily loss limit (3%) trips, IsSafeToTrade() returns false and CloseAllPositions() flattens the account.

Stop Loss

Stop loss is ATR-driven at SLMultiplier=1.0 of the ATR(14) reading at entry, so the SL distance scales with the broker's current volatility. A 100-point ATR pair gets a 100-point SL; a 50-point ATR pair gets a 50-point SL. Trailing stop is independent of the initial SL and only kicks in after 15 points of profit, ratcheting the stop by 5 points per favorable tick.

Take Profit

Take profit is set to SL * TPMultiplier = 1.0 * 2.0 = 2.0 * ATR(14), giving a fixed 1:2 reward-to-risk at the moment of entry. TP is not trailed, scaled, or partial-closed in the source — once the position is open, TP is a static price level until the trailing stop or an opposite-signal exit fires.

Best For

EX16062 is sized for a $100 minimum-deposit account with RiskPercent=1.0 capped at 2% on small balances, and MaxTradesPerDay=5 keeps the worst-day damage bounded. Run it on a low-spread ECN broker with XAUUSD (or any FX major) on M5 or H1, since the ATR-based SL/TP and the volatility-adjusted RSI both need accurate tick-by-tick spread data. The default 02:00–16:00 server-time session window covers the London open through the New York close, so align the broker's GMT offset so that the actual FX session lines up with the EA's local hours. The 95% equity floor and 3% daily loss cap make it suitable for prop-firm style or low-DD mandates, but the adaptive sensitivity ratchets DOWN (loosens) after losing streaks, which means losing days will produce more signals — backtest before trusting the 0.5 sensitivity default in trending-pause environments.

Strategy Logic

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

Family: Trend Magic: 22216062 Version: 2.00

BRIEF: Adaptive multi-confirmation EA using AMA, RSI, MACD, Stochastic and ATR with self-tuning sensitivity. Entry requires confluence of multiple adaptive indicators. Includes session filter, news avoidance, daily loss limits and equity protection. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • IsSafeToTrade()
  • IsInTradingSession()
  • IsNewsTime()
  • GetMarketSignal()
  • GetSMA()
  • UpdateAdaptiveSensitivity()
  • CalculateLotSize()
  • OpenBuyOrder()
  • OpenSellOrder()
  • ManagePositions()
  • TrailingStop()
  • UpdateDailyCounters()
  • ...and 6 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (25 total across 5 groups):

  • [=== Identity ===] InpMagic = 22216062 // Magic number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_16062" // Trade comment
  • [=== Risk Management ===] RiskPercent = 1.0 // Risk percentage per trade (max 2% for $100 account)
  • [=== Risk Management ===] MaxDailyLossPercent = 3.0 // Maximum daily loss percentage
  • [=== Risk Management ===] MaxTradesPerDay = 5 // Maximum trades per day
  • [=== Risk Management ===] MinEquityPercent = 95.0 // Stop trading if equity falls below this % of initial balance
  • [=== Sessions Management ===] UseSessionFilter = true // Use trading session filter
  • [=== Sessions Management ===] SessionStartHour = 2 // London session start (server time)
  • [=== Sessions Management ===] SessionEndHour = 16 // New York session end (server time)
  • [=== Sessions Management ===] AvoidNews = true // Avoid trading during news
  • [=== Adaptive Indicators ===] AMA_Period = 14 // Adaptive Moving Average period
  • [=== Adaptive Indicators ===] AMA_FastEMA = 2 // Fast EMA for AMA
  • [=== Adaptive Indicators ===] AMA_SlowEMA = 30 // Slow EMA for AMA
  • [=== Adaptive Indicators ===] RSI_Period = 14 // RSI period for adaptive calculation
  • [=== Adaptive Indicators ===] MACD_Fast = 12 // MACD fast period
  • [=== Adaptive Indicators ===] MACD_Slow = 26 // MACD slow period
  • [=== Adaptive Indicators ===] MACD_Signal = 9 // MACD signal period
  • [=== Adaptive Indicators ===] Stoch_K = 14 // Stochastic %K period
  • [=== Adaptive Indicators ===] Stoch_D = 3 // Stochastic %D period
  • [=== Adaptive Indicators ===] ATR_Period = 14 // ATR period for volatility
  • [=== Trade Management ===] TPMultiplier = 2.0 // Take Profit multiplier (conservative 1:2 RR)
  • [=== Trade Management ===] SLMultiplier = 1.0 // Stop Loss multiplier
  • [=== Trade Management ===] UseTrailingStop = true // Use trailing stop
  • [=== Trade Management ===] TrailingStart = 15.0 // Trailing start in points
  • [=== Trade Management ===] TrailingStep = 5.0 // Trailing step in points
Pseudocode
// Pipsgrowth EX16062 Trend — Execution Flow (from source analysis)
// Family: Trend
// Adaptive multi-confirmation EA using AMA, RSI, MACD, Stochastic and ATR with self-tuning sensitivity. Entry requires confluence of multiple adaptive indicators. Includes session filter, news avoidance, daily loss limits and equity protection. 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
InpMagic22216062Magic number
InpTradeComment"Psgrowth.com Expert_16062"Trade comment
RiskPercent1.0Risk percentage per trade (max 2% for $100 account)
MaxDailyLossPercent3.0Maximum daily loss percentage
MaxTradesPerDay5Maximum trades per day
MinEquityPercent95.0Stop trading if equity falls below this % of initial balance
UseSessionFiltertrueUse trading session filter
SessionStartHour2London session start (server time)
SessionEndHour16New York session end (server time)
AvoidNewstrueAvoid trading during news
AMA_Period14Adaptive Moving Average period
AMA_FastEMA2Fast EMA for AMA
AMA_SlowEMA30Slow EMA for AMA
RSI_Period14RSI period for adaptive calculation
MACD_Fast12MACD fast period
MACD_Slow26MACD slow period
MACD_Signal9MACD signal period
Stoch_K14Stochastic %K period
Stoch_D3Stochastic %D period
ATR_Period14ATR period for volatility
TPMultiplier2.0Take Profit multiplier (conservative 1:2 RR)
SLMultiplier1.0Stop Loss multiplier
UseTrailingStoptrueUse trailing stop
TrailingStart15.0Trailing start in points
TrailingStep5.0Trailing step in points
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16062.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16062 P — Adaptive multi-confirmation EA, full 12-layer stack."
#include <Trade\Trade.mqh>

// Input Parameters
input group "=== Identity ==="
input int    InpMagic         = 22216062;          // Magic number
input string InpTradeComment  = "Psgrowth.com Expert_16062"; // Trade comment

input group "=== Risk Management ==="
input double RiskPercent = 1.0;                    // Risk percentage per trade (max 2% for $100 account)
input double MaxDailyLossPercent = 3.0;           // Maximum daily loss percentage
input int MaxTradesPerDay = 5;                    // Maximum trades per day
input double MinEquityPercent = 95.0;             // Stop trading if equity falls below this % of initial balance

input group "=== Sessions Management ==="
input bool UseSessionFilter = true;               // Use trading session filter
input int SessionStartHour = 2;                   // London session start (server time)
input int SessionEndHour = 16;                    // New York session end (server time)
input bool AvoidNews = true;                      // Avoid trading during news

input group "=== Adaptive Indicators ==="
input int AMA_Period = 14;                        // Adaptive Moving Average period
input int AMA_FastEMA = 2;                        // Fast EMA for AMA
input int AMA_SlowEMA = 30;                       // Slow EMA for AMA
input int RSI_Period = 14;                        // RSI period for adaptive calculation
input int MACD_Fast = 12;                         // MACD fast period
input int MACD_Slow = 26;                         // MACD slow period
input int MACD_Signal = 9;                        // MACD signal period
input int Stoch_K = 14;                           // Stochastic %K period
input int Stoch_D = 3;                            // Stochastic %D period
input int ATR_Period = 14;                        // ATR period for volatility

input group "=== Trade Management ==="
input double TPMultiplier = 2.0;                  // Take Profit multiplier (conservative 1:2 RR)
input double SLMultiplier = 1.0;                  // Stop Loss multiplier
input bool UseTrailingStop = true;                // Use trailing stop
input double TrailingStart = 15.0;                // Trailing start in points
input double TrailingStep = 5.0;                  // Trailing step in points

// Global Variables
int amaHandle, rsiHandle, macdHandle, stochHandle, atrHandle;
double initialBalance;
int tradesOpenedToday = 0;
datetime lastTradeDate = 0;
double dailyPnL = 0.0;
double adaptiveSensitivity = 0.5; // Self-tuning sensitivity

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Initialize indicators
    amaHandle = iAMA(_Symbol, PERIOD_CURRENT, AMA_Period, AMA_FastEMA, AMA_SlowEMA, 0, PRICE_CLOSE);
    rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, RSI_Period, PRICE_CLOSE);
    macdHandle = iMACD(_Symbol, PERIOD_CURRENT, MACD_Fast, MACD_Slow, MACD_Signal, PRICE_CLOSE);

Full source code available on download

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

Tags:ex16062trendpipsgrowthfreemt5xauusd

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