P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16076 Trend

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

Pipsgrowth.com EX16076 Smart Trend Follower — MA + Stochastic trend follower, full 12-layer stack.

Overview

EX16076 is a smart trend follower that gives you two ways to read momentum on a single chart, then layers additional entries into a basket whose take-profit and stop-loss are calculated from a volume-weighted break-even price rather than the original entry. Both signal modes run on the chart timeframe — the EA declares M5 as its primary working frame and H1 as supported — and the default signal is a moving-average cross.

The two signal paths are selected by an enum input inJnsSignal called "Signal Type." In eTypeCrossMA mode (the default) GetSignal() pulls the last three values of two simple moving averages — inMAPeriodFast defaulting to 14 and inMAPeriodSlow defaulting to 28, both SMA on close — and watches for a fast-line flip relative to the slow line. A sell signal fires when the fast MA is currently above the slow MA and was below it one bar ago, and a buy signal fires when the fast MA is currently below the slow MA and was above it one bar ago. That crossed-bar pattern is a deliberate two-bar confirmation, not a single-bar touch, so the EA is taking the second candle after a cross, not the crossover bar itself. The buy logic in particular looks for fast MA having just slipped under slow, which is the start of a short-term bearish sequence the EA reads as a continuation entry — a small detail that matters when reviewing backtests, because the open of every trade will sit on the bearish side of the cross.

Switch inJnsSignal to eTypeTrend and the engine changes. Now GetSignal() only reads bar index 1, but adds a third handle — gSTOHandle, an iStochastic with K=10, D=3, slowing=3 on low-high. The MA pair is still required, but the cross itself is not — a buy fires when the fast MA is above the slow MA (trend filter) and the previous bar closed as a bullish candle (open below close) and the Stochastic main line is at or below 30. Sell is the mirror. In other words, trend-following with a buy-the-dip entry: the EA waits for the uptrend to pull back into oversold before pulling the trigger. That makes mode 2 materially different from mode 1 — mode 1 is mechanical cross-follow, mode 2 is pullback-in-trend.

Once a signal arrives, OnTick hands it to manageTrading(). If this is the first position in the direction the signal points to, getLotSize() computes the lot as inLotSize * MathPow(inMultiply, layerIndex) — for the first trade that resolves to the base lot of 0.01 by default. validateLot() snaps the result to the symbol's volume step, clamps to min/max, and CheckMoneyForTrade() confirms free margin before openTrade() sends the market order with magic 22216076 and comment Psgrowth.com Expert_16076. If the direction already has a position open, the EA does not place a new trade immediately. Instead it watches for the price to move against the existing position by inJarakLayer pips — 200 pips by default — and only then opens the next layer. For a buy, the trigger is latestBuyPrice − 200 * Point() >= current ask; for a sell, latestSellPrice + 200 * Point() <= current bid. The same getLotSize() formula means the multiplier still controls how much each subsequent layer scales relative to the first — set inMultiply to 1.0 and every layer is the same 0.01 lot; raise it to 1.5 and layer N becomes 0.01 * 1.5^N.

The trades[2] array stores the running state per side: position count (ttlPos), the most recent buy or sell open price (hargaTA, hargaTB), the cumulative notional value (ttlValue), and the cumulative volume (ttlLot). updateDataTrades() rebuilds this on every signal event by scanning PositionsTotal() for positions matching the current symbol and magic number, picking the highest and lowest entry price on each side, and summing the volume-weighted value. That single struct is what makes the basket TP/SL work.

setTPSL() runs unconditionally on every tick — not just on new-bar events — and is where the EA's exit logic lives. It rebuilds the trades array, then for each side calculates the volume-weighted break-even price as ttlValue / ttlLot — that is, the lot-weighted average entry across every layer in the basket. For buys the take-profit is BEP + inTakeProfit * Point() and the stop-loss is BEP − inStopLoss * Point(). For sells the sign flips. inTakeProfit defaults to 500 (50 pips in five-digit notation), and inStopLoss defaults to 0, meaning the basket has a TP but no SL out of the box. The function then iterates every open position matching the magic number and calls modifTPSL() to push the new TP and SL onto any position whose protection is out of date. Because both values are basket-level rather than per-trade, every layer in the basket closes together once price reaches the BEP-based target. Setting inStopLoss to a positive value installs a basket-level stop too.

A small but real risk control: getLotSize() calls getTotalVolume() and refuses to return any lot if the new trade would push the directional exposure above SYMBOL_VOLUME_LIMIT, and CheckMoneyForTrade() rejects the lot if there isn't enough free margin to cover the required margin. So even with martingale multipliers set aggressively, the broker-level volume cap and the account margin cap are still in the loop.

The EA reads as cleanly as any in the PipsGrowth series: header block, three indicator handles created once in OnInit, two-tier signal generation, basket TP/SL via lot-weighted BEP, layered entries at configurable spacing, the standard Trade.mqh trade object plus three retry helpers — TryClose_EX16076, TryClosePartial_EX16076, TryModify_EX16076 — that wrap CTrade with three attempts on requote, timeout, price-off, or price-changed responses. Those helpers are defined in the source but are not currently invoked from OnTick; the live execution path uses raw OrderSend calls in openTrade() and modifTPSL(). The retry code is in place as a safety net a future revision can wire in without re-architecting the trade flow. The EA uses no session filter, no news filter, no OnTester pass, and no daily P&L circuit breaker — all of the trader's discretionary risk controls are therefore expected to live outside the EA.

Because the default SL is 0 and the basket TP is calculated from the lot-weighted average entry, the EA is structurally designed for a let-the-basket-mature use case — open the first position, accumulate layers as the trade moves against you, and close the whole basket at a fixed pips-from-BEP target once price reverses. The default 200-pip spacing and 1.0 multiplier keep the layered exposure small; raising inMultiply to anything above 1.0 quickly turns the EA into a martingale-style averaging system and the trader should treat the basket stop-loss as the primary risk control, not as a safety net.

Strategy Deep Dive

GetSignal() runs only on new-bar opens, comparing bar 0 and bar 1 of the fast and slow SMAs to detect a two-bar cross — the signal fires on the second bar, not the cross bar. In eTypeTrend mode the function additionally reads bar 1's candle direction and the iStochastic main line, requiring a confirmed trend (fast above slow) plus a pullback (Stochastic ≤ 30 for buys). manageTrading() is then responsible for the position book: first position at the base lot, subsequent layers opened only when price has moved inJarakLayer (200 pips) against the existing side, with the lot size of each layer scaled by MathPow(inMultiply, layerIndex). setTPSL() is the workhorse exit logic — it runs on every tick (not gated by new-bar), recalculates the basket BEP from the live trades[] struct, and rewrites a uniform TP and SL onto every open position. Three retry helpers (TryClose_EX16076, TryClosePartial_EX16076, TryModify_EX16076) wrap CTrade with three attempts on requote/timeout/price-change responses, but the live path uses raw OrderSend so the retries are dormant code.

Entry Signal

Default Cross-MA mode fires when the 14-period SMA flips above or below the 28-period SMA between bar 1 and bar 0 — a two-bar-confirmed cross that takes the second candle, not the cross candle. Trend mode replaces the cross with a buy-the-dip filter: the 14 SMA must be above the 28 SMA, the previous bar must be a bullish candle, and the iStochastic(10,3,3) main line must be at or below 30 for buys or at or above 70 for sells. First-layer lots are the base inLotSize (0.01 default); further layers are gated by price moving inJarakLayer (200 pips) against the existing position and lot-scaled by inMultiply (1.0 default = no scaling).

Exit Signal

setTPSL() runs every tick, recomputes the lot-weighted break-even price for the directional basket (ttlValue / ttlLot), and rewrites the TP and SL on every open position in that basket to the same basket-level values. The take-profit is BEP + inTakeProfit * Point() (500 points = 50 pips default) and the basket stop is BEP − inStopLoss * Point() (0 by default, so no stop). Because the basket protection is uniform, every layer closes together when price reaches the target.

Stop Loss

The per-trade stop-loss is set to zero by default (inStopLoss = 0), so individual layers carry no SL. The basket-level stop — installed on every position in the basket by setTPSL() when inStopLoss > 0 — sits inStopLoss * Point() below the lot-weighted break-even for buys or above it for sells, and triggers all layers out together.

Take Profit

Take-profit is basket-level, not per-trade. setTPSL() calculates BEP + inTakeProfit * Point() (500 points = 50 pips default) for buys and BEP − inTakeProfit * Point() for sells, where BEP is the volume-weighted average of all open entry prices for the basket, then writes the same TP onto every layer in the basket.

Best For

EX16076 is sized for a $100 minimum account on XAUUSD M5 or H1 at medium risk, with a 0.01 base lot and no scaling at the default inMultiply = 1.0. The basket structure (200-pip layered entries, 50-pip basket TP from the volume-weighted BEP, no per-trade SL by default) makes it best suited to traders who want one signal-driven entry direction at a time and accept a let-the-basket-mature exit policy. The eTypeCrossMA mode is the right starting point on M5 during the London and New York active hours when XAUUSD is ranging or trending with clean MA separation; eTypeTrend mode fits pullbacks in established trends and is more selective on entry timing. A low-spread, fast-execution broker is the realistic requirement — there is no spread filter, no session gate, and no news filter, so a high-spread quote or a gap through the news window will hit the basket directly.

Strategy Logic

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

Family: Trend Magic: 22216076 Version: 2.00

BRIEF: Smart trend follower using MA cross or trend-follow mode with Stochastic confirmation. Supports layered entries with configurable spacing; martingale multiplier disabled by default. Includes break-even TP/SL management across all open positions

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • isNewCandle()
  • GetSignal()
  • manageTrading()
  • updateDataTrades()
  • openTrade()
  • setTPSL()
  • modifTPSL()
  • validateLot()
  • getLotSize()
  • getTotalVolume()
  • CheckMoneyForTrade()
  • TryClose_EX16076()
  • ...and 2 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (12 total across 1 groups):

  • [] inMagicNumber = 22216076 // Magic number
  • [] inLotSize = 0.01 // Initial Lot Size
  • [] inMultiply = 1.0 // Multiplier (1.0 = no martingale)
  • [] inJarakLayer = 200 // Jarak Layer (pips)
  • [] inJnsSignal = eTypeCrossMA // Signal Type
  • [] inMAPeriodFast = 14 // MA Fast
  • [] inMAPeriodSlow = 28 // MA Slow
  • [] inSTOKPeriod = 10 // Sto %K
  • [] inSTODPeriod = 3 // Sto %D
  • [] inSTOSlowing = 3 // Slowing
  • [] inTakeProfit = 500 // Take Profit
  • [] inStopLoss = 0 // Stop Loss
Pseudocode
// Pipsgrowth EX16076 Trend — Execution Flow (from source analysis)
// Family: Trend
// Smart trend follower using MA cross or trend-follow mode with Stochastic confirmation. Supports layered entries with configurable spacing; martingale multiplier disabled by default. Includes break-even TP/SL management across all open positions

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
inMagicNumber22216076Magic number
inLotSize0.01Initial Lot Size
inMultiply1.0Multiplier (1.0 = no martingale)
inJarakLayer200Jarak Layer (pips)
inJnsSignaleTypeCrossMASignal Type
inMAPeriodFast14MA Fast
inMAPeriodSlow28MA Slow
inSTOKPeriod10Sto %K
inSTODPeriod3Sto %D
inSTOSlowing3Slowing
inTakeProfit500Take Profit
inStopLoss0Stop Loss
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16076.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16076 Smart Trend Follower — MA + Stochastic trend follower, full 12-layer stack."
#include <Trade\Trade.mqh>


enum enumJnsSignal{
   eTypeCrossMA,  //Cross 2 MA
   eTypeTrend,    //Follow Trend
};

enum enumOrderType{
   eBuy,    //BUY
   eSell,   //SELL
   eNone = 99, //None
};

sinput const string GroupIdentity="";//=== Identity ===
input    int         inMagicNumber  = 22216076;  // Magic number
input    string      InpTradeComment = "Psgrowth.com Expert_16076";
sinput const string GroupTrading="";//=== Trading ===
input    double      inLotSize      = 0.01;     //Initial Lot Size
input    double      inMultiply     = 1.0;      //Multiplier (1.0 = no martingale)
input    int         inJarakLayer   = 200;       //Jarak Layer (pips)

input    enumJnsSignal  inJnsSignal = eTypeCrossMA;    //Signal Type

sinput const string GroupMA="";//=== Moving Average ===
input    int         inMAPeriodFast = 14;       //MA Fast
input    int         inMAPeriodSlow = 28;       //MA Slow

sinput const string GroupStochastic="";//=== Stochastic Oscillator ===
input    int         inSTOKPeriod   = 10;       //Sto %K
input    int         inSTODPeriod   = 3;       //Sto %D
input    int         inSTOSlowing   = 3;       //Slowing

sinput const string GroupExit="";//=== Exit Management ===
input    int         inTakeProfit   = 500;      //Take Profit
input    int         inStopLoss     = 0;       //Stop Loss


struct dataTrades{
   int ttlPos;
   double hargaTA, hargaTB;
   double ttlValue, ttlLot;
   void initial(){
      ttlPos   = 0;
      hargaTA  = hargaTB = 0.0;
      ttlValue = ttlLot = 0.0;
   }
};

int gMAFastHandle, gMASlowHandle, gSTOHandle;
dataTrades trades[2];

double gLotMin, gLotMax,gLotStep, gLotLimit;

//+------------------------------------------------------------------+

Full source code available on download

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

Tags:ex16076trendpipsgrowthfreemt5xauusd

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