MetaTrader 5 Expert Advisor v1.00

Impulse Pattern EA

Precision-engineered four-candle impulse pattern detection for XAUUSD M1 trading with dynamic risk management and ATR-validated entries

Pattern-Based Trading Style
M1 (1-Minute) Primary Timeframe
Moderate Risk Level
XAUUSD (Gold) Optimized Market

Overview

What It Does

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.

Key Highlights

๐ŸŽฏ

Precision Pattern

Four-candle pattern with ATR-normalized thresholds for consistent signal quality across volatility regimes

โšก

State Machine Logic

Advanced state tracking system monitors pattern development phase-by-phase with timeout protection

๐Ÿ›ก๏ธ

Dynamic Risk Control

Position sizing based on percentage risk per trade with automatic stop loss and take profit calculation

๐Ÿ“Š

Real-Time Monitoring

Comprehensive debug logging and trade transaction tracking for complete performance transparency

Methodology & Core Logic

๐ŸŸข

Entry Strategy

Pattern Sequence Detection

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.

Candle 1 - Impulse Detection

  • Large directional candle with body exceeding ATR ร— 0.7
  • Bearish for long setups, bullish for short setups
  • Validates momentum exhaustion at pattern start

Candle 2 - Doji Confirmation

  • Opposite direction doji with controlled wick sizes
  • Upper/lower wicks limited to ATR ร— 0.3 each
  • Body size restricted to 40% of total candle range
  • Optional inside-bar requirement relative to Candle 1

Candle 3 & 4 - Engulfing Validation

  • Candle 3: Continuation of Candle 1 direction with body > ATR ร— 0.5
  • Candle 4: Strong reversal engulfing Candle 3 completely
  • True engulfing requires open/close beyond Candle 3's range

Breakout Confirmation

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.

๐Ÿ”ด

Exit Strategy

Stop Loss Placement

Dynamic stop loss calculated from pattern structure:

  • Long trades: Below the lower of Candle 3/4 lows
  • Short trades: Above the higher of Candle 3/4 highs
  • Adjustable pip offset for fine-tuning distance
  • Normalized to symbol's tick size for precision

Take Profit Calculation

Systematic risk:reward execution:

  • Fixed ratio based on input parameter (default 1:2)
  • Calculated as entry price ยฑ (stop distance ร— reward multiplier)
  • Symmetric R:R ensures consistent profit targets

Position Management

Once entered, positions are managed by MT5's native trade management:

  • Stop loss remains static at initial level
  • Take profit locked at calculated target
  • No trailing stop or breakeven mechanisms
  • Full trade lifecycle logged via OnTradeTransaction

Trade Invalidation

Pattern can be invalidated during breakout wait phase:

  • Price exceeding opposite pattern extreme
  • Timeout after maximum candle wait (default 5 candles)
  • Immediate reset to STATE_IDLE for new pattern scan
๐Ÿ›ก๏ธ

Risk Management

Dynamic Position Sizing

Lot size calculation based on account risk percentage:

  • Risk amount = Account Balance ร— InpRiskPercent รท 100
  • Position size adjusted for stop loss distance
  • Respects symbol's minimum/maximum lot limits
  • Normalized to broker's lot step increments

Risk Per Trade

Configurable percentage risk per position (default 1.0%):

  • Ensures consistent risk across varying stop distances
  • Automatically scales lot size with account equity
  • Protects against over-leveraging during drawdowns

Trade Validation

Pre-trade validation prevents order rejection:

  • Stop distance meets broker's SYMBOL_TRADE_STOPS_LEVEL
  • Sufficient margin for calculated position size
  • Price levels normalized to tick size
  • Order filling type set to FOK (Fill or Kill)

No Correlation Management

Focuses on single-symbol precision:

  • No multi-position correlation checks
  • No hedging or position locking
  • Single position per EA instance
  • Complete isolation from other EAs via Magic Number
โš™๏ธ

Advanced Features

State Machine Architecture

Six-state system ensures robust pattern tracking:

  • STATE_IDLE: Scanning for initial impulse candle
  • STATE_CANDLE1_FOUND: Large candle validated
  • STATE_CANDLE2_FOUND: Doji requirements met
  • STATE_CANDLE3_FOUND: First engulfing candle confirmed
  • STATE_CANDLE4_FOUND: Pattern complete, awaiting breakout
  • STATE_WAITING_BREAKOUT: Active breakout monitoring with timeout

Timeframe Flexibility

While optimized for M1, the EA supports any timeframe:

  • Configurable via InpTimeframe parameter
  • ATR adapts automatically to selected period
  • Pattern logic remains consistent across timeframes

Debug Information

Real-time logging for development and monitoring:

  • Detailed rejection reasons for each candle validation
  • State transitions and variable values
  • Trade calculation parameters and final values
  • Breakout detection timing and price levels

Trade Lifecycle Tracking

OnTradeTransaction captures every closure:

  • Comprehensive profit/loss logging
  • Entry/exit price and time recording
  • Swap and commission tracking
  • Standardized output for external analysis

Logic Flow Diagrams

Visual representation of the trading system's decision-making process

Complete Trading Logic Flow

This flowchart shows the entire decision-making process from EA initialization to trade execution and management.

flowchart TD Start([EA Initialization]) --> Init{Initialize
Successfully?} Init -->|No| Error[Display Error
& Exit] Init -->|Yes| CheckMarket{Market
Open?} CheckMarket -->|No| Wait1[Wait for
Market Open] Wait1 --> CheckMarket CheckMarket -->|Yes| CheckTime{Timeframe
Active?} CheckTime -->|No| Wait2[Wait for
Timeframe] CheckTime -->|Yes| HasPos{Has Open
Position?} HasPos -->|Yes| Skip[Skip Analysis
- Manage Only] HasPos -->|No| ATRReady{ATR Data
Available?} ATRReady -->|No| Wait3[Wait for
Indicator Data] ATRReady -->|Yes| ProcessState[Process Current
State Machine] ProcessState --> StateIDLE{State =
STATE_IDLE?} StateIDLE -->|Yes| CheckC1[Check Candle 1
- Large Impulse] StateIDLE -->|No| StateC1{State =
STATE_CANDLE1_FOUND?} CheckC1 -->|Found| SetC1[Set State to
CANDLE1_FOUND] CheckC1 -->|Not Found| WaitNext[Wait Next
Candle] SetC1 --> StoreC1[Store Candle 1
Data & Direction] StoreC1 --> WaitNext StateC1 -->|Yes| CheckC2[Check Candle 2
- Doji Validation] StateC1 -->|No| StateC2{State =
STATE_CANDLE2_FOUND?} CheckC2 -->|Valid| SetC2[Set State to
CANDLE2_FOUND] CheckC2 -->|Invalid| Reset1[Reset to IDLE
& Log Rejection] SetC2 --> StoreC2[Store Candle 2
Data] StoreC2 --> WaitNext StateC2 -->|Yes| CheckC3[Check Candle 3
- Engulfing Start] StateC2 -->|No| StateC3{State =
STATE_CANDLE3_FOUND?} CheckC3 -->|Valid| SetC3[Set State to
CANDLE3_FOUND] CheckC3 -->|Invalid| Reset2[Reset to IDLE
& Log Rejection] SetC3 --> StoreC3[Store Candle 3
Data] StoreC3 --> WaitNext StateC3 -->|Yes| CheckC4[Check Candle 4
- Engulfing Complete] StateC3 -->|No| StateC4{State =
STATE_CANDLE4_FOUND?} CheckC4 -->|Valid| SetC4[Set State to
CANDLE4_FOUND] CheckC4 -->|Invalid| Reset3[Reset to IDLE
& Log Rejection] SetC4 --> StoreC4[Store Candle 4
Data] StoreC4 --> WaitBreakout[Wait for
Breakout Bar] StateC4 -->|Yes| MonitorBreakout[Monitor Current
Bar for Breakout] StateC4 -->|No| StateBO{State =
WAITING_BREAKOUT?} MonitorBreakout --> Breakout{Price Breaks
Candle 4 Level?} MonitorBreakout --> Timeout{Wait Count >
MaxBreakoutWait?} Breakout -->|Yes| CalcTrade[Calculate SL/TP
& Position Size] Timeout -->|Yes| Reset4[Reset to IDLE
- Pattern Timeout] Breakout -->|No| CheckInvalid{Price Breaks
Opposite Level?} CheckInvalid -->|Yes| Reset5[Reset to IDLE
- Pattern Invalid] CheckInvalid -->|No| Increment[Increment
Wait Counter] CalcTrade --> ValidateSLTP{Valid Stop
Levels?} ValidateSLTP -->|No| LogError[Log Validation
Error] ValidateSLTP -->|Yes| SendOrder[Send Market
Order] SendOrder --> OrderOK{Order
Successful?} OrderOK -->|Yes| LogSuccess[Log Trade
Details & Reset] OrderOK -->|No| LogFail[Log Failure
Reason] Reset1 --> WaitNext Reset2 --> WaitNext Reset3 --> WaitNext Reset4 --> WaitNext Reset5 --> WaitNext Increment --> WaitNext LogSuccess --> WaitNext LogError --> WaitNext style Start fill:#00d4ff,stroke:#00d4ff,stroke-width:3px,color:#000 style CalcTrade fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style SendOrder fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style LogSuccess fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style Error fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style Reset1 fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style Reset2 fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style Reset3 fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style Reset4 fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style Reset5 fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style LogFail fill:#ffaa00,stroke:#ffaa00,stroke-width:2px,color:#000 style CheckC1 fill:#151932,stroke:#00d4ff,stroke-width:2px style CheckC2 fill:#151932,stroke:#00d4ff,stroke-width:2px style CheckC3 fill:#151932,stroke:#00d4ff,stroke-width:2px style CheckC4 fill:#151932,stroke:#00d4ff,stroke-width:2px style MonitorBreakout fill:#151932,stroke:#00d4ff,stroke-width:2px style ValidateSLTP fill:#ffaa00,stroke:#ffaa00,stroke-width:2px

Entry Signal Detection Process

Detailed breakdown of how the four-candle pattern is identified and validated step-by-step.

flowchart TD NewBar([New Candle Closed]) --> ATR[Calculate ATR
for Validation] ATR --> StateCheck{Current State?} StateCheck -->|STATE_IDLE| CheckC1[Check Candle 1
- Impulse Size] StateCheck -->|CANDLE1_FOUND| CheckC2[Check Candle 2
- Doji Structure] StateCheck -->|CANDLE2_FOUND| CheckC3[Check Candle 3
- Engulfing Start] StateCheck -->|CANDLE3_FOUND| CheckC4[Check Candle 4
- Engulfing Complete] StateCheck -->|CANDLE4_FOUND| WaitBreak[Wait for
Breakout Bar] CheckC1 --> C1Body{Candle Body >
ATR ร— 0.7?} C1Body -->|No| RejectC1[Reject: Body Too Small
โ†’ Reset to IDLE] C1Body -->|Yes| C1Dir{Directional
Candle?} C1Dir -->|Long Setup: Bullish| RejectC1Dir[Reject: Wrong Direction
โ†’ Reset] C1Dir -->|Short Setup: Bearish| RejectC1Dir C1Dir -->|Long Setup: Bearish| AcceptC1[Accept Candle 1
โ†’ Store Data] C1Dir -->|Short Setup: Bullish| AcceptC1 AcceptC1 --> SetStateC1[Set State to
CANDLE1_FOUND] CheckC2 --> C2Dir{Opposite Direction
of C1?} C2Dir -->|No| RejectC2Dir[Reject: No Reversal
โ†’ Reset] C2Dir -->|Yes| C2Upper{C2 Upper Wick <
ATR ร— 0.3?} C2Upper -->|No| RejectC2Upper[Reject: Upper Wick Too Long] C2Upper -->|Yes| C2Lower{C2 Lower Wick <
ATR ร— 0.3?} C2Lower -->|No| RejectC2Lower[Reject: Lower Wick Too Long] C2Lower -->|Yes| C2BodySize{C2 Body <
Size ร— 0.4?} C2BodySize -->|No| RejectC2Body[Reject: Body Too Large
Not Doji] C2BodySize -->|Yes| C2Inside{Inside C1
if Required?} C2Inside -->|No & Required| RejectC2Inside[Reject: Not Inside Bar] C2Inside -->|Yes or Not Required| AcceptC2[Accept Candle 2
โ†’ Store Data] AcceptC2 --> SetStateC2[Set State to
CANDLE2_FOUND] CheckC3 --> C3Body{C3 Body >
ATR ร— 0.5?} C3Body -->|No| RejectC3Body[Reject: Body Too Small
โ†’ Reset] C3Body -->|Yes| C3Dir{Same Direction
as C1?} C3Dir -->|No| RejectC3Dir[Reject: Wrong Direction] C3Dir -->|Yes| AcceptC3[Accept Candle 3
โ†’ Engulfing Start] AcceptC3 --> SetStateC3[Set State to
CANDLE3_FOUND] CheckC4 --> C4Body{C4 Body >
ATR ร— 0.5?} C4Body -->|No| RejectC4Body[Reject: Body Too Small
โ†’ Reset] C4Body -->|Yes| C4Dir{Opposite Direction
of C3?} C4Dir -->|No| RejectC4Dir[Reject: Wrong Direction] C4Dir -->|Yes| C4Engulf{True Engulf?
C4 OC beyond C3 OC?} C4Engulf -->|No| RejectC4Engulf[Reject: Not True Engulfing] C4Engulf -->|Yes| AcceptPattern[Accept Full Pattern
โ†’ Store C4] AcceptPattern --> SetStateC4[Set State to
CANDLE4_FOUND
โ†’ Wait Breakout] WaitBreak --> Monitor{Monitor Current
Bar Price} Monitor --> Breakout{Price Breaks
C4 Extreme?} Monitor --> Invalid{Price Breaks
Opposite Extreme?} Breakout -->|Yes| Execute[Execute Trade
โ†’ Calculate SL/TP] Invalid -->|Yes| ResetInvalid[Reset Pattern
- Invalidated] RejectC1 --> NewBar RejectC1Dir --> NewBar RejectC2Dir --> NewBar RejectC2Upper --> NewBar RejectC2Lower --> NewBar RejectC2Body --> NewBar RejectC2Inside --> NewBar RejectC3Body --> NewBar RejectC3Dir --> NewBar RejectC4Body --> NewBar RejectC4Dir --> NewBar RejectC4Engulf --> NewBar ResetInvalid --> NewBar Execute --> ResetExecute[Reset to IDLE
- Trade Opened] ResetExecute --> NewBar style NewBar fill:#00d4ff,stroke:#00d4ff,stroke-width:3px,color:#000 style AcceptPattern fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style Execute fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style SetStateC4 fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style RejectC1 fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style RejectC2Dir fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style RejectC4Engulf fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style ResetInvalid fill:#ffaa00,stroke:#ffaa00,stroke-width:2px,color:#000

Exit Strategy & Position Management

How open positions are monitored and closed with static stop loss and take profit.

flowchart TD PositionOpen([Position Opened]) --> LogOpen[Log Entry Details
- Price, Lot, Direction] LogOpen --> MonitorSL[Monitor Stop Loss
Level] LogOpen --> MonitorTP[Monitor Take Profit
Level] MonitorSL --> SLHit{Price Reaches
Stop Loss?} MonitorTP --> TPHit{Price Reaches
Take Profit?} SLHit -->|Yes| CloseSL[Close Position
at Stop Loss] SLHit -->|No| Continue[Continue
Monitoring] TPHit -->|Yes| CloseTP[Close Position
at Take Profit] TPHit -->|No| Continue CloseSL --> LogSL[Log Loss Details
- Time, P/L, Swap] CloseTP --> LogTP[Log Profit Details
- Time, P/L, Swap] LogSL --> OnTradeTrans[OnTradeTransaction
- DEAL_ENTRY_OUT] LogTP --> OnTradeTrans OnTradeTrans --> PrintDetails["Print TRADE_CLOSED
Time | Profit | Type | Symbol"] PrintDetails --> UpdateStats[Update Strategy
Performance Stats] Continue --> CheckClose{Manual Close
or Expiration?} CheckClose -->|Yes| CloseManual[Close Position
Manually] CheckClose -->|No| MonitorSL CloseManual --> LogManual[Log Manual Close] LogManual --> OnTradeTrans UpdateStats --> End([Position Lifecycle
Complete]) style PositionOpen fill:#00d4ff,stroke:#00d4ff,stroke-width:3px,color:#000 style CloseSL fill:#ff0055,stroke:#ff0055,stroke-width:3px,color:#fff style CloseTP fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style CloseManual fill:#ffaa00,stroke:#ffaa00,stroke-width:2px,color:#000 style End fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff

Risk Management System

Position sizing calculation workflow based on ATR stop distance and account risk percentage.

flowchart TD SignalValidated([Entry Signal
Validated]) --> GetAccount[Get Account
Balance & Equity] GetAccount --> CalcRiskAmt[Calculate Risk Amount
Balance ร— InpRiskPercent รท 100] CalcRiskAmt --> GetSLDist[Get Stop Loss
Distance in Points] GetSLDist --> GetTick[Get Symbol
Tick Value & Size] GetTick --> CalcTicks[Calculate Ticks
in Stop Distance] CalcTicks --> CalcRawLot[Calculate Raw
Lot Size
Risk รท Ticks ร— TickValue] CalcRawLot --> ApplyLimits{Within Min/Max
Lot Limits?} ApplyLimits -->|Too Small| UseMin[Use Minimum
Lot Size] ApplyLimits -->|Too Large| UseMax[Use Maximum
Lot Size] ApplyLimits -->|Within Range| NormalizeLot[Normalize to
Lot Step] UseMin --> RoundLot[Round to
Lot Step] UseMax --> RoundLot NormalizeLot --> RoundLot RoundLot --> CheckMargin{Sufficient
Free Margin?} CheckMargin -->|No| RejectMargin[Reject Trade
- Insufficient Margin] CheckMargin -->|Yes| FinalLot[Final Lot Size
Confirmed] RejectMargin --> LogReject[Log Rejection
Reason] FinalLot --> Execute[Execute Trade
with Calculated Size] LogReject --> End([Trade Denied]) Execute --> End style SignalValidated fill:#00d4ff,stroke:#00d4ff,stroke-width:2px,color:#000 style FinalLot fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style Execute fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style RejectMargin fill:#ff0055,stroke:#ff0055,stroke-width:3px,color:#fff style End fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff

System Architecture

High-level overview of EA components and their interactions in the pattern detection and execution pipeline.

graph TB subgraph "Core Engine" OnTick[OnTick Function] StateMachine[State Machine
Controller] TradeMgmt[Trade Manager
CTrade Class] end subgraph "Pattern Recognition" C1Check[Candle 1 Validator
ATR Size Check] C2Check[Candle 2 Validator
Doji Structure] C3Check[Candle 3 Validator
Engulfing Start] C4Check[Candle 4 Validator
True Engulfing] BreakoutCheck[Breakout Monitor
Price Level Detection] end subgraph "Risk & Calculation" RiskCalc[Risk Calculator
% of Balance] LotSize[Lot Size Calculator
Ticks ร— Value] SLTP[SL/TP Calculator
Pattern Based] Validator[Trade Validator
Broker Limits] end subgraph "External Data" ATRIndicator[iATR Handle
Volatility] PriceData[iHigh/iLow/iOpen/iClose
Candle Data] AccountInfo[AccountInfoDouble
Balance & Margin] SymbolInfo[SymbolInfoDouble
Ticks & Limits] end subgraph "Utilities" DebugLog[Debug Logger
Print Statements] TradeLog[Trade Logger
OnTradeTransaction] Normalize[Price Normalizer
Tick Size] end OnTick --> StateMachine StateMachine --> C1Check StateMachine --> C2Check StateMachine --> C3Check StateMachine --> C4Check StateMachine --> BreakoutCheck C1Check --> ATRIndicator C1Check --> PriceData C2Check --> ATRIndicator C2Check --> PriceData C3Check --> ATRIndicator C3Check --> PriceData C4Check --> ATRIndicator C4Check --> PriceData BreakoutCheck --> PriceData BreakoutCheck --> SignalOK{Pattern &
Breakout Valid?} SignalOK -->|Yes| RiskCalc SignalOK -->|No| ResetState[Reset State
to IDLE] RiskCalc --> AccountInfo RiskCalc --> LotSize LotSize --> SymbolInfo LotSize --> SLTP SLTP --> PriceData SLTP --> Validator Validator --> SymbolInfo Validator --> TradeOK{Validation
Passed?} TradeOK -->|Yes| TradeMgmt TradeOK -->|No| DebugLog TradeMgmt --> OrderSent[Order Sent
to Broker] OrderSent --> TradeLog DebugLog --> PrintOut[Print to
Expert Log] TradeLog --> PrintClosed[Print TRADE_CLOSED
on Exit] Normalize --> SLTP Normalize --> Validator style OnTick fill:#00d4ff,stroke:#00d4ff,stroke-width:3px,color:#000 style StateMachine fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff style TradeMgmt fill:#00ff88,stroke:#00ff88,stroke-width:2px,color:#000 style BreakoutCheck fill:#ffaa00,stroke:#ffaa00,stroke-width:2px,color:#000 style SignalOK fill:#00ff88,stroke:#00ff88,stroke-width:2px,color:#000

Key Features & Capabilities

๐ŸŽฏ

Four-Candle Pattern Detection

Identifies high-probability reversal patterns through a sequential validation process: impulse candle, doji confirmation, and engulfing pair completion.

  • ATR-normalized size thresholds for consistency
  • Directional validation at each pattern stage
  • Configurable doji wick and body parameters
  • True engulfing confirmation logic
โšก

Advanced State Machine

Six-state architecture ensures robust pattern tracking with timeout protection and automatic reset capabilities for continuous market scanning.

  • STATE_IDLE through STATE_WAITING_BREAKOUT
  • Timeout protection on breakout wait (MaxBreakoutWait)
  • Automatic invalidation on opposite price breach
  • Phase-by-phase data storage for pattern analysis
๐Ÿ“Š

Dynamic Risk Calculation

Intelligent position sizing based on account equity and configurable risk percentage, automatically adjusting for stop loss distance and symbol specifications.

  • Percentage-based risk per trade (default 1.0%)
  • Automatic lot size normalization to broker limits
  • Tick value calculation for precise risk amount
  • Margin availability validation before execution
๐Ÿ›ก๏ธ

Pattern-Based Stop Loss

Strategic stop placement derived from pattern structure, using Candle 3/4 extremes with adjustable pip offset for optimal risk control.

  • Long: Below lower of Candle 3/4 lows
  • Short: Above higher of Candle 3/4 highs
  • Adjustable pip offset (+ away, - closer)
  • Normalized to tick size for precision
๐Ÿ“ˆ

Fixed Risk:Reward Execution

Systematic profit targeting based on configurable risk:reward ratios, calculated automatically from stop loss distance and entry price.

  • Configurable R:R ratio (default 1:2)
  • Symmetric profit target calculation
  • ATR-independent for consistency
  • Pre-trade validation of TP distance
๐Ÿ”

Comprehensive Debug Logging

Real-time logging system provides complete transparency into pattern validation, state transitions, and trade calculations for monitoring and optimization.

  • Rejection reasons for each validation failure
  • State machine progression tracking
  • Lot size and risk calculation details
  • Breakout detection timing and levels
๐Ÿ•

Breakout Monitoring

Active breakout surveillance on the current (forming) bar with timeout and invalidation logic, ensuring entries occur with genuine momentum.

  • Real-time price monitoring after pattern completion
  • Max candle wait limit (InpMaxBreakoutWait)
  • Opposite extreme invalidation
  • Tick-by-tick processing during breakout phase
๐Ÿ“

Trade Transaction Logging

OnTradeTransaction event handler captures complete trade lifecycle data including profit, swap, commission, and timing for detailed performance analysis.

  • Standardized TRADE_CLOSED output format
  • Entry and exit price recording
  • Swap and commission tracking
  • Compatible with external analytics tools
โš™๏ธ

Flexible Parameter Groups

Intuitive input parameter organization with logical grouping separators and descriptive comments for straightforward configuration and optimization.

  • Grouped by function (Candles, Risk, Display)
  • Clear parameter descriptions and ranges
  • Compatible with MT5 Strategy Tester optimization
  • All parameters accessible via input variables
๐ŸŽ›๏ธ

Doji Customization

Granular control over doji identification parameters including wick multipliers, body-to-size ratios, and optional inside-bar requirements.

  • Upper/Lower wick ATR multipliers (default 0.3 each)
  • Body size factor (default 40% of range)
  • Optional inside-bar requirement
  • Opposite direction validation
๐Ÿ”’

Single Position Protection

Prevents multiple concurrent positions through magic number filtering, ensuring clean trade management and accurate performance attribution.

  • Magic number filtering for position identification
  • Skips pattern analysis when position open
  • No interference with manual or other EA trades
  • Clean isolation between instances
๐Ÿ–ฅ๏ธ

XAUUSD Optimization

Specifically calibrated for XAUUSD characteristics including pip size handling for 2/3 decimal places, volatility patterns, and typical spread conditions.

  • Automatic pip size calculation (handles 2 and 3 decimals)
  • ATR period optimized for gold volatility cycles
  • Pattern thresholds suited for XAUUSD momentum
  • Works with standard gold contract specifications

Input Parameters & Configuration

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

Parameter Categories

Indicators

Core indicator settings including timeframe and ATR period. These define the volatility measurement and analysis timeframe for pattern detection.

Trading

Core trading parameters including breakout wait time, magic number, and trade comments. Controls execution behavior and trade identification.

Risk

Risk management parameters including risk percentage per trade and risk:reward ratio. Critical for position sizing and money management.

Advanced

Advanced pattern configuration including candle thresholds, doji parameters, and debug logging. Fine-tune pattern sensitivity and validation.

Performance Analytics

Comprehensive backtesting and live trading results for Impulse Pattern EA

๐Ÿ“Š

Backtesting Performance Results

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%
60.0%
Win Rate
2.19
Profit Factor
1.46:1
Avg Risk/Reward
-14.7%
Max Drawdown

โš ๏ธ 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.

Usage & Implementation Guide

1

Installation & Compilation

File Placement

Copy the EA file to your MetaTrader 5 installation directory:

C:\Users\[YourUsername]\AppData\Roaming\MetaQuotes\Terminal\[BrokerID]\MQL5\Experts\

Compilation Process

  1. Open MetaEditor from MT5 (press F4)
  2. Navigate to Navigator โ†’ Experts โ†’ Impulse_Pattern_EA.mq5
  3. Double-click the file to open in editor
  4. Click "Compile" button or press F7
  5. Verify "0 error(s), 0 warning(s)" in Errors tab
  6. If errors occur, check MQL5 Trade library inclusion

Verify Installation

After successful compilation, the EA will appear in MT5's Navigator under Expert Advisors. If not visible, right-click Navigator and select "Refresh".

VPS Consideration

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.

2

Chart Setup & EA Attachment

Open XAUUSD M1 Chart

  1. In MT5, right-click Market Watch window
  2. Select "Symbols" and ensure XAUUSD is visible
  3. Right-click XAUUSD โ†’ "Chart Window"
  4. Change timeframe to M1 (1-Minute)

Attach EA to Chart

  1. Open Navigator (Ctrl+N)
  2. Expand "Expert Advisors" section
  3. Drag Impulse Pattern EA onto the XAUUSD M1 chart
  4. Alternatively: Right-click chart โ†’ Expert Advisors โ†’ Impulse_Pattern_EA

Enable Algo Trading

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.

Verify EA is Running

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.

Initial Debug Check

If InpShowDebug=true, you should see initialization messages in Experts tab:

Impulse Pattern EA initialized successfully
Symbol: XAUUSD | Timeframe: M1
Pip Size: 0.01000
3

Parameter Configuration

Accessing Parameters

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.

Recommended Settings for XAUUSD M1

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

Session-Specific Adjustments

  • London Session (08:00-12:00 GMT): Highest volatility - consider reducing InpCandle1_ATRMultiplier to 0.6 for more signals
  • New York Session (13:00-17:00 GMT): Strong trends - increase InpMaxBreakoutWait to 7-8 candles for better confirmation
  • Asian Session (00:00-06:00 GMT): Lower volatility - increase InpCandle1_ATRMultiplier to 0.8-1.0 to filter noise
  • News Events: Consider disabling EA 15 minutes before/after high-impact news or increase all ATR multipliers by 0.2

Debugging Configuration

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.

4

Backtesting & Optimization

Strategy Tester Setup

  1. Open Strategy Tester (View โ†’ Strategy Tester or Ctrl+R)
  2. Select Impulse_Pattern_EA from Expert Advisor dropdown
  3. Symbol: XAUUSD
  4. Timeframe: M1
  5. Date Range: Select at least 6 months of historical data
  6. Model: "Every tick" for highest accuracy
  7. Spread: Use Current or set to typical broker spread (e.g., 30-50 points for XAUUSD)

Initial Backtest Run

Click Start button to run initial backtest with default parameters. This establishes baseline performance to compare against optimizations.

Optimization Process

Once baseline is established, optimize key parameters:

  1. Check "Optimization" box in Strategy Tester
  2. Click "Expert Properties" โ†’ "Inputs" tab
  3. Select parameters to optimize (e.g., InpCandle1_ATRMultiplier, InpRiskPercent)
  4. Set Start, Step, and Stop values for each parameter
  5. Select optimization criterion: Balance or Profit Factor
  6. Click "Start" - optimization may take hours depending on parameter ranges

Optimization Best Practices

โš ๏ธ Important Optimization Guidelines

  • Don't over-optimize: Avoid narrow parameter ranges that only fit past data (curve fitting)
  • Use reasonable ranges: Test InpCandle1_ATRMultiplier from 0.5 to 1.0, not 0.7 to 0.71
  • Walk-forward optimization: Test on 80% of data, validate on remaining 20% (out-of-sample)
  • Forward testing: After optimization, run on demo account for 2-4 weeks before live deployment
  • Focus on robustness: Prefer Profit Factor > 1.5 and Max Drawdown < 20% over high returns
  • Consider slippage: Add 2-3 pips slippage in Strategy Tester settings for realistic results

Analyzing Results

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.

Saving Optimized Parameters

Right-click the best result row โ†’ "Set Input Parameters". These will be applied to the EA for next backtest or live trading.

5

Live Trading Deployment

Pre-Launch Checklist

Monitoring Schedule

  • Daily: Check Expert logs for errors or warnings
  • Daily: Verify Algo Trading button remains green
  • Daily: Review trade log for patterns forming/executing
  • Weekly: Analyze performance metrics and drawdown
  • Weekly: Adjust parameters if market conditions changed significantly
  • Monthly: Full performance review and re-optimization if needed

Warning Signs to Watch For

  • โš ๏ธ Consecutive losses exceeding 5-7 trades in a row
  • โš ๏ธ Drawdown approaching 15-20% of account equity
  • โš ๏ธ EA not finding patterns for extended periods (3+ days)
  • โš ๏ธ Orders rejected by broker frequently (check symbol permissions)
  • โš ๏ธ Significant change in XAUUSD volatility (3x normal ATR)
  • โš ๏ธ Pattern completes but no breakout (increase MaxBreakoutWait)
  • โš ๏ธ Breakout occurs but immediate reversal (consider wider SL adjustment)

When to Pause or Stop

  • Major news events: Disable EA 15 minutes before/after NFP, Fed announcements
  • Holiday periods: Lower liquidity can cause abnormal spreads - pause trading
  • Broker issues: If spreads widen beyond 100 points consistently
  • Drawdown limit: If account drawdown hits your personal stop-loss (e.g., 25%)

Common Issues & Solutions

EA not opening any trades

+
  • Check Algo Trading: Ensure green button is active in toolbar
  • Verify smiley face: Should see ๐Ÿ˜Š in top-right corner of chart
  • Enable debug: Set InpShowDebug=true and check Experts tab for rejection reasons
  • ATR data: Ensure ATR indicator is calculating (no errors in logs)
  • Pattern rarity: Four-candle pattern is specific - may only appear 2-5 times per day on XAUUSD M1
  • Timeframe: Confirm chart is M1 (pattern optimized for 1-minute)

Orders rejected or failing to execute

+
  • Stop level too close: Increase InpStopLossPipAdjustment (+ values move SL away)
  • Insufficient margin: Reduce InpRiskPercent or increase account balance
  • Invalid lot size: Check broker's minimum lot (e.g., 0.01) and step requirements
  • Spread too wide: Avoid trading during news or low liquidity periods
  • Symbol restrictions: Verify XAUUSD is available for algo trading with broker
  • Trade permissions: Check account settings allow automated trading

Pattern completes but no breakout (timeout)

+
  • Increase wait time: Raise InpMaxBreakoutWait from 5 to 7-10 candles
  • Volatility change: Market may have slowed - check if ATR decreased significantly
  • Pattern quality: Review debug logs - pattern may have been marginal
  • Time of day: Asian session typically has slower breakout follow-through
  • Consider entry modification: Some traders enter on Candle 4 close instead of waiting for breakout (requires code modification)

Too many false signals / low win rate

+
  • Increase Candle 1 threshold: Raise InpCandle1_ATRMultiplier to 0.8-1.0 for stronger impulse requirement
  • Tighten doji parameters: Reduce InpDoji_BodyToSizeFactor to 0.25-0.3 for purer dojis
  • Stricter engulfing: Increase InpCandle3/4 multipliers to 0.6-0.7
  • Add session filter: Only trade during London/NY overlap (13:00-17:00 GMT)
  • Check ATR period: Experiment with 10-20 periods to match current market volatility
  • Review spread: High spreads during entry can reduce win rate - avoid wide spread periods

Debug logs show "Invalid stop levels" error

+
  • Broker's stop level: Some brokers require minimum stop distance. Check SYMBOL_TRADE_STOPS_LEVEL
  • Increase stop distance: Add +5 to +10 pips in InpStopLossPipAdjustment
  • Pattern structure issue: Very tight patterns may create naturally close stops. This is a feature, not a bug
  • Normalize issue: Ensure tick size calculation is correct for XAUUSD (should be 0.01 for 2-decimal brokers)
  • Timeframe mismatch: Verify InpTimeframe matches chart timeframe

Technical Specifications

Platform Requirements

Platform MetaTrader 5
MQL Version 5.00
Build Required Build 2600+
Type Expert Advisor (EA)
Execution Mode OnTick / OnTradeTransaction

Trading Specifications

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

Account Requirements

Minimum Balance $500
Recommended Balance $1,000+
Account Type Standard, ECN, STP
Leverage 1:100 to 1:500
Hedging Not required

Code Specifications

Lines of Code ~850 LOC
Custom Functions 15+
Indicator Handles 1 (iATR)
Complexity Level Intermediate-Advanced
State Machine States 6 ENUM states

Features Implementation Checklist

Broker & Server Compatibility

โœ…

Market & Instant Execution

Compatible with both market and instant execution brokers. Auto-adapts to execution type.

โœ…

ECN/STP Accounts

Optimized for ECN and STP account types with tight spreads and fast execution.

โœ…

2 & 3 Decimal Gold Quotes

Auto-detects XAUUSD quote format (e.g., 2035.50 vs 2035.500) and calculates pip size correctly.

โœ…

Standard & Pro Accounts

Works with standard lots, micro lots, and any contract size. Respects broker's minimum/maximum limits.

โš ๏ธ

VPS Highly Recommended

For 24/7 pattern monitoring, especially during breakout wait phases. Any disconnect can miss valid entries.

โš ๏ธ

Spread Sensivity

Best performance with raw spread + commission accounts. High fixed spreads ( > 50 points) may reduce profitability.

โš ๏ธ

IMPORTANT RISK DISCLOSURE

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.

About This Expert Advisor

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.

User Responsibility & Acknowledgment

By using this Expert Advisor, you acknowledge and accept full responsibility for:

  • All trading decisions and parameter configuration
  • Understanding the pattern logic and inherent risks
  • Monitoring EA performance and intervening when necessary
  • Ensuring broker compatibility and account permissions
  • Maintaining stable connection (VPS) for continuous operation
  • Regularly reviewing and updating parameters as market conditions evolve

Financial Risk Warning

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.

No Warranties or Guarantees

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.

Recommended Safety Practices

  • Always test on demo account for minimum 2 weeks before live trading
  • Start with lowest risk setting (0.5% per trade) for first month
  • Never risk more than 2-3% of account balance per trade
  • Limit total EA risk to 10-15% of overall portfolio
  • Use VPS for 24/7 operation to avoid missed entries
  • Monitor during high-impact news (NFP, Fed decisions, CPI)
  • Keep detailed records of all trades and performance metrics
  • Be prepared to disable EA during abnormal market conditions
  • Regularly withdraw profits to protect capital

Limitation of Liability

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.

Contact & Support

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.