P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX18068 TrendFollow

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

Pipsgrowth.com EX18068 T3Trend — Regime-gated T3 (Tillson) slope trend EA, full 12-layer stack.

Overview

Pipsgrowth EX18068 T3Trend is a single-position trend follower that builds its signal from a Tillson T3 moving average computed entirely in software. Rather than loading a custom indicator or calling iCustom, the EA spins up six identical-period EMA handles in OnInit and runs the remaining smoothing passes inside CalcT3Series() / CascadeEMA(). The T3 itself is the standard Tillson construction: six nested EMAs of close, blended with the volume factor v (InpT3Coeff, default 0.7) using the four Tillson coefficients c1 = -v^3, c2 = 3v^2 + 3v^3, c3 = -6v^2 - 3v - 3v^3, c4 = 1 + 3v + v^3 + 3v^2. All six EMAs share the same period input (InpT3Period, default 14), so the user-facing knobs are just the period and the volume factor. The cascade uses a 200-bar working window (T3_LOOKUP=200), which is well past the warm-up required for the sixth EMA to stabilize. Because the EA reads iMA handles for the first pass and then does the rest in code, the chart and the strategy tester produce identical T3 values, and there is no .mqh or .ex5 to distribute alongside the .mq5.

The signal is the slope of the T3, not its value. T3Slope() runs an ordinary-least-squares regression over the last three T3 points (T3_SLOPE_BARS=3) and returns the regression coefficient. Signal() combines that slope with two additional checks on the closed bar (shift=1): a long is armed only when close is above the current T3, the prior T3 is below the current one (i.e. the T3 is rising bar-on-bar), and the regression slope is positive. Shorts mirror the same three conditions with the signs flipped. The monotonicity test is what separates EX18068 from a raw slope-sign-flip system: the EA is not satisfied with a momentary uptick, it wants the T3 itself to be climbing. Confidence is reported but not gated on — it is the magnitude of the slope, normalized by the current ATR(14) and capped at 100, returned alongside the direction so external dashboards and the strategy tester can rank trades, but a low confidence score does not block a valid directional match.

A six-state regime classifier runs on every tick before any entry logic is touched. CalcRegime() reads ADX(14), ATR(14) over a 100-bar window, and Bollinger Bands(20, 2.0), and ranks the live ATR against its own 100-bar distribution and the live band-width against its own 100-bar distribution via Percentile(). The state map is: ADX <= 15 forces REG_CHOPPY, ADX >= 25 with either percentile >= 80 is REG_BREAKOUT, ADX >= 25 alone is REG_STRONG_TREND, ADX >= 20 is REG_WEAK_TREND, ATR-percentile <= 20 is REG_COMPRESS, the same percentile or band-width test with lower ADX is REG_EXPAND, and the residue is REG_RANGE. CHOPPY is the only state that triggers a hard no-trade veto through the rest of the pipeline. The other five are diagnostic — they get stamped on each tick for the journal and for the OnTester pass, but the T3 slope is the only directional input that opens trades.

Confirm() stacks four gates on top of an allowed regime. With InpRequireHTF=true (default), the last closed H1 candle must be on the same side of an H1 EMA(21) (hHTF_EMA, period HTF_T3_PERIOD=21) as the proposed direction. With InpRequireSession=true, the broker-server hour must be inside 7-21 (SESSION_START_HOUR=7, SESSION_END_HOUR=21), a 14-hour window. The spread gate compares the current spread to a rolling 50-bar EMA of spreads (g_spreadAvg) maintained inside OnTick with alpha = 0.05, and rejects entries when the live spread is more than 3.0x that average (MAX_SPREAD_MULT=3.0). Finally, the reward-to-risk ratio is computed from SL_ATR_MULT * ATR(14) for the stop and TP_ATR_MULT * ATR(14) for the target, and the trade is refused if the resulting ratio falls below InpMinRR=1.5. With the hard-coded 2.0 / 4.0 ratio (SL = 2.0 x ATR, TP = 4.0 x ATR, R:R = 2.0), the InpMinRR check is effectively a sanity gate rather than a real constraint.

The capital allocation cap is the EA's most distinctive design choice and the lever most worth understanding before going live. EffCapital() returns min(InpCapAmount, account equity) minus today's realized P&L, but only when InpCapAmount is greater than zero. The default value of 0.0 disables the cap entirely, so out of the box the EA sizes off the full account equity. The cap turns the system from "size off whatever is in the account" into "treat the account as a $X sandbox" — set InpCapAmount=1000 and the EA will never risk more than it thinks it has 1000 dollars of, regardless of how much the account actually holds. InpCapFloor (default $50) is a separate kill: when EffCapital() drops below that level, NoTrade() returns true with reason "capital_below_floor" and the EA stops opening new positions, which is how the EA defends against a runaway losing streak on a capped account. All daily-loss and weekly-loss math is also taken from EffCapital(): a 3% daily loss limit (InpDailyLossPct=3.0) and a 9% weekly loss limit (InpWeeklyLossPct=9.0) halt entries the moment those thresholds are breached in closed-trade P&L.

Sizing rides on the same capital figure. CalcLot() takes EffCapital() * min(InpRiskPercent=0.5%, KELLY_CAP_PCT=5.0%) as the dollar-at-risk budget, then divides by the per-lot risk computed from slDistPrice * (TickValue / TickSize). The resulting lot is rounded down to the broker's LotsStep, floored at LotsMin, capped at LotsMax, and refused outright if OrderCalcMargin says free margin cannot cover the resulting position. InpMaxConcurrent=1 and InpMaxSymbolPos=1 are both hard-coded to 1, so the EA is strictly a one-trade-at-a-time, one-symbol-at-a-time system — running a second chart of XAUUSD with the same magic will be rejected by CountSymbolPositions().

ManageExits() runs on every tick before the entry pipeline, so the exits are always up to date before the next signal is even considered. When unrealized profit reaches 1R (the initial SL distance), the stop is ratcheted to entry + 50 points for longs and entry - 50 points for shorts (BE_OFFSET_POINTS=50), and 50% of the position is closed at the same trigger (PARTIAL_AT_R=1.0, PARTIAL_RATIO=0.5), provided the residual volume is at least 2 * LotsStep. The trailing stop runs continuously: at every tick the EA recomputes the trail at 2.5x ATR(14) (TRAIL_ATR_MULT=2.5) from the current bid/ask, and only updates the stop if the new value is at least 30 points (TRAIL_STEP_POINTS=30) inside the previous one, which avoids spamming the broker with re-modify calls in low-volatility drift. An opposite T3 slope signal closes the position outright via the Signal() function, and a 240-bar time stop (MAX_BARS_IN_TRADE=240) closes anything still open at roughly 20 hours on M5 or 10 days on H1. Order execution goes through three-attempt retry helpers — TryClose_EX18068, TryClosePartial_EX18068, TryModify_EX18068 — that back off 200ms on close-style failures (requote, timeout, price-off, price-changed) and 100ms on modify-style failures (requote, timeout only), which is the right cadence for a busy ECN gold book.

InpDryRun defaults to true, which means the EA logs every intended BUY / SELL / modify / close to the journal as DRYRUN lines but does not place orders until you flip that input to false. InpKillSwitch (default false) is the second safety input: when toggled true, both new entries and most management actions stop. OnTester() ranks optimization passes by (net profit * profit_factor) / (1 + balance_dd_percent / 100) and returns 0 for any test with fewer than 30 trades, so the optimizer only grades runs that have a statistically meaningful sample size. EX18068 is built for traders who want a single, methodical T3 trend position on gold during the active part of the day, sized as a 0.5% slice of effective capital, with the capital cap as the lever that turns a gold-trend EA into a sandbox-sized, equity-isolated test bed.

Strategy Deep Dive

On each tick the EA first refreshes its spread sample into a 50-bar rolling EMA, then CalcRegime() reads ADX(14), ATR(14) over a 100-bar window, and Bollinger(20, 2.0) band-width to assign one of six market states — CHOPPY blocks entries outright, the other five let the pipeline run. ManageExits() walks every open position, applying the 1R break-even with a 50-point buffer, the 50% partial at 1R, the 2.5x ATR(14) forward-only trail (ratcheting only when at least 30 points better), the opposite-signal close, and the 240-bar M5 time stop. The signal core is CalcT3Series() — six identical-period EMAs combined by the Tillson volume factor in software — and T3Slope() runs a 3-bar linear-regression slope on the result, requiring close, T3 value, prior T3 value and slope to be mutually consistent on the closed bar. Confirm() layers the H1 EMA(21) trend gate, the 7-21 server-hour window, the 3.0x rolling-spread cap, and the 1.5 minimum R:R check on top, and OpenMarket() sizes the trade to 0.5% of effective capital (capped at 5% by the Kelly ceiling) with an OrderCalcMargin pre-send check, then ships the order through a three-attempt retry helper that backs off 200ms or 100ms depending on the failure class.

Entry Signal

A long is armed when the last closed candle closes above the inlined Tillson T3, the prior T3 value is below the current one (monotonic rise), and a 3-bar linear-regression slope of the T3 itself is positive. Shorts mirror the same three conditions with signs flipped. The signal is only allowed to fire after CalcRegime() rules out CHOPPY (ADX <= 15) and after Confirm() passes the H1 EMA(21) trend agreement, the 7-21 server-hour window, the 3.0x rolling-spread cap, and the minimum 1.5 R:R check.

Exit Signal

Each open position walks through four exit paths in ManageExits(). At 1R of unrealized profit, the stop ratchets to entry plus a 50-point buffer and 50% of the position is closed (the partial only fires when residual volume still satisfies 2 * LotsStep). A 2.5x ATR(14) forward-only trail then tracks the bid or ask, updating only when the new stop is at least 30 points better than the prior one. An opposite T3 slope signal closes the position outright, and a 240-bar time stop closes any trade still open at the end of that window.

Stop Loss

The initial stop is 2.0x ATR(14) below entry for longs and 2.0x ATR(14) above entry for shorts, with the broker's StopsLevel respected via RespectStops(). Once price moves 1R in favor, the stop is ratcheted to entry + 50 points for longs (entry - 50 for shorts), and a 2.5x ATR(14) forward-only trail then takes over, advancing in steps of at least 30 points.

Take Profit

The initial target is 4.0x ATR(14) above entry for longs and 4.0x ATR(14) below entry for shorts, which gives a fixed 1:2 reward-to-risk envelope relative to the 2.0x ATR(14) stop. The 1R break-even + 50-point offset plus 50% partial close at the same 1R threshold is the de-facto mid-trade TP step, and the 2.5x ATR(14) trailing stop usually closes the remainder before the original TP fires on a sustained move.

Best For

Built for traders running a single XAUUSD chart at M5 or H1 with a $100 minimum deposit and a MEDIUM risk tolerance, ideally on an ECN or low-spread raw-spread account — the 3.0x rolling-spread cap and the broker's StopsLevel filter do the bulk of the broker-quality work, but tighter spreads mean more 1R partial fills. The 7-21 server-hour window covers the London and New York sessions, and is when the T3 cascade and the H1 EMA(21) confirmation produce the cleanest signals. Treat InpMaxConcurrent=1 and InpMaxSymbolPos=1 as a hard rule: do not run a second chart of XAUUSD or any other symbol with this magic, and remember that InpDryRun defaults to true — flip it to false before going live.

Strategy Logic

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

Family: TrendFollow Magic: 22218068 Version: 2.00

BRIEF: T3 (Tillson) is inlined as 6 nested EMAs with volume factor v. Signal = T3 slope on closed bar (shift=1). Entries gated by REGIME (ADX+ATRpctile+BBwidth). CONFIRM gates: HTF trend, session, min R/R, spread. CAPITAL ALLOCATION CAP drives all sizing and daily-loss math. Risk is per-trade % of effective_capital with ATR-based SL. Exits: BE + partial + ATR-trail + opposite-signal + max bars. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • EffCapital()
  • TodayRealizedPnL()
  • WeekRealizedPnL()
  • CountMyPositions()
  • CountSymbolPositions()
  • NormalizePrice()
  • RespectStops()
  • ClampVolume()
  • CopyBufSafe()
  • CopiedReset()
  • CalcT3Series()
  • CascadeEMA()
  • ...and 16 more

INTERNAL CONSTANTS (34 total):

  • T3_PERIOD_DEF = 14 // T3 EMA period (all 6 EMAs share it)
  • T3_VOLUME_FACTOR = 0.7 // Tillson volume factor v (0..1)
  • T3_SLOPE_BARS = 3 // bars used for slope regression
  • ADX_PERIOD = 14 // ADX period
  • ADX_STRONG_TREND = 25 // ADX >= this = StrongTrend
  • ADX_WEAK_TREND = 20 // ADX >= this = WeakTrend
  • ADX_CHOPPY = 15 // ADX <= this = Choppy
  • ATR_PERIOD = 14 // ATR period for SL/trail
  • ATR_PCTILE_LOOKBACK = 100 // bars for ATR percentile
  • ATR_PCTILE_EXPAND = 80 // percentile >= this = Expand
  • ATR_PCTILE_COMPRESS = 20 // percentile <= this = Compress
  • BB_PERIOD = 20 // Bollinger period
  • BB_DEVIATION = 2.0 // Bollinger stddev
  • BBW_LOOKBACK = 100 // bars for BB width percentile
  • BBW_EXPAND_PCT = 80 // BBW percentile >= = trend/breakout
  • ...and 19 more

INPUT PARAMETERS (21 total across 7 groups):

  • [=== Identity ===] InpMagicNumber = 22218068 // Magic number (unique id)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_18068" // Trade comment
  • [=== Identity ===] InpSlippagePts = 30 // Slippage cap (points)
  • [=== Identity ===] InpDryRun = true // Dry-run (no real sends)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% effective capital)
  • [=== Risk & Sizing ===] InpDailyLossPct = 3.0 // Max daily loss (% effective capital)
  • [=== Risk & Sizing ===] InpWeeklyLossPct = 9.0 // Max weekly loss (% effective capital)
  • [=== Risk & Sizing ===] InpMaxConcurrent = 1 // Max concurrent trades (all symbols)
  • [=== Risk & Sizing ===] InpMaxSymbolPos = 1 // Max positions per symbol
  • [=== Capital Allocation Cap ===] InpCapAmount = 0.0 // Capital cap amount ($ real money)
  • [=== Capital Allocation Cap ===] InpCapFloor = 50.0 // Floor below which no new entries ($)
  • [=== Signal (T3) ===] InpT3Period = T3_PERIOD_DEF // T3 period (EMA nesting)
  • [=== Signal (T3) ===] InpT3Coeff = T3_VOLUME_FACTOR // T3 volume factor v (0..1)
  • [=== Regime / Confirm ===] InpRequireHTF = true // Require HTF trend agreement
  • [=== Regime / Confirm ===] InpRequireSession = true // Require trading-session window
  • [=== Regime / Confirm ===] InpMinRR = 1.5 // Minimum reward:risk ratio
  • [=== Exit / Manage ===] InpUseBreakEven = true // Use break-even
  • [=== Exit / Manage ===] InpUsePartial = true // Use partial TP
  • [=== Exit / Manage ===] InpUseATRTrail = true // Use ATR trailing stop
  • [=== Exit / Manage ===] InpExitOnReverse = true // Exit on opposite signal
  • [=== Safety ===] InpKillSwitch = false // Kill switch (halt everything)
Pseudocode
// Pipsgrowth EX18068 TrendFollow — Execution Flow (from source analysis)
// Family: TrendFollow
// T3 (Tillson) is inlined as 6 nested EMAs with volume factor v. Signal = T3 slope on closed bar (shift=1). Entries gated by REGIME (ADX+ATRpctile+BBwidth). CONFIRM gates: HTF trend, session, min R/R, spread. CAPITAL ALLOCATION CAP drives all sizing and daily-loss math. Risk is per-trade % of effective_capital with ATR-based SL. Exits: BE + partial + ATR-trail + opposite-signal + max bars. 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
InpMagicNumber22218068Magic number (unique id)
InpTradeComment"Psgrowth.com Expert_18068"Trade comment
InpSlippagePts30Slippage cap (points)
InpDryRuntrueDry-run (no real sends)
InpRiskPercent0.5Risk per trade (% effective capital)
InpDailyLossPct3.0Max daily loss (% effective capital)
InpWeeklyLossPct9.0Max weekly loss (% effective capital)
InpMaxConcurrent1Max concurrent trades (all symbols)
InpMaxSymbolPos1Max positions per symbol
InpCapAmount0.0Capital cap amount ($ real money)
InpCapFloor50.0Floor below which no new entries ($)
InpT3PeriodT3_PERIOD_DEFT3 period (EMA nesting)
InpT3CoeffT3_VOLUME_FACTORT3 volume factor v (0..1)
InpRequireHTFtrueRequire HTF trend agreement
InpRequireSessiontrueRequire trading-session window
InpMinRR1.5Minimum reward:risk ratio
InpUseBreakEventrueUse break-even
InpUsePartialtrueUse partial TP
InpUseATRTrailtrueUse ATR trailing stop
InpExitOnReversetrueExit on opposite signal
InpKillSwitchfalseKill switch (halt everything)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX18068.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX18068 T3Trend — Regime-gated T3 (Tillson) slope trend EA, full 12-layer stack."

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

CTrade         trade;
CPositionInfo  position;
CSymbolInfo    sym;
CAccountInfo   acc;

//====================== TUNABLE #define CONSTANTS ===================
#define T3_PERIOD_DEF       14          // T3 EMA period (all 6 EMAs share it)
#define T3_VOLUME_FACTOR    0.7         // Tillson volume factor v (0..1)
#define T3_SLOPE_BARS       3           // bars used for slope regression
#define ADX_PERIOD          14          // ADX period
#define ADX_STRONG_TREND    25          // ADX >= this = StrongTrend
#define ADX_WEAK_TREND      20          // ADX >= this = WeakTrend
#define ADX_CHOPPY          15          // ADX <= this = Choppy
#define ATR_PERIOD          14          // ATR period for SL/trail
#define ATR_PCTILE_LOOKBACK 100         // bars for ATR percentile
#define ATR_PCTILE_EXPAND   80          // percentile >= this = Expand
#define ATR_PCTILE_COMPRESS 20          // percentile <= this = Compress
#define BB_PERIOD           20          // Bollinger period
#define BB_DEVIATION        2.0         // Bollinger stddev
#define BBW_LOOKBACK        100         // bars for BB width percentile
#define BBW_EXPAND_PCT      80          // BBW percentile >= = trend/breakout
#define HTF_TF              PERIOD_H1   // higher-timeframe trend filter
#define HTF_T3_PERIOD       21          // HTF trend EMA period
#define SL_ATR_MULT         2.0         // SL = SL_ATR_MULT * ATR(points)
#define TP_ATR_MULT         4.0         // TP initial = TP_ATR_MULT * ATR (R:R 2)
#define BE_TRIGGER_R        1.0         // BE trigger at 1R
#define BE_OFFSET_POINTS    50          // BE lock-in offset
#define PARTIAL_AT_R        1.0         // partial close 50% at 1R
#define PARTIAL_RATIO       0.5         // fraction to close
#define TRAIL_ATR_MULT      2.5         // trail distance = TRAIL_ATR_MULT * ATR
#define TRAIL_STEP_POINTS   30          // trail min step
#define MAX_BARS_IN_TRADE   240         // time exit after N bars
#define SESSION_START_HOUR  7           // broker server time
#define SESSION_END_HOUR    21          // broker server time
#define MAX_SPREAD_MULT     3.0         // spread cap = rolling avg * mult
#define SPREAD_AVG_BARS     50          // bars for rolling spread avg
#define COOLDOWN_BARS       5           // bars of cooldown after a loss
#define PYRAMID_MAX_LEVELS  0           // pyramid OFF (hard-coded; spec default OFF)
#define NEWS_WINDOW_MIN     0           // manual news window minutes (0=off)
#define KELLY_CAP_PCT       5.0         // never size > 5% effective capital risk
//====================================================================

//------------------- INPUTS (grouped; 22 total) ---------------------
input group "=== Identity ==="
input int      InpMagicNumber    = 22218068;                          // Magic number (unique id)
input string   InpTradeComment   = "Psgrowth.com Expert_18068";       // Trade comment
input int      InpSlippagePts    = 30;                               // Slippage cap (points)
input bool     InpDryRun         = true;                             // Dry-run (no real sends)

Full source code available on download

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

Tags:ex18068trendfollowpipsgrowthfreemt5xauusd

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