P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16051 Trend

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

Pipsgrowth.com EX16051 new_copy — Multi-indicator scalping EA, full 12-layer stack.

Overview

Pipsgrowth EX16051 Trend is a role-assignable multi-indicator scalping EA, hard-locked to USDJPY at OnInit (the function returns INIT_FAILED outright if the chart symbol is anything else and OnlyTradeUSDJPY stays true), built around a single architectural idea: every indicator on the chart can be promoted to one of seven roles — Primary Signal, Confirmation, Filter, Exit Signal, Exit Filter, Trend Filter, or Disabled — and the EA then runs the same logical chain regardless of which indicator you assigned. The shipped role map is EMA(8) crossed with EMA(21) as Primary Signal, RSI(14) as Confirmation, Stochastic(14,3,3) as a second Confirmation, MACD(12,26,9) as Filter, Bollinger Bands(20,2) as Exit Filter, and ATR(14) as Filter, with an extra ATR(14) on the higher timeframe pulled in for multi-timeframe alignment. That means eight native handles are created in InitializeIndicators() — fastEMA, slowEMA, RSI, MACD, BB, Stochastic, ATR, and ATR_HTF — and the same buffers are read three different ways depending on role: GetEMASignal() returns 1 / 0 / -1, GetRSISignal() returns 1 / 0 / -1, GetMACDSignal() returns 1 / 0 / -1, GetStochasticSignal() returns 1 / 0 / -1, and the same numbers are then consumed by GetPrimarySignal(), GetTradeSignal(), CalculateSignalStrength(), PassesFilters(), and CheckExitSignals() in turn.

GetEMASignal() is the only one configured as Primary by default and it gates everything. A buy needs the fast EMA crossing above the slow EMA on the current bar (fast1 ≤ slow1 and fast0 > slow0), the slope of the fast EMA on the latest bar (fast0 − fast1) being at least EMA_MinSlope = 0.00020, and the absolute separation between fast and slow being at least EMA_MinSeparation = 0.0003. A sell is the mirror. If EMA_RequireCrossover is flipped off, the function degenerates into a directional check: positive separation plus positive slope = buy, negative separation plus negative slope = sell. Every signal-reading function has the same three-bar structure (current, previous, two-bars-back) and the same slope-momentum logic — RSI only counts a bounce if r0 was oversold (≤30) one bar ago AND r0 > r1 > r2 AND r0 is still inside the neutral band 40–60, so RSI fires on a controlled recovery, not a raw oversold read; MACD requires a histogram zero-cross (hist1 ≤ 0 and hist0 > 0) with the main line above the signal line and, when MACD_RequireHistogramGrowing is on, hist0 > hist1; Stochastic requires %K to cross %D (k1 ≤ d1 and k0 > d0) with both lines moving in the same direction and %K sitting between the 20 and 80 levels.

GetTradeSignal() reads the primary, then counts how many of the four indicators currently sit in ROLE_CONFIRMATION agree with it, and demands the count reaches RequiredConfirmations (default 3). If three or four of them line up with the EMA direction, the function then calls PassesFilters() which walks every indicator still in ROLE_FILTER — in the shipped setup that means MACD and ATR — and also Bollinger Bands when its role is set to filter, with each filter hard-failing the signal if its individual condition is not met. The BB filter rejects entries where the current close sits closer to either band than BB_MiddleBandFilter (0.5 means within 50% of half the band width) and rejects during a squeeze (band width < ATR × 1.5). The ATR filter rejects when atr[0] in pips falls outside MinATR_Pips..MaxATR_Pips, default 8 to 20 pips on a 5-digit USDJPY chart. Bollinger Bands is wired as ROLE_EXIT_FILTER by default, so BB itself doesn't veto entries but contributes to exit decisions via PassesBBFilter().

CalculateSignalStrength() takes the base (confirmations / total enabled confirmations) and stacks four bonus terms on top: +0.15 if IsTrendAligned (close > fast EMA > slow EMA for buys, the mirror for sells), +0.10 if IsHTFAligned (current HTF ATR not more than 5% below previous HTF ATR — a deliberately permissive check that essentially means 'HTF ATR is stable'), +0.05 if current ATR is within 20% of the midpoint of the volatility band, and a session bonus of 0.03 for Tokyo, 0.05 for London, 0.05 for New York, 0.02 for Sydney. The total is clamped to 0..1 and the entry chain only fires when the value is at least MinSignalStrength = 0.85 AND MinSignalConfidence = 0.90 — those two thresholds are gated separately, so a setup with a 0.87 base strength gets rejected by the quality filter while a 0.91 setup that fails the bad-trade filter is also rejected. With three or four confirmations plus a trend-aligned bonus, the typical passing setup lands in the 0.850.95 range, which is exactly the narrow window the EA is designed to fire in.

The execution chain is straightforward. ExecuteBuyTrade() pulls the ask, calls CalculateLotSize() (which returns the fixed LotSize = 1.0 unless UseAutoLotSize is on, in which case it sizes to RiskPercent = 1.0% of balance divided by the SL distance in pips times the tick value), CalculateStopLoss() (15 pips or ATR × ATR_StopLossMultiplier = 2.0, whichever is larger and broker-stops-level-safe), and CalculateTakeProfit() (25 pips or ATR × ATR_TakeProfitMultiplier = 3.0), then submits a market order via trade.Buy() with ORDER_FILLING_FOK and a slippage allowance of SlippagePoints = 5. The trade comment embeds the signal strength as a decimal for later forensics. The same path runs in reverse for sells. CalculateStopLoss() and CalculateTakeProfit() both honour SYMBOL_TRADE_STOPS_LEVEL — if the broker enforces a 10-point minimum stop distance, the EA widens the SL to that minimum rather than sending a rejected order — and both cap their final distance at MaxATR_Pips = 20 pips, so the EA will not place a 60-pip SL on a single 60-pip-Atr bar even if StopLossPips is set to 50.

Management runs every tick once the entry throttle (EntryTickDelay = 2 ticks) has elapsed. ManagePositions() loops the open positions and, for each, calls CheckQuickExit() first, then CheckMaxHoldingTime(), then UpdateTrailingStop(), then CheckExitSignals(). CheckQuickExit() re-evaluates GetTradeSignal() and closes the position if the current signal direction is opposite to the position type — so a buy that flips to a confirmed sell closes immediately. CheckMaxHoldingTime() counts closed bars since the open time via iBarShift and force-closes when the count reaches MaxHoldingBars = 10. UpdateTrailingStop() ratchets the SL by TrailingStopPips = 10 pips every TrailingStepPips = 5 pips of favourable move, and only moves the SL toward the open price and beyond it (no initial break-even if the EA opens a trade at the broker minimum stop distance and price hasn't moved 10 pips yet, the trail stays put). CheckExitSignals() walks the indicators in ROLE_EXIT_SIGNAL — in the shipped map that includes EMA, RSI, and MACD — and closes the position if any of them fires a direction-flipping signal. The trailing modification goes through TryModify_EX16051 (3 attempts, 100 ms sleep on REQUOTE or TIMEOUT) and the close goes through TryClose_EX16051 (3 attempts, 200 ms sleep, also handles PRICE_OFF and PRICE_CHANGED). TryClosePartial_EX16051 is defined at the file footer but never called from any live path — it's dead code carried over from the template.

Two additional safety rails run before entries. CheckDailyLimits() reads the broker-side account balance, tracks daily P/L deltas in UpdateDailyPL(), and force-closes every open USDJPY position if dailyLossMaxDailyLoss = 50.0 or dailyProfitMaxDailyProfit = 150.0. The new-day reset is keyed off a StringToTime of the YYYY.MM.DD date string, so the rollover fires at server midnight. IsBasicTradingAllowed() is the per-tick guard: it blocks when the spread exceeds MaxSpreadPips = 2.0, when the GMT hour isn't inside any of the four allowed sessions (Tokyo 23–07, London 08–16, NY 13–21, Sydney 21–05), when AvoidNews is on and the current minute is within NewsAvoidanceMinutes = 30 of the next hour mark, when ATR isn't in MinVolatilityPips..MaxVolatilityPips, when the time since lastTradeTime is less than MinBarsSinceLastTrade × PeriodSeconds, or when the open position count has hit MaxConcurrentTrades = 3. ValidateBuySignal() and ValidateSellSignal() add a second pass that rejects entries near recent 10-bar highs (resistance) or lows (support) within 10 points, rejects whipsaw setups (CheckWhipsaw() requires current ATR ≥ midpoint of recent ATR range × WhipsawThreshold = 0.8), and rejects entries when the current bar's tick volume is below MinBarVolume = 10.

What you actually get in live trading is a slow but selective system. With M5 USDJPY and the shipped session filter on, the EA only fires inside four windows totalling roughly 20 hours per day but the actual entries land in the 0.850.95 strength band, the SL is 15 pips with a 25-pip TP for a 1:1.67 reward-to-risk, the trail activates at +10 pips and steps every +5 pips, and the daily caps cut the EA off at +$150 or −$50 whichever comes first. OnInit, OnTick, and OnDeinit are the only event handlers — there is no OnTrade, no OnTimer, no OnChartEvent, no OnTester. The HTF ATR pull is the only piece of multi-timeframe work the EA does, and IsHTFAligned is a deliberately permissive check (current HTF ATR within 5% of previous), so it doesn't actually filter out a meaningful number of setups. The two thresholds MinSignalStrength and MinSignalConfidence are checked sequentially with different minimums, which means a setup that crosses one but not the other still fails — that is the design, not a bug.

Strategy Deep Dive

Each tick, the EA first gates the symbol (returns INIT_FAILED at OnInit if the chart is not USDJPY when OnlyTradeUSDJPY is true), then runs IsBasicTradingAllowed() to filter spread (≤2 pips), session (one of Tokyo, London, NY, Sydney GMT windows), volatility (ATR in 5–25 pips), time-since-last-trade, and position count (≤3). On a new bar, UpdateIndicatorBuffers() pulls 3 bars from each of the eight indicator handles, and GetTradeSignal() runs GetEMASignal() (Primary) then counts how many of the four other indicators currently in ROLE_CONFIRMATION match its direction. If the count reaches RequiredConfirmations (default 3) and the signal survives the ROLE_FILTER chain, the raw direction is returned. CalculateSignalStrength() then stacks trend-alignment, HTF-ATR, volatility, and session bonuses on top of the base rate, and the trade only fires when both MinSignalStrength = 0.85 and MinSignalConfidence = 0.90 are cleared. After execution, ManagePositions() runs the trailing-stop ratchet, the 10-bar time stop, the indicator-driven exit signals, and the daily P/L caps that force-close everything once dailyLoss50.0 or dailyProfit150.0.

Entry Signal

Long entries require a bullish EMA(8) over EMA(21) crossover on the current bar with the fast-EMA slope ≥ 0.00020 and the absolute EMA separation ≥ 0.0003, plus at least three of the four indicator votes (EMA, RSI(14) oversold-bounce in the 40–60 neutral band, MACD(12,26,9) histogram zero-cross with main line above signal, Stochastic(14,3,3) %K/%D cross with both lines moving in the same direction) agreeing with the EMA direction. Sells are the exact mirror. The combined signal must clear both MinSignalStrength = 0.85 and MinSignalConfidence = 0.90, and survive the filter chain (MACD, ATR 8–20 pips, optional BB distance + squeeze).

Exit Signal

Positions close on three possible paths: a quick-exit triggered when GetTradeSignal() returns the opposite direction (immediate close via TryClose_EX16051), a time exit after 10 closed bars from open (iBarShift-based count in CheckMaxHoldingTime), or an indicator exit when any ROLE_EXIT_SIGNAL indicator (EMA, RSI at 70/30 extremes, or MACD) flips to the opposing direction. Successful entries also run UpdateTrailingStop() every tick, ratcheting the SL by 10 pips for every 5 pips of favourable price move once the trade is in profit.

Stop Loss

Default stop loss is 15 pips or ATR(14) × ATR_StopLossMultiplier = 2.0, whichever is larger, with the broker's SYMBOL_TRADE_STOPS_LEVEL enforced as a minimum and MaxATR_Pips = 20 capping the upper bound. The trailing stop then takes over: it ratchets the SL 10 pips closer to the open price for every 5 pips of favourable move, but only after the trade is in profit past the trail distance.

Take Profit

Take profit defaults to 25 pips or ATR(14) × ATR_TakeProfitMultiplier = 3.0, whichever is larger, capped at MaxATR_Pips = 20 pips, and broker-stops-level-safe. The 1:1.67 reward-to-risk comes from the 15/25 pips split on a 5-digit USDJPY chart.

Best For

Run this on USDJPY M5 (or H1 for fewer but cleaner signals) at a low-spread ECN or RAW broker — the 2-pip MaxSpreadPips filter is tight and the 1.0 default lot only makes sense at $5,000+ account size unless you switch to UseAutoLotSize with 1% risk. With the four-session filter on, you'll get overlap coverage through London and New York (the only sessions where both MinSignalStrength and MinSignalConfidence typically clear together), with isolated setups in Tokyo and Sydney. $100 minimum deposit will accept the EA but $1,000+ is needed for the 15-pip SL on 1.0 lot USDJPY to represent under 2% account risk. MEDIUM risk classification reflects the 1:1.67 RR with a tight daily-loss cap.

Strategy Logic

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

Family: Trend Magic: 22216051 Version: 2.00

BRIEF: Robust USDJPY scalping EA with multi-role indicator system using EMA, RSI, MACD, Bollinger Bands, and Stochastic. Features signal quality filtering, multi-timeframe alignment, session filters, trailing stops, and daily loss/profit limits. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • InitializeIndicators()
  • UpdateIndicatorBuffers()
  • IsBasicTradingAllowed()
  • CheckForEntrySignals()
  • CalculateSignalStrength()
  • GetPrimarySignal()
  • GetEMASignal()
  • GetRSISignal()
  • GetMACDSignal()
  • GetStochasticSignal()
  • GetTradeSignal()
  • PassesFilters()
  • ...and 42 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (94 total across 14 groups):

  • [=== Identity ===] InpMagicNumber = 22216051 // Magic Number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_16051" // Trade Comment
  • [=== GLOBAL TRADING SETTINGS ===] LotSize = 1.0 // Fixed lot size
  • [=== GLOBAL TRADING SETTINGS ===] UseAutoLotSize = false // Use automatic lot sizing
  • [=== GLOBAL TRADING SETTINGS ===] RiskPercent = 1.0 // Risk percentage for auto lot sizing
  • [=== GLOBAL TRADING SETTINGS ===] MaxSpreadPips = 2.0 // e.g. 2 pips maximum spread
  • [=== GLOBAL TRADING SETTINGS ===] SlippagePoints = 5 // Maximum slippage (points)
  • [=== GLOBAL TRADING SETTINGS ===] OnlyTradeUSDJPY = true // Only trade USDJPY pair
  • [=== GLOBAL TRADING SETTINGS ===] TradingPairs = "USDJPY" // Allowed trading pairs (comma separated)
  • [=== RISK MANAGEMENT ===] StopLossPips = 15 // Stop Loss in pips
  • [=== RISK MANAGEMENT ===] TakeProfitPips = 25 // Take Profit in pips
  • [=== RISK MANAGEMENT ===] UseTrailingStop = true // Enable trailing stop
  • [=== RISK MANAGEMENT ===] TrailingStopPips = 10 // Trailing stop distance (pips)
  • [=== RISK MANAGEMENT ===] TrailingStepPips = 5 // Trailing step (pips)
  • [=== RISK MANAGEMENT ===] MaxConcurrentTrades = 3 // Maximum concurrent trades
  • [=== RISK MANAGEMENT ===] MaxDailyLoss = 50.0 // Maximum daily loss (account currency)
  • [=== RISK MANAGEMENT ===] MaxDailyProfit = 150.0 // Daily profit target (account currency)
  • [=== SIGNAL QUALITY FILTERS ===] EnableQualityFiltering = true // Enable 95% accuracy filtering
  • [=== SIGNAL QUALITY FILTERS ===] MinSignalStrength = 0.85 // Minimum signal strength (0.5-1.0)
  • [=== SIGNAL QUALITY FILTERS ===] RequiredConfirmations = 3 // Required confirmations for entry
  • [=== SIGNAL QUALITY FILTERS ===] RequireMultiTimeframeAlignment = true // Require HTF alignment
  • [=== SIGNAL QUALITY FILTERS ===] HigherTimeframe = 9 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher timeframe for alignment
  • [=== SIGNAL QUALITY FILTERS ===] UseTrendFilter = true // Only trade with trend
  • [=== SIGNAL QUALITY FILTERS ===] TrendLookbackBars = 50 // Bars for trend analysis
  • [=== MARKET CONDITIONS ===] EnableSessionFilter = true // Enable trading session filter
  • [=== MARKET CONDITIONS ===] TradingSessions = "Tokyo,London,NY,Sydney" // Allowed sessions (Tokyo,London,NY,Sydney)
  • [=== MARKET CONDITIONS ===] AvoidNews = false // Avoid trading during news
  • [=== MARKET CONDITIONS ===] NewsAvoidanceMinutes = 30 // Minutes to avoid before/after news
  • [=== MARKET CONDITIONS ===] MinVolatilityPips = 5.0 // Minimum ATR (pips) for trading
  • [=== MARKET CONDITIONS ===] MaxVolatilityPips = 25.0 // Maximum ATR (pips) for trading
  • [=== MARKET CONDITIONS ===] UseATRFilter = true // Use ATR filtering
  • [=== MARKET CONDITIONS ===] MinATR_Pips = 8.0 // Minimum ATR (pips) for additional filters
  • [=== MARKET CONDITIONS ===] MaxATR_Pips = 20.0 // Maximum ATR (pips) for additional filters
  • [=== SCALPING SETTINGS ===] EnableScalpingMode = true // Enable scalping optimizations
  • [=== SCALPING SETTINGS ===] MinBarsSinceLastTrade = 3 // Minimum bars between trades
  • [=== SCALPING SETTINGS ===] ScalpingNoiseThresholdPips = 0.3 // Noise threshold in pips
  • [=== SCALPING SETTINGS ===] QuickExitOnReverse = true // Quick exit on reverse signal
  • [=== SCALPING SETTINGS ===] MaxHoldingBars = 10 // Maximum bars to hold position
  • [=== SCALPING SETTINGS ===] UseTickBasedEntry = true // Use tick-based entry precision
  • [=== SCALPING SETTINGS ===] EntryTickDelay = 2 // Ticks to wait before entry
  • [=== EMA SYSTEM ===] EMA_Role = ROLE_PRIMARY_SIGNAL // EMA Role in Trading System
  • [=== EMA SYSTEM ===] EMA_Fast_Period = 8 // Fast EMA Period
  • [=== EMA SYSTEM ===] EMA_Slow_Period = 21 // Slow EMA Period
  • [=== EMA SYSTEM ===] EMA_AppliedPrice = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // Applied Price
  • [=== EMA SYSTEM ===] EMA_RequireCrossover = true // Require EMA crossover
  • [=== EMA SYSTEM ===] EMA_MinSeparation = 0.0003 // Minimum EMA separation
  • [=== EMA SYSTEM ===] EMA_MinSlope = 0.00020 // Minimum slope for signal
  • [=== RSI SYSTEM ===] RSI_Role = ROLE_CONFIRMATION // RSI Role in Trading System
  • [=== RSI SYSTEM ===] RSI_Period = 14 // RSI Period
  • [=== RSI SYSTEM ===] RSI_AppliedPrice = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // Applied Price
  • [=== RSI SYSTEM ===] RSI_OverboughtLevel = 70.0 // Overbought level
  • [=== RSI SYSTEM ===] RSI_OversoldLevel = 30.0 // Oversold level
  • [=== RSI SYSTEM ===] RSI_NeutralUpper = 60.0 // Neutral zone upper bound
  • [=== RSI SYSTEM ===] RSI_NeutralLower = 40.0 // Neutral zone lower bound
  • [=== MACD SYSTEM ===] MACD_Role = ROLE_FILTER // MACD Role in Trading System
  • [=== MACD SYSTEM ===] MACD_FastEMA = 12 // Fast EMA Period
  • [=== MACD SYSTEM ===] MACD_SlowEMA = 26 // Slow EMA Period
  • [=== MACD SYSTEM ===] MACD_SignalSMA = 9 // Signal SMA Period
  • [=== MACD SYSTEM ===] MACD_AppliedPrice = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)// Applied Price
  • [=== MACD SYSTEM ===] MACD_RequireHistogramGrowing = true // Require growing histogram
  • [=== MACD SYSTEM ===] MACD_MinHistogramValue = 0.0001 // Minimum histogram value
  • [=== BOLLINGER BANDS SYSTEM ===] BB_Role = ROLE_EXIT_FILTER // BB Role in Trading System
  • [=== BOLLINGER BANDS SYSTEM ===] BB_Period = 20 // BB Period
  • [=== BOLLINGER BANDS SYSTEM ===] BB_Deviation = 2.0 // BB Deviation
  • [=== BOLLINGER BANDS SYSTEM ===] BB_AppliedPrice = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // Applied Price
  • [=== BOLLINGER BANDS SYSTEM ===] BB_MiddleBandFilter = 0.5 // Distance from middle band (0.0-1.0)
  • [=== BOLLINGER BANDS SYSTEM ===] BB_UseSqueezeDetection = true // Detect BB squeeze
  • [=== STOCHASTIC SYSTEM ===] STOCH_Role = ROLE_CONFIRMATION // Stochastic Role
  • [=== STOCHASTIC SYSTEM ===] STOCH_KPeriod = 14 // %K Period
  • [=== STOCHASTIC SYSTEM ===] STOCH_DPeriod = 3 // %D Period
  • [=== STOCHASTIC SYSTEM ===] STOCH_Slowing = 3 // Slowing
  • [=== STOCHASTIC SYSTEM ===] STOCH_Method = MODE_SMA // MA Method
  • [=== STOCHASTIC SYSTEM ===] STOCH_PriceField = STO_LOWHIGH // Price Field
  • [=== STOCHASTIC SYSTEM ===] STOCH_OverboughtLevel = 80.0 // Overbought level
  • [=== STOCHASTIC SYSTEM ===] STOCH_OversoldLevel = 20.0 // Oversold level
  • [=== ATR SYSTEM ===] ATR_Role = ROLE_FILTER // ATR Role in Trading System
  • [=== ATR SYSTEM ===] ATR_Period = 14 // ATR Period
  • [=== ATR SYSTEM ===] ATR_VolatilityMultiplier = 1.5 // Volatility multiplier
  • [=== ATR SYSTEM ===] ATR_UseForStopLoss = true // Use ATR for stop loss
  • [=== ATR SYSTEM ===] ATR_StopLossMultiplier = 2.0 // ATR multiplier for SL
  • [=== ATR SYSTEM ===] ATR_UseForTakeProfit = true // Use ATR for take profit
  • [=== ATR SYSTEM ===] ATR_TakeProfitMultiplier = 3.0 // ATR multiplier for TP
  • [Mix] MinBarVolume = 10 // Minimum tick volume to consider a bar “valid”
  • [Mix] DebugMode = true // ⇐ Toggle all debug logging on/off
  • [=== BAD TRADE AVOIDANCE ===] EnableBadTradeFilter = true // Enable bad trade avoidance
  • [=== BAD TRADE AVOIDANCE ===] MinSignalConfidence = 0.90 // Minimum signal confidence
  • [=== BAD TRADE AVOIDANCE ===] AvoidWhipsaws = true // Avoid whipsaw conditions
  • [=== BAD TRADE AVOIDANCE ===] WhipsawLookback = 5 // Bars to check for whipsaws
  • [=== BAD TRADE AVOIDANCE ===] WhipsawThreshold = 0.8 // Whipsaw detection threshold
  • [=== BAD TRADE AVOIDANCE ===] RequireVolumeBias = false // Require volume bias (tick volume)
  • [=== BAD TRADE AVOIDANCE ===] AvoidFlatMarkets = true // Avoid flat/sideways markets
  • [=== BAD TRADE AVOIDANCE ===] FlatMarketThreshold = 0.0005 // Flat market ATR threshold
  • [=== BAD TRADE AVOIDANCE ===] AvoidOverextension = true // Avoid overextended markets
  • [=== BAD TRADE AVOIDANCE ===] OverextensionMultiplier = 2.5 // Overextension threshold multiplier
Pseudocode
// Pipsgrowth EX16051 Trend — Execution Flow (from source analysis)
// Family: Trend
// Robust USDJPY scalping EA with multi-role indicator system using EMA, RSI, MACD, Bollinger Bands, and Stochastic. Features signal quality filtering, multi-timeframe alignment, session filters, trailing stops, and daily loss/profit limits. 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
InpMagicNumber22216051Magic Number
InpTradeComment"Psgrowth.com Expert_16051"Trade Comment
LotSize1.0Fixed lot size
UseAutoLotSizefalseUse automatic lot sizing
RiskPercent1.0Risk percentage for auto lot sizing
MaxSpreadPips2.0e.g. 2 pips maximum spread
SlippagePoints5Maximum slippage (points)
OnlyTradeUSDJPYtrueOnly trade USDJPY pair
TradingPairs"USDJPY"Allowed trading pairs (comma separated)
StopLossPips15Stop Loss in pips
TakeProfitPips25Take Profit in pips
UseTrailingStoptrueEnable trailing stop
TrailingStopPips10Trailing stop distance (pips)
TrailingStepPips5Trailing step (pips)
MaxConcurrentTrades3Maximum concurrent trades
MaxDailyLoss50.0Maximum daily loss (account currency)
MaxDailyProfit150.0Daily profit target (account currency)
EnableQualityFilteringtrueEnable 95% accuracy filtering
MinSignalStrength0.85Minimum signal strength (0.5-1.0)
RequiredConfirmations3Required confirmations for entry
RequireMultiTimeframeAlignmenttrueRequire HTF alignment
HigherTimeframe9Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Higher timeframe for alignment
UseTrendFiltertrueOnly trade with trend
TrendLookbackBars50Bars for trend analysis
EnableSessionFiltertrueEnable trading session filter
TradingSessions"Tokyo,London,NY,Sydney"Allowed sessions (Tokyo,London,NY,Sydney)
AvoidNewsfalseAvoid trading during news
NewsAvoidanceMinutes30Minutes to avoid before/after news
MinVolatilityPips5.0Minimum ATR (pips) for trading
MaxVolatilityPips25.0Maximum ATR (pips) for trading
UseATRFiltertrueUse ATR filtering
MinATR_Pips8.0Minimum ATR (pips) for additional filters
MaxATR_Pips20.0Maximum ATR (pips) for additional filters
EnableScalpingModetrueEnable scalping optimizations
MinBarsSinceLastTrade3Minimum bars between trades
ScalpingNoiseThresholdPips0.3Noise threshold in pips
QuickExitOnReversetrueQuick exit on reverse signal
MaxHoldingBars10Maximum bars to hold position
UseTickBasedEntrytrueUse tick-based entry precision
EntryTickDelay2Ticks to wait before entry
EMA_RoleROLE_PRIMARY_SIGNALEMA Role in Trading System
EMA_Fast_Period8Fast EMA Period
EMA_Slow_Period21Slow EMA Period
EMA_AppliedPrice1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // Applied Price
EMA_RequireCrossovertrueRequire EMA crossover
EMA_MinSeparation0.0003Minimum EMA separation
EMA_MinSlope0.00020Minimum slope for signal
RSI_RoleROLE_CONFIRMATIONRSI Role in Trading System
RSI_Period14RSI Period
RSI_AppliedPrice1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // Applied Price
RSI_OverboughtLevel70.0Overbought level
RSI_OversoldLevel30.0Oversold level
RSI_NeutralUpper60.0Neutral zone upper bound
RSI_NeutralLower40.0Neutral zone lower bound
MACD_RoleROLE_FILTERMACD Role in Trading System
MACD_FastEMA12Fast EMA Period
MACD_SlowEMA26Slow EMA Period
MACD_SignalSMA9Signal SMA Period
MACD_AppliedPrice1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)// Applied Price
MACD_RequireHistogramGrowingtrueRequire growing histogram
MACD_MinHistogramValue0.0001Minimum histogram value
BB_RoleROLE_EXIT_FILTERBB Role in Trading System
BB_Period20BB Period
BB_Deviation2.0BB Deviation
BB_AppliedPrice1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // Applied Price
BB_MiddleBandFilter0.5Distance from middle band (0.0-1.0)
BB_UseSqueezeDetectiontrueDetect BB squeeze
STOCH_RoleROLE_CONFIRMATIONStochastic Role
STOCH_KPeriod14%K Period
STOCH_DPeriod3%D Period
STOCH_Slowing3Slowing
STOCH_MethodMODE_SMAMA Method
STOCH_PriceFieldSTO_LOWHIGHPrice Field
STOCH_OverboughtLevel80.0Overbought level
STOCH_OversoldLevel20.0Oversold level
ATR_RoleROLE_FILTERATR Role in Trading System
ATR_Period14ATR Period
ATR_VolatilityMultiplier1.5Volatility multiplier
ATR_UseForStopLosstrueUse ATR for stop loss
ATR_StopLossMultiplier2.0ATR multiplier for SL
ATR_UseForTakeProfittrueUse ATR for take profit
ATR_TakeProfitMultiplier3.0ATR multiplier for TP
MinBarVolume10Minimum tick volume to consider a bar “valid”
DebugModetrue⇐ Toggle all debug logging on/off
EnableBadTradeFiltertrueEnable bad trade avoidance
MinSignalConfidence0.90Minimum signal confidence
AvoidWhipsawstrueAvoid whipsaw conditions
WhipsawLookback5Bars to check for whipsaws
WhipsawThreshold0.8Whipsaw detection threshold
RequireVolumeBiasfalseRequire volume bias (tick volume)
AvoidFlatMarketstrueAvoid flat/sideways markets
FlatMarketThreshold0.0005Flat market ATR threshold
AvoidOverextensiontrueAvoid overextended markets
OverextensionMultiplier2.5Overextension threshold multiplier
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16051.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16051 new_copy — Multi-indicator scalping EA, full 12-layer stack."

#include <Trade/Trade.mqh>

//+------------------------------------------------------------------+
//| Global Trading 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_HigherTimeframe = PERIOD_H1;
ENUM_APPLIED_PRICE g_EMA_AppliedPrice = PRICE_CLOSE;
ENUM_APPLIED_PRICE g_RSI_AppliedPrice = PRICE_CLOSE;
ENUM_APPLIED_PRICE g_MACD_AppliedPrice = PRICE_CLOSE;
ENUM_APPLIED_PRICE g_BB_AppliedPrice = PRICE_CLOSE;
input group "=== Identity ===";
input ulong      InpMagicNumber = 22216051;           // Magic Number
input string     InpTradeComment = "Psgrowth.com Expert_16051"; // Trade Comment

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;

Full source code available on download

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

Tags:ex16051trendpipsgrowthfreemt5xauusd

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