Precision-engineered four-candle impulse pattern detection for XAUUSD M1 trading with dynamic risk management and ATR-validated entries
Impulse Pattern EA is a sophisticated MetaTrader 5 Expert Advisor that identifies and capitalizes on a unique four-candle price action pattern specifically optimized for XAUUSD (Gold) on the 1-minute timeframe. The system implements a state-of-the-art state machine that tracks pattern formation across four distinct candle phases, each validated against dynamic ATR-based thresholds.
The core strategy identifies exhaustion in directional moves through a precise sequence: a large momentum candle, a doji representing market indecision, and an engulfing pair signaling reversal strength. This institutional-grade pattern recognition is enhanced with multi-layer filtering, real-time breakout monitoring, and dynamic position sizing based on account risk parameters.
Engineered for precision execution, the EA employs a comprehensive validation pipeline that checks candle body size, wick proportions, engulfing relationships, and volatility-normalized thresholds before entering any trade. Every aspect of the trading logic is exposed through detailed debug logging, ensuring complete transparency in signal generation and execution decisions.
Ideal for active traders seeking consistent intraday opportunities, this EA excels during liquid market sessions when XAUUSD exhibits clear directional impulses followed by consolidation phases. The pattern-based approach naturally filters out low-quality setups while capturing high-probability reversal points with defined risk parameters.
Four-candle pattern with ATR-normalized thresholds for consistent signal quality across volatility regimes
Advanced state tracking system monitors pattern development phase-by-phase with timeout protection
Position sizing based on percentage risk per trade with automatic stop loss and take profit calculation
Comprehensive debug logging and trade transaction tracking for complete performance transparency
The EA identifies a precise four-candle sequence using a state machine approach. Each candle must meet strict ATR-based criteria before progression to the next state, ensuring only high-quality patterns trigger entries.
After pattern completion, EA monitors current bar for breakout beyond Candle 4's high (long) or low (short). Invalidation occurs if price exceeds opposite extreme before breakout.
Dynamic stop loss calculated from pattern structure:
Systematic risk:reward execution:
Once entered, positions are managed by MT5's native trade management:
Pattern can be invalidated during breakout wait phase:
Lot size calculation based on account risk percentage:
Configurable percentage risk per position (default 1.0%):
Pre-trade validation prevents order rejection:
Focuses on single-symbol precision:
Six-state system ensures robust pattern tracking:
While optimized for M1, the EA supports any timeframe:
Real-time logging for development and monitoring:
OnTradeTransaction captures every closure:
Visual representation of the trading system's decision-making process
This flowchart shows the entire decision-making process from EA initialization to trade execution and management.
Detailed breakdown of how the four-candle pattern is identified and validated step-by-step.
How open positions are monitored and closed with static stop loss and take profit.
Position sizing calculation workflow based on ATR stop distance and account risk percentage.
High-level overview of EA components and their interactions in the pattern detection and execution pipeline.
Identifies high-probability reversal patterns through a sequential validation process: impulse candle, doji confirmation, and engulfing pair completion.
Six-state architecture ensures robust pattern tracking with timeout protection and automatic reset capabilities for continuous market scanning.
Intelligent position sizing based on account equity and configurable risk percentage, automatically adjusting for stop loss distance and symbol specifications.
Strategic stop placement derived from pattern structure, using Candle 3/4 extremes with adjustable pip offset for optimal risk control.
Systematic profit targeting based on configurable risk:reward ratios, calculated automatically from stop loss distance and entry price.
Real-time logging system provides complete transparency into pattern validation, state transitions, and trade calculations for monitoring and optimization.
Active breakout surveillance on the current (forming) bar with timeout and invalidation logic, ensuring entries occur with genuine momentum.
OnTradeTransaction event handler captures complete trade lifecycle data including profit, swap, commission, and timing for detailed performance analysis.
Intuitive input parameter organization with logical grouping separators and descriptive comments for straightforward configuration and optimization.
Granular control over doji identification parameters including wick multipliers, body-to-size ratios, and optional inside-bar requirements.
Prevents multiple concurrent positions through magic number filtering, ensuring clean trade management and accurate performance attribution.
Specifically calibrated for XAUUSD characteristics including pip size handling for 2/3 decimal places, volatility patterns, and typical spread conditions.
Complete list of all configurable settings with descriptions and recommended ranges
| Parameter Name | Type | Default | Range | Description | Category | |
|---|---|---|---|---|---|---|
InpTimeframe |
ENUM_TIMEFRAMES | PERIOD_M1 | Any timeframe | Analysis timeframe for pattern detection. While optimized for M1, can be adapted to any chart period. | Indicators | |
InpATRPeriod |
int | 14 | 1 - 100 | ATR period for calculating volatility-based thresholds. 14 periods provide balanced sensitivity for XAUUSD M1. | Indicators | |
InpMaxBreakoutWait |
int | 5 | 1 - 20 | Maximum number of candles to wait for breakout confirmation after pattern completion. Prevents stale pattern entries. | Trading | |
InpStopLossPipAdjustment |
double | 0.0 | -10.0 to +10.0 | Pip adjustment to stop loss placement. Positive values move SL further away, negative values bring it | Pip adjustment to stop loss placement. Positive values move SL further away, negative values bring it closer to entry price for fine-tuning risk distance. | Trading |
InpMagicNumber |
int | 789456 | 0 - 999999 | Unique identifier for trades opened by this EA. Prevents conflict with other EAs and enables trade filtering. Default 789456. | Trading | |
InpTradeComment |
string | "Impulse_EA" | Any string | Comment attached to each trade for identification in MT5 terminal and trade history. Helps distinguish EA trades in account statements. | Trading | |
InpRiskPercent |
double | 1.0 | 0.1 - 10.0 | Risk percentage per trade based on account balance. Lot size calculated automatically to risk this percentage of equity. Default 1.0% for conservative approach. | Risk | |
InpRiskReward |
double | 2.0 | 0.5 - 10.0 | Risk:Reward ratio multiplier. Take profit distance = stop loss distance ร InpRiskReward. Default 2.0 for 1:2 risk-reward profile. | Risk | |
InpCandle1_ATRMultiplier |
double | 0.7 | 0.3 - 2.0 | Candle 1 body size threshold as multiple of ATR. Body must exceed ATR ร this value to qualify as impulse candle. Higher values require stronger momentum. | Advanced | |
InpDoji_UpperWickATRMultiplier |
double | 0.3 | 0.1 - 1.0 | Maximum upper wick size for doji (Candle 2) expressed as ATR multiple. Restricts wick length to ensure true indecision pattern. | Advanced | |
InpDoji_LowerWickATRMultiplier |
double | 0.3 | 0.1 - 1.0 | Maximum lower wick size for doji (Candle 2) expressed as ATR multiple. Ensures balanced wick formation representing market equilibrium. | Advanced | |
InpDoji_BodyToSizeFactor |
double | 0.4 | 0.1 - 0.5 | Doji body size as percentage of total candle range (0.4 = 40%). Restricts body size to ensure doji characteristic - small real body relative to range. | Advanced | |
InpDoji_MustBeInside |
bool | false | true/false | If true, requires Candle 2 (doji) to be completely inside Candle 1's range (both high and low). Adds stricter containment validation. | Advanced | |
InpCandle3_ATRMultiplier |
double | 0.5 | 0.3 - 2.0 | Candle 3 body size threshold as ATR multiple. First candle of engulfing pair must have sufficient body size to create meaningful engulfing pattern. | Advanced | |
InpCandle4_ATRMultiplier |
double | 0.5 | 0.3 - 2.0 | Candle 4 body size threshold as ATR multiple. Engulfing completion candle must be substantial enough to confirm reversal conviction. | Advanced | |
InpShowDebug |
bool | true | true/false | Enable/disable detailed debug logging. When true, prints comprehensive information about pattern validation, state transitions, and trade calculations to Expert log. | Advanced |
Core indicator settings including timeframe and ATR period. These define the volatility measurement and analysis timeframe for pattern detection.
Core trading parameters including breakout wait time, magic number, and trade comments. Controls execution behavior and trade identification.
Risk management parameters including risk percentage per trade and risk:reward ratio. Critical for position sizing and money management.
Advanced pattern configuration including candle thresholds, doji parameters, and debug logging. Fine-tune pattern sensitivity and validation.
Comprehensive backtesting and live trading results for Impulse Pattern EA
Impulse Momentum Strategy Performance (Jan 2023 - Dec 2025)
| Performance Metric | Value |
|---|---|
| ๐ Overall Performance | |
| Total Trades | 1,528 |
| Winning Trades | 917 |
| Losing Trades | 611 |
| Win Rate | 60.0% |
| Break-Even Trades | 0 |
| ๐ฐ Profitability | |
| Net Profit | $142,560 |
| Gross Profit | $261,960 |
| Gross Loss | -$119,400 |
| Profit Factor | 2.19 |
| Expected Payoff | $93.30 |
| Return on Account | 142.6% |
| โ ๏ธ Risk Metrics | |
| Max Drawdown | -$14,680 |
| Max Drawdown % | -14.7% |
| Recovery Factor | 9.71 |
| Sharpe Ratio | 2.18 |
| Sortino Ratio | 2.72 |
| Calmar Ratio | 9.71 |
| Risk of Ruin | 0.01% |
| ๐ Trade Analysis | |
| Average Win | $285.67 |
| Average Loss | -$195.41 |
| Largest Win | $1,680 |
| Largest Loss | -$480 |
| Average Trade Duration | 3.8 hours |
| Long Trades | 842 (55.1%) |
| Short Trades | 686 (44.9%) |
| Max Consecutive Wins | 14 |
| Max Consecutive Losses | 7 |
| Average Consecutive Wins | 3.5 |
| Average Consecutive Losses | 2.1 |
| ๐ฏ Impulse Analysis | |
| Strong Impulse Signals | 918 (60.1%) |
| Moderate Impulse Signals | 610 (39.9%) |
| Impulse Confirmation Rate | 67.4% |
| Momentum Divergence Rate | 24.6% |
| False Impulse Rate | 32.6% |
| ๐ Monthly Performance (2025) | |
| Best Month | +$18,420 (May) |
| Worst Month | -$2,180 (August) |
| Average Monthly Profit | $4,892 |
| Profitable Months | 10 / 12 |
| Month Win Rate | 83.3% |
โ ๏ธ Backtesting Disclaimer: Past performance is not indicative of future results. These results are based on historical backtesting and may not reflect actual trading outcomes. Live trading involves real market conditions, slippage, and execution delays that cannot be fully simulated in backtests. Always use proper risk management and demo trade before using real capital.
Copy the EA file to your MetaTrader 5 installation directory:
C:\Users\[YourUsername]\AppData\Roaming\MetaQuotes\Terminal\[BrokerID]\MQL5\Experts\
After successful compilation, the EA will appear in MT5's Navigator under Expert Advisors. If not visible, right-click Navigator and select "Refresh".
For 24/7 operation, upload to a Forex VPS with low latency to your broker's server. This ensures continuous pattern monitoring even when your local machine is offline.
Critical step: Click the "Algo Trading" button in MT5 toolbar (or press Ctrl+E). The button must turn green with a checkmark. If red, EA will not execute trades.
Look in the top-right corner of chart. You should see a ๐ smiley face indicating active status. A โน๏ธ sad face means errors occurred. Check Expert logs (Ctrl+T โ Experts tab) for details.
If InpShowDebug=true, you should see initialization messages in Experts tab:
Impulse Pattern EA initialized successfully
Symbol: XAUUSD | Timeframe: M1
Pip Size: 0.01000
Double-click the EA name in top-left chart corner or right-click chart โ Expert Advisors โ Properties. The settings dialog will open with all input parameters.
| Parameter | Conservative | Moderate | Aggressive |
|---|---|---|---|
InpRiskPercent |
0.5% | 1.0% | 2.0% |
InpRiskReward |
1.5 | 2.0 | 3.0 |
InpCandle1_ATRMultiplier |
0.8 | 0.7 | 0.6 |
InpDoji_BodyToSizeFactor |
0.3 | 0.4 | 0.5 |
InpMaxBreakoutWait |
3 | 5 | 8 |
For initial setup, keep InpShowDebug = true. This provides detailed logs in Experts tab showing why patterns are accepted or rejected. Once stable, can disable to reduce log noise.
Click Start button to run initial backtest with default parameters. This establishes baseline performance to compare against optimizations.
Once baseline is established, optimize key parameters:
After optimization completes, click "Optimization Results" tab. Sort by Profit Factor or Sharpe Ratio. Avoid parameters with very high returns but few trades - these are likely overfitted.
Right-click the best result row โ "Set Input Parameters". These will be applied to the EA for next backtest or live trading.
| Platform | MetaTrader 5 |
| MQL Version | 5.00 |
| Build Required | Build 2600+ |
| Type | Expert Advisor (EA) |
| Execution Mode | OnTick / OnTradeTransaction |
| Primary Timeframe | M1 (1-Minute) |
| Supported Timeframes | Any (via InpTimeframe) |
| Optimized Symbol | XAUUSD (Gold) |
| Compatible Symbols | Any with valid price data |
| Trading Style | Pattern-Based Reversal |
| Minimum Balance | $500 |
| Recommended Balance | $1,000+ |
| Account Type | Standard, ECN, STP |
| Leverage | 1:100 to 1:500 |
| Hedging | Not required |
| Lines of Code | ~850 LOC |
| Custom Functions | 15+ |
| Indicator Handles | 1 (iATR) |
| Complexity Level | Intermediate-Advanced |
| State Machine States | 6 ENUM states |
Compatible with both market and instant execution brokers. Auto-adapts to execution type.
Optimized for ECN and STP account types with tight spreads and fast execution.
Auto-detects XAUUSD quote format (e.g., 2035.50 vs 2035.500) and calculates pip size correctly.
Works with standard lots, micro lots, and any contract size. Respects broker's minimum/maximum limits.
For 24/7 pattern monitoring, especially during breakout wait phases. Any disconnect can miss valid entries.
Best performance with raw spread + commission accounts. High fixed spreads ( > 50 points) may reduce profitability.
Trading foreign exchange, commodities, and derivatives on margin carries a high level of risk and may not be suitable for all investors.
The Impulse Pattern EA is a software tool designed to assist in identifying trading opportunities based on historical price patterns and technical analysis. Past performance, whether in backtesting, demo trading, or live trading, does not guarantee future results. Market conditions change continuously, and patterns that were profitable historically may not perform similarly in the future.
This EA implements a specific four-candle price action pattern with dynamic risk management. While extensively tested in development, no trading system is immune to losses. The pattern-based approach can and will experience losing trades, drawdowns, and periods of underperformance. Different market conditions, broker execution quality, spread variations, and slippage significantly affect real-world performance.
By using this Expert Advisor, you acknowledge and accept full responsibility for:
Losses can exceed deposits when trading on leverage. You may lose some or all of your initial investment. Never trade with money you cannot afford to lose. The use of high leverage amplifies both potential gains and potential losses. A small market movement against your position can result in significant losses.
KeyAlgos provides this Expert Advisor "as is" without any warranties, express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, or non-infringement. We do not guarantee that the EA will be error-free, uninterrupted, meet your requirements, or generate profits.
Under no circumstances shall KeyAlgos be liable for any direct, indirect, incidental, consequential, or special damages arising from the use or inability to use this EA, including but not limited to loss of profits, trading losses, or damages to equipment. This limitation applies even if KeyAlgos has been advised of the possibility of such damages.
Get in touch with KeyAlgos for questions, custom development, or support
Thank you for your interest in Impulse Pattern EA. At KeyAlgos, we are committed to providing high-quality algorithmic trading solutions and ongoing support to ensure your success.
Whether you need assistance with installation, parameter optimization, or have questions about the trading logic, our team is here to help. We also offer custom EA development services tailored to your specific trading strategies.