P
PipsGrowth
OtherOpen Source – Free

Pipsgrowth EX17016 Volatility

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

Pipsgrowth.com EX17016 GB_1_4 — Universal EA template with Donchian Channel breakout, full 12-layer stack.

Overview

EX17016 is a universal EA template that pairs a Donchian Channel breakout entry with a comprehensive 12-layer trade-management stack designed to be portable across FX majors and metals. The header comment in the source file labels it GB_1_4 (general-purpose build 1.4) and frames the EA as the first release in a line of generic, parameterised trading scaffolds rather than a strategy that targets a specific market structure. Every layer below the entry signal — risk caps, position management, exit handlers, session filters, EOD closures, notifications, retry logic — is implemented out of the box, with several indicator-dependent hooks left as placeholders the user can extend.

The signal itself lives in GetEntrySignal(). The EA computes the upper and lower Donchian bounds by scanning InpDonchianPeriod bars (default 10) starting InpDonchianShift bars back (default 1, i.e. excluding the still-forming bar). A long setup fires when the current bar's close prints above the upper band, after both of the previous two closes were at or below it, and the optional InpRequireStrongCandle filter is satisfied — which is the case when the current bar's body covers at least 60 percent of its full high-low range. A short setup mirrors the logic in the opposite direction. The InpDonchianOffsetPips input (default 1 pip) widens the breakout threshold slightly so that price must clear the band by that margin, which suppresses marginal breakouts. The shift of 1 is the convention: the channel is built from completed bars only, so the trigger depends on a real close beyond a real high or low rather than an intra-bar poke.

Trade management runs from ManageOpenPositions() on every tick. The function walks the open position list, filters by magic and symbol, and chains six sub-routines in fixed order: ApplyHardSL_TP_IfNotSet, ApplyTrailingStop, ApplyBreakEven, ApplyProfitLock, CheckTimeBasedSL, and GetExitSignal. The hard stop defaults to 4000 points below (or above) entry and is the primary safety net. The fixed take profit is set to 100000 points by default — effectively a disabled TP that leaves the position to be closed by the management stack or by the indicator hooks. The trailing stop, ATR stop, break-even move, and time-based close are all turned off by default and let the user opt in; each has a placeholder or input scaffold ready to be wired in.

The profit-lock chain is the most distinctive piece of the management layer. Once the price has travelled InpProfitLockTriggerPoints (default 1000 points) in favour of the position, ApplyProfitLock starts moving the stop to current_price - InpProfitLockSecurePoints (default 500 points behind). The stop is only ever ratcheted forward in increments of at least InpProfitLockStepPoints (default 500 points), and when InpProfitLockOnlyAfterBE is true (default), the lock waits until the break-even trigger has fired first. The result is a stepped, hand-rolled trailing stop that secures open profits in discrete tiers without smoothing — the open position is held until price reverses by the secure distance, then closed by the original stop.

Risk caps are split into three layers. IsDrawdownLimitOk blocks new entries when the equity drawdown against the balance exceeds InpMaxDrawdownPercent (default 20%) or the absolute loss in account currency exceeds InpMaxDrawdownAmount. CanOpenNewTrade enforces a cap on simultaneous positions (InpMaxOpenTrades, default 10) and a per-day ceiling (InpMaxTradesPerDay, default 5) and refuses to open a new trade if the same-direction existing positions do not already have the InpMinProfitPerTradeToAdd (default 1600 points) locked in. UpdateConsecutiveLossesAndPause is fed by trade transactions and freezes the EA for InpPauseMinutesAfterLosingStreak (default 60 minutes) after InpMaxConsecutiveLosingTrades (default 3) losses in a row. Together they form a cool-off loop that prevents revenge trading during losing streaks.

Lot sizing is two-mode. The default LOT_FIXED mode uses the input lot (0.01) directly. The LOT_AUTO_SCALED mode calculates floor(capital / InpAutoLot_CapitalPerIncrement) × InpAutoLot_Increment, where the capital base is either account balance or equity depending on InpAutoLotBaseType. The defaults (0.01 lot per 1000 currency units, min 0.01, max 10) give a roughly 0.1 percent per-unit exposure on a $10k account, which suits the EA's wider stops but is easy to retune for tighter or wider risk profiles.

Session control is optional. With InpEnableSessionControl off (default), trading runs around the clock subject only to the EA's other gates. When enabled, the EA checks the current time against three configurable windows and pauses new entries InpPauseMinutesBeforeEndOfSession (default 30) minutes before the active session ends. InpForceCloseAllTradesAtSessionEnd triggers a bulk close InpForceCloseMinutesBeforeSessionEnd minutes before the end, and InpCloseAllTradesAtEndOfDay does the same at InpEndOfDayCloseTime (default 23:50 server time). A smart-exit timer, also off by default, ramps up the same pause window earlier (InpSmartExitStartMinutesBeforeSessionEnd default 60) for setups that want a wider cool-down ahead of the close.

The order-execution layer ships with a hardened OpenMarketOrder function. It forces ORDER_FILLING_IOC (a hard-coded workaround for ICMarkets-style brokers that reject the default ORDER_FILLING_FOK on certain symbols), clamps SL and TP away from the price by the symbol's StopsLevel plus the slippage input, refuses to send orders with SL or TP values below 10.0 (a guard against floating-point glitches), and logs every attempt. The three execution helpers — TryClose_EX17016, TryClosePartial_EX17016, and TryModify_EX17016 — each retry up to three times on requote, timeout, price-off, or price-changed return codes, sleeping 200 ms between close attempts and 100 ms between modify attempts. The naming suffix _EX17016 is the EA's way of avoiding collisions when other EAs in the same terminal share global trade helpers.

Three function stubs in the lower half of the file make the template extensible. GetExitSignal, GetIndicatorStopLoss, and GetIndicatorTakeProfit all return placeholder values (false, 0.0, 0.0) and are explicitly called by the management chain. The intent is that a downstream user or future build can drop indicator logic into those hooks to override the hard-coded SL/TP defaults with ATR pivots, structure levels, or any other custom exit. The 12 layers in the header brief — REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester — are the conceptual slots these hooks fill. The exit and scaling layers are intentionally left empty so that a future indicator stack can be added without re-architecting the management chain.

Notifications and logging round the template out. The Log function writes to the terminal whenever InpLogTradeEvents is on (default) and emits an Alert for errors; email and push channels are toggled by InpEnableEmailNotify and InpEnablePushNotify but the actual transport is left as a TODO inside Log. InpLogTickEvents lets the user enable verbose per-tick output for debugging, at the cost of an exponential increase in journal size.

The expected backtest character of the EA on the M5H1 default range is moderate-frequency breakout: the 2-bar confirmation plus 1-pip offset filter produces a small handful of entries per day per symbol, with a wide 4000-point default stop. The profit-lock ladder and break-even are off by default, so the raw output without tuning is wide-stop breakout with rare exits — long, drawn-out trades that close either at the hard stop or at a profit-lock tier after a sizeable move. Tuning the entry period, the offset, and the profit-lock step together is the main optimisation surface.

Strategy Deep Dive

Every tick runs OnTick which first checks terminal trade permission, refreshes the symbol, evaluates the session and EOD windows, and applies session-end and EOD force-closes before touching the position loop. ManageOpenPositions then walks the open tickets by magic and symbol, and chains hard-SL application, trailing stop, break-even, profit-lock, time-based close, and the indicator exit hook in that order on every ticket. The signal engine in GetEntrySignal samples the previous InpDonchianPeriod bars via iHighest and iLowest, applies the optional 1-pip offset, and checks the 2-bar confirmation together with the strong-candle filter before allowing a new entry. The 3-retry scaffold in TryClose_EX17016, TryClosePartial_EX17016, and TryModify_EX17016 retries on requote, timeout, and price-change return codes, sleeping 200 ms between close attempts and 100 ms between modify attempts. The three placeholders — GetExitSignal, GetIndicatorStopLoss, GetIndicatorTakeProfit — return zero values and are explicitly called from the management chain so that an indicator stack can be added without re-architecting the entry or risk layers.

Entry Signal

The Donchian Channel breakout is built from InpDonchianPeriod (default 10) previous bars, shifted by InpDonchianShift (default 1) to skip the still-forming bar. A long fires when the current close prints above the upper band after two prior closes were at or below it, with the optional strong-candle filter requiring a 60% body. A short mirrors the logic in the opposite direction. The InpDonchianOffsetPips (default 1 pip) widens the breakout threshold to suppress marginal pokes.

Exit Signal

Exits default to the hard stop-loss or to a profit-lock ratchet: once the price has travelled InpProfitLockTriggerPoints (1000 points) in favour, the stop moves to current_price - InpProfitLockSecurePoints (500 points behind), then ratchets in steps of at least InpProfitLockStepPoints (500 points). Indicator-driven exits via GetExitSignal return false by default, leaving the placeholder open for a custom hook. Optional trailing stop, break-even, and time-based close (default 120 minutes) can be turned on to add additional exit paths.

Stop Loss

A hard stop of InpHardSL_Points (default 4000 points) sits beneath every entry, optionally switched off when the user wants to leave the position to the profit-lock chain or to the indicator hooks. The break-even module moves the stop to entry + 2 points once the price has travelled InpBreakEvenTriggerPoints (default 30 points) in favour. Trailing-stop and ATR-stop (period 14, multiplier 2.0) are off by default and can be turned on as a secondary stop.

Take Profit

The fixed take profit is set to 100000 points by default — effectively a disabled TP that lets the management chain handle the close. Indicator-driven take profit via GetIndicatorTakeProfit overrides the fixed value when the hook is filled. Time-based exit (default 120 minutes) and session-end force-close (default off) provide additional take-profit-style exits.

Best For

The 4000-point default stop, the per-position 0.01 fixed lot, and the wide profit-lock tiers are sized for a $100 micro account trading XAUUSD on M5H1, where the wider stops absorb gold's typical intraday volatility without over-leveraging. The Donchian breakout plus 2-bar confirmation produces a small handful of entries per day per symbol, which suits traders who want a moderate breakout frequency rather than a scalper. The 3-loss pause and 20% drawdown cap fit a discretionary trader who wants a hard cool-off after a bad streak, while the auto-scaled lot mode (0.01 per 1000 capital) scales cleanly up to a $10k account. A low-spread ECN broker with reliable requote handling is required to make the 3-retry execution layer useful.

Strategy Logic

Pipsgrowth EX17016 Volatility — Strategy Logic Analysis (from .mq5 source)

Family: Volatility Magic: 22217016 Version: 2.00

BRIEF: Universal EA template with Donchian Channel breakout entry, comprehensive trade management including profit locking, trailing stops, session control, and smart exit. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • StringToTime()
  • Log()
  • IsTradingDayAllowed()
  • IsWithinTradingSession()
  • HandleSessionAndEndOfDayClosures()
  • CalculateLotSize()
  • IsDrawdownLimitOk()
  • CountOpenTradesByMagic()
  • CanOpenNewTrade()
  • ApplyHardSL_TP_IfNotSet()
  • ApplyTrailingStop()
  • ApplyBreakEven()
  • ...and 13 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (68 total across 8 groups):

  • [=== Trade Settings ===] InpTradeComment = "Psgrowth.com Expert_17016" // Trade comment for orders
  • [=== Trade Settings ===] InpLotSize = 0.01 // Fixed Lot Size (if LotSizingMethod is LOT_FIXED)
  • [=== Trade Settings ===] InpMagicNumber = 22217016 // Magic Number for orders
  • [=== Trade Settings ===] InpMaxSlippage = 3 // Slippage in points
  • [=== Trade Settings ===] InpMaxSpreadPoints = 25 // Maximum allowed spread in points (0 for none)
  • [=== Trade Settings ===] InpOneTradeOnly = false // Allow only one trade at a time (per symbol for this EA)
  • [=== Trade Settings ===] InpMaxOpenTrades = 10 // Maximum allowed open trades at the same time
  • [=== Trade Settings ===] InpAllowOnlyProfitableAdditions = true // Open new trades only if all existing (by this EA) are in profit
  • [=== Trade Settings ===] InpMinProfitPerTradeToAdd = 1600 // Min. profit in points for each existing trade to open new one
  • [=== Trade Settings ===] InpMaxDrawdownPercent = 20.0 // Max drawdown % allowed (0 to disable)
  • [=== Trade Settings ===] InpMaxDrawdownAmount = 0.0 // Max drawdown amount in account currency (0 to disable)
  • [=== Trade Settings ===] InpMaxTradesPerDay = 5 // Max trades per day (0 for unlimited)
  • [=== Trade Settings ===] InpMinBarsBetweenTrades = 1 // Min bars between opening new trades
  • [=== Trade Settings ===] InpMaxConsecutiveLosingTrades = 3 // Pause trading after this many consecutive losses (0 to disable)
  • [=== Trade Settings ===] InpPauseMinutesAfterLosingStreak = 60 // Minutes to pause after reaching losing streak
  • [=== Trade Settings ===] InpRequireProfitLockForAdditions = true // Require profit to be locked before adding new trades
  • [=== Money Management & Lot Sizing ===] InpLotSizingMethod = LOT_FIXED // Lot Sizing Method
  • [=== Money Management & Lot Sizing ===] InpAutoLotBaseType = BASE_ACCOUNT_EQUITY // Capital base for auto lot calculation
  • [=== Money Management & Lot Sizing ===] InpAutoLot_Increment = 0.01 // Lot size to add (e.g., 0.01)
  • [=== Money Management & Lot Sizing ===] InpAutoLot_CapitalPerIncrement = 1000 // For every X amount of capital
  • [=== Money Management & Lot Sizing ===] InpAutoLot_MaxAllowedLot = 10.0 // Maximum lot size allowed by auto calculation
  • [=== Money Management & Lot Sizing ===] InpAutoLot_MinAllowedLot = 0.01 // Minimum lot size allowed by auto calculation
  • [=== Money Management & Lot Sizing ===] InpOrderType = ORDER_TYPE_BUY_SELL // Order type
  • [=== Stop Loss Management ===] InpUseHardSL = true // Enable Hard Stop Loss
  • [=== Stop Loss Management ===] InpHardSL_Points = 4000 // Fixed Stop Loss in points (0 to disable)
  • [=== Stop Loss Management ===] InpUseTrailingStop = false // Enable Trailing Stop
  • [=== Stop Loss Management ===] InpTrailingStop_Points = 2000 // Trailing Stop activation in points of profit
  • [=== Stop Loss Management ===] InpTrailingStep_Points = 2000 // Trailing Stop step in points
  • [=== Stop Loss Management ===] InpUseATRStop = false // Use ATR-based stop loss (Placeholder for indicator logic)
  • [=== Stop Loss Management ===] InpATR_SL_Period = 14 // ATR period for SL calculation
  • [=== Stop Loss Management ===] InpATR_SL_Multiplier = 2.0 // ATR multiplier for SL
  • [=== Stop Loss Management ===] InpMoveSLToBreakEven = false // Move SL to breakeven after X points
  • [=== Stop Loss Management ===] InpBreakEvenTriggerPoints = 30 // Points in profit to trigger breakeven move
  • [=== Stop Loss Management ===] InpBreakEvenLockPoints = 2 // Lock X points profit at breakeven (e.g., entry + 2 points)
  • [=== Stop Loss Management ===] InpUseTimeBasedSL = false // Close trade after X minutes
  • [=== Stop Loss Management ===] InpTimeBasedSLMinutes = 120 // Minutes before time-based SL triggers
  • [=== Take Profit & Profit Management ===] InpFixedTP_Points = 100000 // Fixed Take Profit in points (0 to disable)
  • [=== Take Profit & Profit Management ===] InpUseProfitLock = true // Enable dynamic profit locking
  • [=== Take Profit & Profit Management ===] InpProfitLockTriggerPoints = 1000 // Start locking profit after this many points in profit
  • [=== Take Profit & Profit Management ===] InpProfitLockStepPoints = 500 // Move SL every X points further in profit (after trigger)
  • [=== Take Profit & Profit Management ===] InpProfitLockSecurePoints = 500 // How many points behind current price to lock (e.g., if price moves 20, SL moves to current - 10)
  • [=== Take Profit & Profit Management ===] InpProfitLockOnlyAfterBE = true // Only start profit lock after breakeven is reached
  • [=== Sessions Control Settings ===] InpEnableSessionControl = false // Enable sessions control
  • [=== Sessions Control Settings ===] InpEnableSession1 = true // Enable session 1
  • [=== Sessions Control Settings ===] InpSession1Start = "08:00" // Session 1 start time (HH:MM server time)
  • [=== Sessions Control Settings ===] InpSession1End = "16:00" // Session 1 end time (HH:MM server time)
  • [=== Sessions Control Settings ===] InpEnableSession2 = false // Enable session 2
  • [=== Sessions Control Settings ===] InpEnableSession3 = false // Enable session 3
  • [=== Sessions Control Settings ===] InpSession3End = "00:00" // Example: Not used
  • [=== Sessions Control Settings ===] InpPauseBeforeEndOfSession = true // Stop opening new trades before end of active session
  • [=== Sessions Control Settings ===] InpPauseMinutesBeforeEndOfSession = 30 // Minutes before end of session to pause new trades
  • [=== Sessions Control Settings ===] InpForceCloseAllTradesAtSessionEnd = false // Force close all trades at the end of an active session
  • [=== Sessions Control Settings ===] InpForceCloseMinutesBeforeSessionEnd = 5 // Minutes before session end to force close
  • [=== Sessions Control Settings ===] InpCloseAllTradesAtEndOfDay = false // Close all trades at specific EOD time
  • [=== Sessions Control Settings ===] InpEndOfDayCloseTime = "23:50" // EOD time to close all trades (HH:MM server time)
  • [=== Smart Exit Timing Settings ===] InpEnableSmartExitManagement = false // Enable Smart Exit Management (currently simplified)
  • [=== Smart Exit Timing Settings ===] InpSmartExitStartMinutesBeforeSessionEnd = 60 // When to start "smartly" managing (e.g., no new trades, check for early profitable close)
  • [=== Smart Exit Timing Settings ===] InpUseTrendConfirmationDuringSmartExit = true // Placeholder: To be used by GetExitSignal
  • [=== Notifications & Logging ===] InpEnableAlerts = true // Enable Terminal Alerts for important events
  • [=== Notifications & Logging ===] InpEnableEmailNotify = false // Enable Email Notifications
  • [=== Notifications & Logging ===] InpEnablePushNotify = false // Enable Push Notifications
  • [=== Notifications & Logging ===] InpLogTradeEvents = true // Log trade open/close/modify events
  • [=== Notifications & Logging ===] InpLogTickEvents = false // Log detailed tick processing (for debugging, can be verbose)
  • [=== Donchian Channel ===] InpDonchianPeriod = 10 // Donchian Channel period
  • [=== Donchian Channel ===] InpDonchianShift = 1 // Shift for Donchian calculation (1 = previous closed bar)
  • [=== Donchian Channel ===] InpDonchianConfirmBars = 2 // Number of bars to confirm breakout
  • [=== Donchian Channel ===] InpDonchianOffsetPips = 1.0 // Offset in pips for breakout buffer
  • [=== Donchian Channel ===] InpRequireStrongCandle = true // Require strong candle for entry (body >= 60% of range)
Pseudocode
// Pipsgrowth EX17016 Volatility — Execution Flow (from source analysis)
// Family: Volatility
// Universal EA template with Donchian Channel breakout entry, comprehensive trade management including profit locking, trailing stops, session control, and smart exit. 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 a chart matching the recommended timeframe
  7. 7Configure parameters according to the table on this page
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InpTradeComment"Psgrowth.com Expert_17016"Trade comment for orders
InpLotSize0.01Fixed Lot Size (if LotSizingMethod is LOT_FIXED)
InpMagicNumber22217016Magic Number for orders
InpMaxSlippage3Slippage in points
InpMaxSpreadPoints25Maximum allowed spread in points (0 for none)
InpOneTradeOnlyfalseAllow only one trade at a time (per symbol for this EA)
InpMaxOpenTrades10Maximum allowed open trades at the same time
InpAllowOnlyProfitableAdditionstrueOpen new trades only if all existing (by this EA) are in profit
InpMinProfitPerTradeToAdd1600Min. profit in points for each existing trade to open new one
InpMaxDrawdownPercent20.0Max drawdown % allowed (0 to disable)
InpMaxDrawdownAmount0.0Max drawdown amount in account currency (0 to disable)
InpMaxTradesPerDay5Max trades per day (0 for unlimited)
InpMinBarsBetweenTrades1Min bars between opening new trades
InpMaxConsecutiveLosingTrades3Pause trading after this many consecutive losses (0 to disable)
InpPauseMinutesAfterLosingStreak60Minutes to pause after reaching losing streak
InpRequireProfitLockForAdditionstrueRequire profit to be locked before adding new trades
InpLotSizingMethodLOT_FIXEDLot Sizing Method
InpAutoLotBaseTypeBASE_ACCOUNT_EQUITYCapital base for auto lot calculation
InpAutoLot_Increment0.01Lot size to add (e.g., 0.01)
InpAutoLot_CapitalPerIncrement1000For every X amount of capital
InpAutoLot_MaxAllowedLot10.0Maximum lot size allowed by auto calculation
InpAutoLot_MinAllowedLot0.01Minimum lot size allowed by auto calculation
InpOrderTypeORDER_TYPE_BUY_SELLOrder type
InpUseHardSLtrueEnable Hard Stop Loss
InpHardSL_Points4000Fixed Stop Loss in points (0 to disable)
InpUseTrailingStopfalseEnable Trailing Stop
InpTrailingStop_Points2000Trailing Stop activation in points of profit
InpTrailingStep_Points2000Trailing Stop step in points
InpUseATRStopfalseUse ATR-based stop loss (Placeholder for indicator logic)
InpATR_SL_Period14ATR period for SL calculation
InpATR_SL_Multiplier2.0ATR multiplier for SL
InpMoveSLToBreakEvenfalseMove SL to breakeven after X points
InpBreakEvenTriggerPoints30Points in profit to trigger breakeven move
InpBreakEvenLockPoints2Lock X points profit at breakeven (e.g., entry + 2 points)
InpUseTimeBasedSLfalseClose trade after X minutes
InpTimeBasedSLMinutes120Minutes before time-based SL triggers
InpFixedTP_Points100000Fixed Take Profit in points (0 to disable)
InpUseProfitLocktrueEnable dynamic profit locking
InpProfitLockTriggerPoints1000Start locking profit after this many points in profit
InpProfitLockStepPoints500Move SL every X points further in profit (after trigger)
InpProfitLockSecurePoints500How many points behind current price to lock (e.g., if price moves 20, SL moves to current - 10)
InpProfitLockOnlyAfterBEtrueOnly start profit lock after breakeven is reached
InpEnableSessionControlfalseEnable sessions control
InpEnableSession1trueEnable session 1
InpSession1Start"08:00"Session 1 start time (HH:MM server time)
InpSession1End"16:00"Session 1 end time (HH:MM server time)
InpEnableSession2falseEnable session 2
InpEnableSession3falseEnable session 3
InpSession3End"00:00"Example: Not used
InpPauseBeforeEndOfSessiontrueStop opening new trades before end of active session
InpPauseMinutesBeforeEndOfSession30Minutes before end of session to pause new trades
InpForceCloseAllTradesAtSessionEndfalseForce close all trades at the end of an active session
InpForceCloseMinutesBeforeSessionEnd5Minutes before session end to force close
InpCloseAllTradesAtEndOfDayfalseClose all trades at specific EOD time
InpEndOfDayCloseTime"23:50"EOD time to close all trades (HH:MM server time)
InpEnableSmartExitManagementfalseEnable Smart Exit Management (currently simplified)
InpSmartExitStartMinutesBeforeSessionEnd60When to start "smartly" managing (e.g., no new trades, check for early profitable close)
InpUseTrendConfirmationDuringSmartExittruePlaceholder: To be used by GetExitSignal
InpEnableAlertstrueEnable Terminal Alerts for important events
InpEnableEmailNotifyfalseEnable Email Notifications
InpEnablePushNotifyfalseEnable Push Notifications
InpLogTradeEventstrueLog trade open/close/modify events
InpLogTickEventsfalseLog detailed tick processing (for debugging, can be verbose)
InpDonchianPeriod10Donchian Channel period
InpDonchianShift1Shift for Donchian calculation (1 = previous closed bar)
InpDonchianConfirmBars2Number of bars to confirm breakout
InpDonchianOffsetPips1.0Offset in pips for breakout buffer
InpRequireStrongCandletrueRequire strong candle for entry (body >= 60% of range)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX17016.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX17016 GB_1_4 — Universal EA template with Donchian Channel breakout, full 12-layer stack."

// Include Trade class
#include <Trade/Trade.mqh>
#include <Trade/AccountInfo.mqh>
#include <Trade/SymbolInfo.mqh>

// --- Global Variables ---
CTrade        trade;
CAccountInfo  account;
CSymbolInfo   mySymbol;

// EA State Variables
long          g_last_trade_bar_time = 0;
int           g_consecutive_losses = 0;
datetime      g_pause_until_time = 0;
int           g_daily_trades_count = 0;
datetime      g_last_daily_trades_reset_time = 0;

// --- Input Parameters ---

//--- Trade Settings
input group "=== Trade Settings ==="
input string   InpTradeComment        = "Psgrowth.com Expert_17016";  // Trade comment for orders
input double InpLotSize = 0.01;                   // Fixed Lot Size (if LotSizingMethod is LOT_FIXED)
input ulong  InpMagicNumber = 22217016;              // Magic Number for orders
input int    InpMaxSlippage = 3;                  // Slippage in points
input int    InpMaxSpreadPoints = 25;             // Maximum allowed spread in points (0 for none)
input bool   InpOneTradeOnly = false;              // Allow only one trade at a time (per symbol for this EA)
input int    InpMaxOpenTrades = 10;                // Maximum allowed open trades at the same time
input bool   InpAllowOnlyProfitableAdditions = true; // Open new trades only if all existing (by this EA) are in profit
input double InpMinProfitPerTradeToAdd = 1600;     // Min. profit in points for each existing trade to open new one
input double InpMaxDrawdownPercent = 20.0;        // Max drawdown % allowed (0 to disable)
input double InpMaxDrawdownAmount = 0.0;          // Max drawdown amount in account currency (0 to disable)
input int    InpMaxTradesPerDay = 5;              // Max trades per day (0 for unlimited)
input int    InpMinBarsBetweenTrades = 1;         // Min bars between opening new trades
input int    InpMaxConsecutiveLosingTrades = 3;   // Pause trading after this many consecutive losses (0 to disable)
input int    InpPauseMinutesAfterLosingStreak = 60; // Minutes to pause after reaching losing streak
input bool   InpRequireProfitLockForAdditions = true;   // Require profit to be locked before adding new trades

// --- Money Management & Lot Sizing ---
input group "=== Money Management & Lot Sizing ==="
enum ENUM_LOT_SIZING_METHOD
  {
   LOT_FIXED,              // Use the 'LotSize' specified in "Trade Settings"
   LOT_AUTO_SCALED         // Automatically calculate lot size based on capital
  };
input ENUM_LOT_SIZING_METHOD InpLotSizingMethod = LOT_FIXED; // Lot Sizing Method

// --- Settings for LOT_AUTO_SCALED ---
enum ENUM_AUTO_LOT_BASE_TYPE
  {
   BASE_ACCOUNT_BALANCE,   // Calculate based on Account Balance
   BASE_ACCOUNT_EQUITY     // Calculate based on Account Equity
  };
input ENUM_AUTO_LOT_BASE_TYPE InpAutoLotBaseType = BASE_ACCOUNT_EQUITY; // Capital base for auto lot calculation

Full source code available on download

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

Tags:ex17016volatilitypipsgrowthfreemt5xauusd

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