P
PipsGrowth
ScalpingOpen Source – Free

Pipsgrowth EX10004 Momentum-Scalper

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

Pipsgrowth.com EX10004 TSI XAUUSD 5M — True Strength Index momentum scalper, full 12-layer stack.

Overview

EX10004 builds its own True Strength Index oscillator from raw close prices and then trades the cross of that oscillator against its own smoothed signal line on the last completed bar of the signal timeframe. The construction lives entirely in the CalcTSI function — there is no iCustom reference and no built-in TSI handle. The implementation grabs a CopyClose series for the configured timeframe, computes point-to-point price deltas, takes the absolute value of those deltas, then runs each series through two back-to-back EMAs with periods 25 and 13. The double-smoothed momentum series is divided by the double-smoothed absolute-momentum series and scaled by 100, producing a normalized oscillator bounded roughly between -100 and +100. A 10-period EMA of the oscillator itself becomes the signal line, and the EA fires when the main line crosses that signal line on bar index 1 — deliberately skipping the still-forming bar to eliminate repaint.

The raw TSI cross is the entry seed, never the entry trigger. Before any order reaches DoSend(), the cross has to clear ConfirmHTF(), a four-gate confirm stack. The first gate requires a higher-timeframe agreement: a H1 EMA(50) is built with iMA on PERIOD_H1, and the prior closed H1 close must sit above the EMA for longs or below it for shorts. The second gate is a same-timeframe EMA stack — fast EMA(50) above slow EMA(100) for longs, the mirror for shorts. The third gate is a RSI(14) filter that blocks longs when RSI is in overbought territory and shorts when it is in oversold territory, defending against chasing the last leg of an exhausted swing. The fourth gate is a minimum 1.2 R:R on the projected SL/TP distances derived from the entry price. All four are AND-ed; failure on any one prints [SKIP-CONFIRM] with the per-gate flag and returns without firing.

Before the confirm stack even runs, the environment has to be tradeable. DetectRegime() produces a 1-to-7 label from three measurements: ADX(14) at the last closed bar, the percentile rank of the current ATR(14) against the last 100 ATR values, and Bollinger Band (20, 2.0) width. The seven states are StrongTrend, WeakTrend, Range, Breakout, Compress, Expand, and Choppy. Entries are blocked outright in Range, Compress, or Choppy, and ManageExits() force-closes every open position the moment the classifier flips to Range or Choppy. This means a position that opens inside a valid regime can still be yanked by the EA the next bar if the environment degrades — a deliberate cost of trading the cross without a regime override.

Position lifecycle runs every tick, independent of the new-bar check. ManageExits() walks the open positions in a six-stage cascade. Regime-change close has the highest priority, followed by opposite-signal close (a fresh bearish TSI cross closes longs, bullish closes shorts), followed by a hard time stop at 80 bars held (DEF_MAX_BARS). After those three exits come the management stages: a partial-TP at 1R closes 50% of the position and tags the ticket with P1 to prevent a second partial; a one-shot break-even at 0.8R moves the stop to open + 0.15R and never ratchets back; and an ATR trailing stop at 2.5× ATR(14) engages after 1R of progress and ratchets only in the favorable direction. The trailing stop writes a new SL on every tick that improves, gated by the broker's SYMBOL_TRADE_STOPS_LEVEL so the modification never lands inside the freeze band.

Risk is hard-capped at the EA level. The lot size comes from CalcLots(), which divides the effective capital by the per-lot risk derived from the ATR-anchored stop distance and the symbol's tick value and tick size, then clamps to the broker's volume step, minimum, and maximum. Effective capital is the smaller of the account equity and InpCapitalCapAmount when that cap is set, with a hard floor of 50 dollars below which NoTrade() blocks every entry. Loss limits are 3% of effective capital per day and 7% per week, both computed from the deal history filtered by the EA's magic and symbol. Three consecutive losses trigger a 30-minute cooldown during which no new entries are taken. The spread gate is 35 points and the slippage allowance is 20 points, and the server-time session window is 7 to 21 — outside that window the EA returns silently and prints nothing.

Two execution flags deserve attention before going live. InpDryRun=true is the default; with that flag on, the EA logs every intended order with the exact SL, TP, and reasoning string but does not place it. The intended behavior is to dry-run the strategy in the strategy tester or a demo account, watch the logs, and only flip InpDryRun to false once the parameters look stable. InpKillSwitch=true is the panic button: with it set, OnTick() returns immediately on the first line and no management, confirm, or send logic runs. Order execution goes through CTrade with the broker's filling mode auto-detected from the symbol's SYMBOL_FILLING_MODE mask, an OrderCalcMargin pre-check before every send, and a one-retry on requote, timeout, price-off, or price-changed retcodes before the order is logged as failed.

The OnTester custom fitness is net * profit_factor / (1 + balance_dd), with a hard floor of 30 trades below which the score is zero and a dd <= 0 guard that treats zero drawdown as one to prevent division by zero. That formula rewards a combination of net profit, profit factor, and a low drawdown, and it heavily penalizes runs with very few trades, which means optimization passes that land on a curve-fitted configuration will score poorly simply by producing too few signals. The seven indicator handles — ATR, ADX, RSI, BB, FastEMA, SlowEMA, and H1 EMA — are all created in OnInit with a 500-bar minimum requirement; if the chart does not have that much history the EA refuses to start.

A practical note for live deployment: the ATR-anchored SL and TP scale automatically with volatility, so on quiet Asian-session hours the stop will be tight and many trades will stop out on routine noise, while on volatile London-open hours the stop will widen and the same nominal risk percentage will produce a larger absolute lot only when the broker's max volume allows it. The regime filter is what bridges that scaling with discipline: it cuts off entries when the ATR-percentile collapses and the ADX is weak, which is exactly the time when a fixed-multiple ATR stop would be most likely to be hit by noise. Set the capital cap (InpCapitalCapAmount) explicitly if you run the EA on a sub-account, because the default of 0 disables the cap and the effective capital reverts to the full account equity.

Strategy Deep Dive

EX10004 builds the True Strength Index inline from CopyClose math: point-to-point momentum, double-EMA smoothed with periods 25 and 13, divided by the double-EMA of absolute momentum and scaled by 100, with a 10-period EMA signal line. The cross is read only on the last closed bar (index 1) of the signal timeframe to avoid repaint. The raw cross is then filtered by ConfirmHTF() — H1 EMA(50) agreement, M5 EMA(50/100) stack, RSI(14) not at extreme, and a 1.2 R:R floor on the ATR-anchored SL/TP. The seven-state DetectRegime() classifier (ADX14 + ATR14 percentile over 100 bars + BB20 width) gates the environment, blocking entries in Range, Compress, or Choppy, and ManageExits() force-closes open positions when the regime degrades to Range or Choppy. ManageExits() itself is a six-stage tick-driven cascade: regime-change close, opposite-signal close, 80-bar time stop, 50% partial-TP at 1R (with P1 tag to prevent re-partial), one-shot break-even at 0.8R that locks open + 0.15R, and an ATR trailing stop at 2.5× ATR14 that engages after 1R of progress and ratchets only favorably, gated by the broker's stops level. Risk is hard-capped at 0.5% of effective capital per trade, with 3% daily and 7% weekly loss limits, a 3-consecutive-loss 30-minute cooldown, a 35-point spread gate, and a 7-21 server-time session window. Two defaults deserve attention: InpDryRun=true is the factory state, so the EA logs every intended order but does not send it until you flip the flag to false; and InpKillSwitch=true halts all logic on the first line of OnTick(). The OnTester custom criterion is net * profit_factor / (1 + balance_dd), with a 30-trade hard floor and a dd <= 0 guard that treats zero drawdown as one.

Entry Signal

Long entry fires when the True Strength Index main line crosses above its 10-period EMA signal line on the last closed bar (index 1) of the configured signal timeframe, with a raw cross check (the InpTSICrossBuf is 0 by default). Short is the mirror cross below. The cross then has to clear four AND-ed gates in ConfirmHTF(): H1 EMA(50) directional agreement, M5 EMA(50/100) stack alignment, RSI(14) not at extreme, and a minimum 1.2 R:R on the projected ATR-anchored SL/TP. The seven-state regime classifier must return a tradable state (StrongTrend, WeakTrend, Breakout, or Expand) — entries are blocked in Range, Compress, or Choppy. One position at a time, one entry per closed bar, sized via CalcLots() at 0.5% of effective capital.

Exit Signal

Exits run as a six-stage cascade in ManageExits() on every tick. First, a regime-change close force-exits every open position the moment the classifier flips to Range or Choppy. Second, an opposite-signal close fires when a fresh bearish TSI cross closes a long, or a fresh bullish cross closes a short. Third, a hard time stop closes anything held longer than 80 bars (DEF_MAX_BARS). Fourth, a partial-TP at 1R closes 50% of the position and tags the ticket P1 to prevent a second partial. Fifth, a one-shot break-even at 0.8R moves the stop to open + 0.15R with no ratchet back. Sixth, an ATR trailing stop at 2.5× ATR(14) engages after 1R of progress and ratchets only in the favorable direction.

Stop Loss

Initial stop is ATR(14) * 1.8 from DEF_SL_MULT, with a hard floor at the broker's SYMBOL_TRADE_STOPS_LEVEL. The stop is anchored to the entry bar and is then managed by three mechanisms: a one-shot break-even at 0.8R profit that moves the stop to open + 0.15R; an ATR trailing stop at 2.5× ATR(14) that engages after 1R of progress and ratchets only in the favorable direction; and a regime-change or opposite-signal forced close that overrides the SL entirely.

Take Profit

Initial TP is ATR(14) * 3.0 from DEF_TP_MULT, giving a 1.67:1 R:R. The TP is then staged by the partial-TP in ManageExits(): at 1R of progress, the EA closes 50% of the position and lets the remainder run under the ATR trailing stop (2.5× ATR, engaged after 1R). The remaining half is governed by the trailing stop, the opposite-signal exit, the regime-change exit, or the 80-bar time stop — whichever fires first. There is no basket TP and no martingale-style re-entry.

Best For

Designed for XAUUSD on M5 (works M5-M15) with an ECN broker that holds XAUUSD spread under 30 points during the 7-21 server-time window. The H1 EMA(50) agreement gate, the ADX regime classifier, and the ATR-scaled stops all favor the London and New York sessions when XAUUSD has directional flow; running this in the Asian session will leave the classifier stuck in Range or Compress and block most entries. Minimum recommended balance: $500 — the 0.5% risk-per-trade sizing only delivers meaningful diversification above that, and the absolute SL distance on XAUUSD in points makes sub-$300 accounts too thin to absorb a normal loss streak. The capital cap input (InpCapitalCapAmount, default 0 = off) is the cleanest way to size the EA to a sub-account: set it to the amount you want the EA to act on, and the effective capital formula will min() that against the account equity. InpDryRun=true is the shipping default, so flip it to false before live trading, and use InpKillSwitch=true as the panic button if a session turns against you.

Strategy Logic

Pipsgrowth EX10004 Momentum-Scalper — Strategy Logic Analysis (from .mq5 source)

Family: Momentum-Scalper Magic: 22210004 Version: 2.00

BRIEF: TSI (True Strength Index) is a double-smoothed momentum oscillator. Long/short trigger = TSI main crosses its EMA signal line in the direction of the slow/fast EMA stack bias, on the last CLOSED bar. Entries gated by ADX/ATR-pct/BB-width regime, HTF-EMA agreement, RSI filter, min R/R, session, spread, daily-loss/capital cap. Exits: BE, partial-TP, ATR- trail, opposite-signal, time, regime-change. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • ATR
  • ADX
  • RSI
  • BB
  • FastEMA
  • SlowEMA
  • HTF_EMA

KEY FUNCTIONS:

  • SymPoint()
  • SymDigits()
  • NormalizePrice()
  • NormalizeLots()
  • NewBar()
  • RegimeStr()
  • EMA_Series()
  • CalcTSI()
  • DetectRegime()
  • EffectiveCapital()
  • EARealizedToday()
  • EARealizedWeek()
  • ...and 12 more

INTERNAL CONSTANTS (11 total):

  • DEF_TSI_R = 25 // TSI first smoothing (momentum)
  • DEF_TSI_S = 13 // TSI second smoothing
  • DEF_TSI_SIG = 10 // TSI signal line EMA
  • DEF_FAST_EMA = 50 // Fast trend EMA
  • DEF_SLOW_EMA = 100 // Slow trend EMA
  • DEF_HTF_EMA_P = 50 // HTF EMA period
  • DEF_SL_MULT = 1.8 // SL = ATR * mult
  • DEF_TP_MULT = 3.0 // TP = ATR * mult (R:R ~1.67)
  • DEF_TP1_R = 1.0 // partial TP at 1R
  • DEF_BE_R = 0.8 // BE trigger at 0.8R
  • DEF_SPREAD_MULT = 2.5 // +------------------------------------------------------------------+

INPUT PARAMETERS (25 total across 7 groups):

  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_10004" // Trade comment / magic-tag
  • [=== Identity ===] InpMagic = 22210004 // Magic number
  • [=== Identity ===] InpTFSig = 4 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Signal timeframe
  • [=== Identity ===] InpBaseLots = 0.05 // Base lot (risk floor / fallback)
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade (% of effective capital)
  • [=== Risk & Sizing ===] InpDailyLossLimitPercent = 3.0 // Daily loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPercent = 7.0 // Weekly loss limit (% of effective capital)
  • [=== Risk & Sizing ===] InpMaxOpenTrades = 1 // Max concurrent open positions (this EA+symbol)
  • [=== Risk & Sizing ===] InpLossCooldownN = 3 // Cooldown after N consecutive losses
  • [=== Risk & Sizing ===] InpMaxSpreadPts = 35.0 // Max allowed spread (in points)
  • [=== Risk & Sizing ===] InpSlippagePts = 20 // Order slippage deviation (points)
  • [=== Capital Allocation Cap (§4.6) ===] InpCapitalCapAmount = 0.0 // Cap amount (real-money equity $)
  • [=== Capital Allocation Cap (§4.6) ===] InpCapitalCapFloor = 50.0 // Floor below which entries blocked
  • [=== Signal (TSI) ===] InpTSICrossBuf = 0.0 // TSI main/signal buffer (TSI units, 0..100)
  • [=== Signal (TSI) ===] InpUseRSIFilter = true // Require RSI extreme (avoid mid-range)
  • [=== Regime / Confirm ===] InpRequireHTF = true // Require HTF-EMA agreement
  • [=== Regime / Confirm ===] InpRequireTrendBias = true // Require fast/slow EMA stack bias
  • [=== Regime / Confirm ===] InpUseAdxGate = true // Gate entries on ADX strength
  • [=== Exit / Manage ===] InpUseBreakEven = true // Enable one-shot break-even
  • [=== Exit / Manage ===] InpUsePartialTP = true // Enable partial TP at TP1
  • [=== Exit / Manage ===] InpUseATRTrail = true // Enable ATR trailing stop
  • [=== Exit / Manage ===] InpExitOppSignal = true // Exit on opposite TSI cross
  • [=== Exit / Manage ===] InpExitRegimeChg = true // Exit on regime change to Range/Choppy
  • [=== Execution ===] InpDryRun = true // Dry-run: log but do not send orders
  • [=== Execution ===] InpKillSwitch = false // Kill switch (true = block all trading)
Pseudocode
// Pipsgrowth EX10004 Momentum-Scalper — Execution Flow (from source analysis)
// Family: Momentum-Scalper
// TSI (True Strength Index) is a double-smoothed momentum oscillator. Long/short trigger = TSI main crosses its EMA signal line in the direction of the slow/fast EMA stack bias, on the last CLOSED bar. Entries gated by ADX/ATR-pct/BB-width regime, HTF-EMA agreement, RSI filter, min R/R, session, spread, daily-loss/capital cap. Exits: BE, partial-TP, ATR- trail, opposite-signal, time, regime-change. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

ON_INIT:
    Create indicator handles: ATR, ADX, RSI, BB, FastEMA, SlowEMA, HTF_EMA
    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:
M5M15

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 from the Navigator onto any chart (M1 or M5 recommended)
  7. 7In the EA dialog, enable Allow Algo Trading and set your lot size
  8. 8Click OK — the EA will begin trading automatically

EA Parameters

ParameterDefaultDescription
InpTradeComment"Psgrowth.com Expert_10004"Trade comment / magic-tag
InpMagic22210004Magic number
InpTFSig4Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Signal timeframe
InpBaseLots0.05Base lot (risk floor / fallback)
InpRiskPercent0.5Risk per trade (% of effective capital)
InpDailyLossLimitPercent3.0Daily loss limit (% of effective capital)
InpWeeklyLossLimitPercent7.0Weekly loss limit (% of effective capital)
InpMaxOpenTrades1Max concurrent open positions (this EA+symbol)
InpLossCooldownN3Cooldown after N consecutive losses
InpMaxSpreadPts35.0Max allowed spread (in points)
InpSlippagePts20Order slippage deviation (points)
InpCapitalCapAmount0.0Cap amount (real-money equity $)
InpCapitalCapFloor50.0Floor below which entries blocked
InpTSICrossBuf0.0TSI main/signal buffer (TSI units, 0..100)
InpUseRSIFiltertrueRequire RSI extreme (avoid mid-range)
InpRequireHTFtrueRequire HTF-EMA agreement
InpRequireTrendBiastrueRequire fast/slow EMA stack bias
InpUseAdxGatetrueGate entries on ADX strength
InpUseBreakEventrueEnable one-shot break-even
InpUsePartialTPtrueEnable partial TP at TP1
InpUseATRTrailtrueEnable ATR trailing stop
InpExitOppSignaltrueExit on opposite TSI cross
InpExitRegimeChgtrueExit on regime change to Range/Choppy
InpDryRuntrueDry-run: log but do not send orders
InpKillSwitchfalseKill switch (true = block all trading)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX10004.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX10004 TSI XAUUSD 5M — True Strength Index momentum scalper, full 12-layer stack."

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

//=========================== CONSTANTS ==============================
#define DEF_TSI_R           25      // TSI first smoothing (momentum)
#define DEF_TSI_S           13      // TSI second smoothing
#define DEF_TSI_SIG         10      // TSI signal line EMA
#define DEF_FAST_EMA        50      // Fast trend EMA
#define DEF_SLOW_EMA        100     // Slow trend EMA
#define DEF_HTF_EMA_P       50      // HTF EMA period
#define DEF_HTF_TF          PERIOD_H1
#define DEF_ATR_P           14
#define DEF_ADX_P           14
#define DEF_RSI_P           14
#define DEF_BB_P            20
#define DEF_BB_DEV          2.0
#define DEF_ATR_PCT_BARS    100
#define DEF_ATR_PCT_HI      0.85
#define DEF_ATR_PCT_LO      0.20
#define DEF_REGIME_ADX_STRONG  25
#define DEF_REGIME_ADX_WEAK    18
#define DEF_RSI_OB          70
#define DEF_RSI_OS          30
#define DEF_MIN_RR          1.2
#define DEF_SESSION_START   7
#define DEF_SESSION_END     21
#define DEF_SL_MULT         1.8     // SL = ATR * mult
#define DEF_TP_MULT         3.0     // TP = ATR * mult (R:R ~1.67)
#define DEF_TP1_R           1.0     // partial TP at 1R
#define DEF_TP1_PCT         50
#define DEF_BE_R            0.8     // BE trigger at 0.8R
#define DEF_BE_OFFSET_R     0.15
#define DEF_TRAIL_ATR       2.5
#define DEF_TRAIL_START_R   1.0
#define DEF_MAX_BARS        80
#define DEF_LOSS_COOLDOWN_S (30*60)
#define DEF_SPREAD_MULT     2.5

//+------------------------------------------------------------------+
//| INPUTS (12-22, grouped)                                          |
//+------------------------------------------------------------------+
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;

Full source code available on download

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

Tags:ex10004momentum-scalperpipsgrowthfreemt5xauusd

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_EX10004.mq5
File Size41.1 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyScalping
Risk LevelHigh Risk
Timeframes
M5M15
Currency Pairs
XAUUSD
Min. Deposit$100