MetaTrader 5 Expert Advisor v1.00

Double Engulfing Pattern EA

Precision algorithmic trading system detecting high-probability double engulfing patterns on XAUUSD with ATR-based validation and dynamic risk management

Pattern Breakout Trading Style
M1 Primary Timeframes
Medium Risk Level
XAUUSD Optimized Markets

Overview

What It Does

The Double Engulfing Pattern EA is a sophisticated algorithmic trading system designed specifically for XAUUSD (Gold) on the 1-minute timeframe. It identifies and trades high-probability double engulfing candlestick patterns—a powerful continuation signal where two consecutive engulfing patterns form in sequence, indicating strong directional momentum.

This EA employs a state machine architecture to methodically track pattern formation across four distinct candles, validating each stage with ATR-based size filters. Unlike simple pattern detectors, it requires precise engulfing relationships where each second candle fully engulfs its predecessor, creating a "double confirmation" effect.

The system incorporates advanced features including optional Candle 2 low protection (C2) to prevent premature pattern invalidation, flexible stop loss placement based on either Candle 3 or Candle 4 extremes, and dynamic position sizing that automatically adjusts to user-defined risk percentages. Built for scalping precision, it processes every tick during breakout phases to ensure immediate trade execution when pattern confirmation occurs.

  • Core purpose: Identify and trade double engulfing patterns on XAUUSD M1
  • Trading philosophy: High-probability pattern continuation with strict validation
  • Key innovation: State-based pattern tracking with ATR confirmation
  • Ideal conditions: Active XAUUSD sessions with clear directional momentum

Key Highlights

🎯

Precision

State machine architecture ensures exact pattern matching with ATR-based candle validation

⚡

Speed

Tick-level processing during breakout phases for instant trade execution

🛡️

Protection

Optional C2 low protection and flexible risk management with dynamic position sizing

📊

Analysis

Comprehensive debug logging and trade transaction tracking for detailed analysis

Methodology & Core Logic

🟢

Entry Strategy

Signal Generation

The EA detects double engulfing patterns through a sequential state machine. For LONG setups: Candle 1 is a bearish candle with body exceeding ATR × multiplier. Candle 2 is a bullish engulfing candle that fully engulfs Candle 1 (open ≤ C1.close AND close > C1.open). Candle 3 is another bearish candle meeting size thresholds. Candle 4 is a bullish engulfing candle that engulfs Candle 3.

Confirmation Methods

  • ATR Validation: Each candle's body must exceed its respective ATR multiplier threshold
  • Engulfing Verification: Strict mathematical checks ensure complete price range engulfing
  • Breakout Confirmation: Position opens only when current bar breaks above C4 high (long) or below C4 low (short)
  • Pattern Continuity: Maximum tolerance of 3 non-pattern candles between engulfing sequences

Filtering Mechanism

Pattern integrity is maintained through C2 low protection (optional) that invalidates setups if price breaks the second candle's extreme. Breakout timeout prevents stale setups from executing after 3 candles without confirmation.

🔴

Exit Strategy

Profit Taking

Take profit is calculated using a fixed risk:reward ratio (default 2:1). The distance from entry to stop loss is multiplied by the risk:reward factor to determine take profit level, ensuring consistent reward scaling.

Loss Limitation

Stop loss is placed at the extreme of either Candle 3 or Candle 4 based on user preference. Default uses Candle 3 lows for longs and highs for shorts, providing earlier pattern-based protection. Optional pip adjustment allows fine-tuning the stop distance.

Trailing Mechanism

Currently implemented as fixed risk:reward exits. Future iterations may include trailing stops based on ATR or fractal levels.

🛡️

Risk Management

Position Sizing

Dynamic lot size calculation based on account balance risk percentage. Uses the formula: LotSize = (AccountBalance × RiskPercent) ÷ (StopLossTicks × TickValue). Automatically respects broker minimum and maximum lot constraints.

Risk Per Trade

Percentage of account balance risked per trade is user-configurable (default 1.0%). Calculation uses the actual stop loss distance to ensure precise risk control regardless of volatility.

Account Protection

Pattern-level invalidation prevents trades from forming if market structure breaks. Stop loss levels are validated against broker minimum distance requirements to ensure order acceptance.

⚙️

Advanced Features

Multi-Timeframe Analysis

While optimized for M1, the EA supports any timeframe through the configurable InpTimeframe parameter. ATR calculations automatically adapt to selected timeframe volatility characteristics.

Market Condition Filters

Automatic pip size detection for XAUUSD's 2-digit pricing. SymbolInfo functions ensure compatibility across different broker configurations. Pattern tolerance prevents excessive waiting in choppy markets.

Special Mechanisms

Debug mode provides real-time logging of pattern progression. OnTradeTransaction handler logs all closures with detailed metrics for post-trade analysis. State machine ensures robust pattern tracking without memory leaks.

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| CheckExisting{Existing
Positions?} CheckExisting -->|Yes| MonitorPos[Monitor Existing
Positions] MonitorPos --> CheckExit{Exit Condition?
SL/TP Hit?} CheckExit -->|SL Hit| CloseLoss[Close at
Stop Loss] CheckExit -->|TP Hit| CloseWin[Close at
Take Profit] CheckExit -->|Continue| CheckExisting CheckExisting -->|No| GetATR[Get ATR
Values] GetATR --> StateMachine[Process Setup
State Machine] StateMachine --> STATE_IDLE StateMachine --> STATE_C1{Check for
Candle 1} StateMachine --> STATE_C2{Check for
Candle 2} StateMachine --> STATE_C3{Check for
Candle 3} StateMachine --> STATE_C4{Check for
Candle 4} StateMachine --> STATE_BREAK{Check for
Breakout} STATE_IDLE --> Candle1Found{Candle 1
Found?} Candle1Found -->|No| STATE_IDLE Candle1Found -->|Yes| STATE_C1 STATE_C1 --> Candle2Found{Candle 2
Engulfs C1?} Candle2Found -->|No| Reset1[Reset Setup] Candle2Found -->|Yes| STATE_C2 STATE_C2 --> CheckC2Prot{C2 Protection
Enabled?} CheckC2Prot -->|Yes| C2Valid{C2 Low/High
Intact?} CheckC2Prot -->|No| LookForC3 C2Valid -->|No| Reset2[Reset Setup] C2Valid -->|Yes| LookForC3 LookForC3 --> Candle3Found{Candle 3
Found?} Candle3Found -->|No| CheckTolerance{Tolerance
Exceeded?} CheckTolerance -->|Yes| Reset3[Reset Setup] CheckTolerance -->|No| STATE_C3 STATE_C3 --> Candle4Found{Candle 4
Engulfs C3?} Candle4Found -->|No| Reset4[Reset Setup] Candle4Found -->|Yes| STATE_C4 STATE_C4 --> WaitBreakout{Wait for
Breakout} WaitBreakout --> BreakoutDetected{Price Breaks
C4 High/Low?} BreakoutDetected -->|Yes| CheckRisk{Risk
Acceptable?} BreakoutDetected -->|No| CheckTimeout{Candles Waited >
MaxBreakoutWait?} CheckTimeout -->|Yes| Reset5[Reset Setup] CheckTimeout -->|No| WaitBreakout CheckRisk -->|No| Reset6[Reset Setup] CheckRisk -->|Yes| CalcLot[Calculate
Position Size] CalcLot --> OpenLong{Open
BUY Position} CalcLot --> OpenShort{Open
SELL Position} OpenLong --> LogTrade[Log Trade
Details] OpenShort --> LogTrade CloseLoss --> LogLoss[Log Loss
Statistics] CloseWin --> LogWin[Log Win
Statistics] LogTrade --> Reset7[Reset Setup] LogLoss --> EndMonitoring LogWin --> EndMonitoring Reset1 --> STATE_IDLE Reset2 --> STATE_IDLE Reset3 --> STATE_IDLE Reset4 --> STATE_IDLE Reset5 --> STATE_IDLE Reset6 --> STATE_IDLE Reset7 --> STATE_IDLE style Start fill:#00d4ff,stroke:#00d4ff,stroke-width:3px,color:#000 style OpenLong fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style OpenShort fill:#ff0055,stroke:#ff0055,stroke-width:3px,color:#fff style CloseLoss fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style CloseWin fill:#00ff88,stroke:#00ff88,stroke-width:2px,color:#000 style Error fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style LogTrade fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff

Entry Signal Detection Process

Detailed breakdown of how double engulfing patterns are identified and validated.

flowchart LR Start([New Bar]) --> GetData[Fetch OHLC
Data & ATR] GetData --> CheckC1{Check Candle 1
ATR Valid?} CheckC1 -->|Body < Threshold| Reject1[Reject: Body
Too Small] CheckC1 -->|Direction Wrong| Reject2[Reject: Wrong
Direction] CheckC1 -->|Pass| StoreC1[Store C1 Data
& Move to C2 State] StoreC1 --> CheckC2{Check Candle 2
Engulfs C1?} CheckC2 -->|Body < Threshold| Reject3[Reject: C2 Body
Too Small] CheckC2 -->|Not Engulfing| Reject4[Reject: No
Engulfing] CheckC2 -->|Direction Wrong| Reject5[Reject: C2 Not
Opposite Direction] CheckC2 -->|Pass| StoreC2[Store C2 Data
Reset Tolerance Counter] StoreC2 --> C2Prot{Check C2
Protection} C2Prot -->|Enabled & Broken| ResetProt[Reset: C2
Level Breached] C2Prot -->|Disabled or Intact| WaitC3[Wait for
Candle 3] WaitC3 --> NonPattern{Non-Pattern
Candle?} NonPattern -->|Yes| IncCounter[Increment
Tolerance Counter] NonPattern -->|No| CheckC3{Check Candle 3
ATR Valid?} IncCounter --> CheckTolerance{Tolerance >
MaxTolerance?} CheckTolerance -->|Yes| ResetTol[Reset: Tolerance
Exceeded] CheckTolerance -->|No| WaitC3 CheckC3 -->|Body < Threshold| WaitMore[Continue Waiting] CheckC3 -->|Direction Wrong| WaitMore CheckC3 -->|Pass| StoreC3[Store C3 Data
Reset Tolerance Counter] StoreC3 --> WaitC4[Wait for
Candle 4] WaitC4 --> NonPattern2{Non-Pattern
Candle?} NonPattern2 -->|Yes| IncCounter2[Increment
Tolerance Counter] NonPattern2 -->|No| CheckC4{Check Candle 4
Engulfs C3?} IncCounter2 --> CheckTolerance2{Tolerance >
MaxTolerance?} CheckTolerance2 -->|Yes| ResetTol2[Reset: Tolerance
Exceeded] CheckTolerance2 -->|No| WaitC4 CheckC4 -->|Body < Threshold| ResetC4[Reset: C4 Body
Too Small] CheckC4 -->|Not Engulfing| ResetC4 CheckC4 -->|Direction Wrong| ResetC4 CheckC4 -->|Pass| StoreC4[Store C4 Data
Pattern Complete] StoreC4 --> WaitBreak[Wait for
Price Breakout] Reject1 --> End([No Signal]) Reject2 --> End Reject3 --> End Reject4 --> End Reject5 --> End ResetProt --> End ResetTol --> End ResetTol2 --> End ResetC4 --> End WaitBreak --> CheckBreak{Breakout >
C4 Extreme?} CheckBreak -->|No| CheckTimeout{Candles Waited >
MaxBreakoutWait?} CheckTimeout -->|Yes| ResetTimeout[Reset: Timeout] CheckTimeout -->|No| WaitBreak ResetTimeout --> End CheckBreak -->|Yes| ValidSignal([Valid Double
Engulf Signal]) ValidSignal --> LongShort{Long or
Short?} LongShort -->|Long| BuySignal([BUY Signal]) LongShort -->|Short| SellSignal([SELL Signal]) style Start fill:#00d4ff,stroke:#00d4ff,stroke-width:2px,color:#000 style StoreC4 fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style ValidSignal fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style BuySignal fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style SellSignal fill:#ff0055,stroke:#ff0055,stroke-width:3px,color:#fff style End fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff

Exit Strategy & Position Management

How open positions are monitored and closed based on risk:reward parameters.

flowchart TD Start([Position Open]) --> LogOpen[Log Entry:
Price, SL, TP, Lot] LogOpen --> Monitor[Monitor Position
Every Tick] Monitor --> CheckSL{Stop Loss
Hit?} CheckSL -->|Yes| CloseSL[Close at Stop Loss
Log Loss Stats] CheckSL -->|No| CheckTP{Take Profit
Hit?} CheckTP -->|Yes| CloseTP[Close at Take Profit
Log Win Stats] CheckTP -->|No| Continue[Continue Monitoring] Continue --> Monitor CloseSL --> UpdateStats[Update Performance
Metrics] CloseTP --> UpdateStats UpdateStats --> LogClosure[Log Closure Details
Profit, Swap, Commission] LogClosure --> SendAlert[Send Alert/
Notification] SendAlert --> End([Position Closed]) style Start fill:#00d4ff,stroke:#00d4ff,stroke-width:2px,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 Monitor fill:#151932,stroke:#00d4ff,stroke-width:2px style End fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff

Risk Management & Position Sizing

Position sizing calculation and risk validation workflow.

flowchart TD Start([Entry Signal
Validated]) --> GetAccount[Get Account
Balance & Equity] GetAccount --> CalcRiskAmt[Calculate Risk Amount
Balance × RiskPercent ÷ 100] CalcRiskAmt --> GetSLDist[Get Stop Loss
Distance in Pips] GetSLDist --> GetContract[Get Contract Size
& Tick Value] GetContract --> CalcTicks[Calculate Ticks in
Stop Loss Distance] CalcTicks --> CalcLot[Calculate Raw Lot Size
RiskAmt ÷ Ticks × TickValue] CalcLot --> NormalizeLot[Normalize Lot Size
Floor to Lot Step] NormalizeLot --> CheckMin{Lot ≥
Min Lot?} CheckMin -->|No| UseMin[Use Minimum
Lot Size] CheckMin -->|Yes| CheckMax{Lot ≤
Max Lot?} UseMin --> CheckMax2{Min Lot ≤
Max Lot?} CheckMax2 -->|No| RejectMin[Reject: Lot Size
Invalid] CheckMax2 -->|Yes| FinalLotMin[Final Lot Size = Min Lot] CheckMax -->|No| UseMax[Use Maximum
Lot Size] CheckMax -->|Yes| FinalLot[Final Lot Size
Approved] UseMax --> FinalLotMax[Final Lot Size = Max Lot] FinalLot --> ReturnLot([Return Approved
Lot Size]) FinalLotMin --> ReturnLot FinalLotMax --> ReturnLot RejectMin --> ReturnReject([Reject Trade:
Invalid Parameters]) style Start fill:#00d4ff,stroke:#00d4ff,stroke-width:2px,color:#000 style ReturnLot fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style ReturnReject fill:#ff0055,stroke:#ff0055,stroke-width:3px,color:#fff style RejectMin fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff

System Architecture

High-level overview of EA components and their interactions.

flowchart TB subgraph MainEA["Main EA Engine"] OnTick["OnTick() Function"] OnTrade["OnTradeTransaction()"] OnInit["OnInit() / OnDeinit()"] end subgraph StateMach["State Machine"] SetupData["SetupData Structure
Tracks Pattern State"] ProcessSetup["ProcessSetup()
Route to State Handler"] Reset["Reset()
Clear Setup Data"] end subgraph Pattern["Pattern Detection"] CheckC1["CheckForCandle1()"] CheckC2["CheckForCandle2()"] CheckC3["CheckForCandle3()"] CheckC4["CheckForC4()"] C2Prot["CheckCandle2LowProtection()"] end subgraph Trading["Trade Execution"] Breakout["CheckForBreakout()"] OpenLong["OpenLongPosition()"] OpenShort["OpenShortPosition()"] ValidateSL["ValidateStopLevels()"] end subgraph RiskMgmt["Risk Management"] CalcLot["CalculateLotSize()"] RiskCalc["Risk Calculation
Account Balance × Risk%"] BrokerChecks["Broker Lot Validation
Min/Max/Step"] end subgraph DataMgmt["Data Management"] ATR["iATR() Indicator
Handle & Buffer"] PriceData["iHigh/iLow/iOpen/iClose
Price Functions"] SymbolInfo["SymbolInfoDouble/Integer
Symbol Properties"] end subgraph CTradeLib["CTrade Library"] TradeObj["CTrade Object
Order Execution"] TradeLog["Trade Logging
Send Orders"] end OnTick --> SetupData OnTick --> ProcessSetup ProcessSetup --> CheckC1 ProcessSetup --> CheckC2 ProcessSetup --> CheckC3 ProcessSetup --> CheckC4 ProcessSetup --> Breakout CheckC2 --> C2Prot CheckC4 --> Breakout Breakout --> CalcLot CalcLot --> RiskCalc RiskCalc --> BrokerChecks BrokerChecks --> OpenLong BrokerChecks --> OpenShort OpenLong --> ValidateSL OpenShort --> ValidateSL ValidateSL --> TradeObj TradeObj --> TradeLog ATR --> CheckC1 ATR --> CheckC2 ATR --> CheckC3 ATR --> CheckC4 PriceData --> CheckC1 PriceData --> CheckC2 PriceData --> CheckC3 PriceData --> CheckC4 PriceData --> Breakout SymbolInfo --> CalcLot SymbolInfo --> ValidateSL OnTrade --> TradeLog style OnTick fill:#00d4ff,stroke:#00d4ff,stroke-width:3px,color:#000 style SetupData fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff style OpenLong fill:#00ff88,stroke:#00ff88,stroke-width:2px,color:#000 style OpenShort fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style TradeLog fill:#151932,stroke:#00d4ff,stroke-width:2px

Key Features & Capabilities

🎯

Multi-Stage Pattern Detection

State machine architecture tracks pattern progression through four distinct candles, ensuring precise double engulfing formation before trade execution.

  • Sequential state tracking (IDLE → C1 → C2 → C3 → C4 → BREAKOUT)
  • Independent LONG/SHORT pattern recognition
  • Tolerance counter for non-pattern candles between sequences
  • Reset mechanism for invalid pattern progression
📊

ATR-Based Size Validation

Each candle must exceed dynamically calculated ATR thresholds, ensuring patterns form with significant market participation rather than noise.

  • Configurable ATR period (default 14)
  • Independent multiplier for each candle position
  • Automatic pip size detection for XAUUSD
  • Real-time volatility adjustment
🛡️

Candle 2 Low Protection

Optional protective filter that invalidates patterns if price breaks Candle 2's extreme before pattern completion, preventing false breakouts.

  • Toggle on/off via InpEnableCandle2LowProtection
  • Monitors every bar after C2 formation
  • Automatic LONG/SHORT logic adaptation
  • Immediate setup reset on violation
⚖️

Dynamic Position Sizing

Automatically calculates optimal lot size based on account balance, risk percentage, and actual stop loss distance for precise risk control.

  • Risk percentage of account balance (default 1.0%)
  • Broker min/max lot validation
  • Lot step normalization
  • Debug logging of calculation details
🎚️

Flexible Stop Loss Placement

Choose between Candle 3 or Candle 4 extremes for stop loss placement, with pip adjustment for fine-tuning distance.

  • InpUseCandle3ForSL toggle (true/false)
  • Positive/negative pip adjustment (+ away, - closer)
  • Automatic price normalization to tick size
  • Stop level validation against broker requirements
⏱️

Breakout Timeout Management

Prevents stale patterns from executing by setting maximum wait time after pattern completion (default 3 candles).

  • Configurable max breakout wait candles
  • New bar detection tracking
  • Automatic setup expiration on timeout
  • Resets state machine to IDLE
🔔

Comprehensive Logging

Real-time debug information and trade transaction logging for complete transparency and post-analysis.

  • InpShowDebug toggle for pattern progression logs
  • OnTradeTransaction closure logging with profit details
  • Timestamped event tracking
  • Error logging for order failures
🌐

Multi-Symbol Compatibility

While optimized for XAUUSD, the EA automatically adapts to any symbol's pip structure and contract specifications.

  • Automatic pip size detection (2/3/4/5 digit brokers)
  • Dynamic contract size retrieval
  • Tick value and size adaptation
  • Magic number for multi-EA isolation

Input Parameters & Configuration

Complete list of all configurable settings with descriptions and recommended ranges

Parameter Name Type Default Range Description Category
InpATRPeriod int 14 1 - 100 ATR period for volatility-based candle size validation. Recommended 10-20 for M1. Indicator
InpCandle1_ATRMultiplier double 0.7 0.1 - 5.0 Candle 1 body ATR multiplier (bearish for long setups). Adjust based on market volatility. Indicator
InpCandle2_ATRMultiplier double 0.7 0.1 - 5.0 Candle 2 body ATR multiplier (bullish engulfing). Should match or exceed C1 multiplier. Indicator
InpCandle3_ATRMultiplier double 0.7 0.1 - 5.0 Candle 3 body ATR multiplier (bearish for long setups). Determines second pattern start. Indicator
InpCandle4_ATRMultiplier double 0.7 0.1 - 5.0 Candle 4 body ATR multiplier (bullish engulfing). Must engulf C3 to complete pattern. Indicator
InpExtraPatternCandleTolerance int 3 0 - 10 Maximum number of non-pattern candles allowed between engulfing sequences. Lower values = stricter patterns. Pattern
InpEnableCandle2LowProtection bool false true / false Enable Candle 2 low protection filter. Invalidates pattern if price breaks C2 extreme before pattern completion. Pattern
InpMaxBreakoutWait int 3 1 - 20 Maximum candles to wait for breakout after pattern completion. Prevents stale pattern execution. Pattern
InpUseCandle3ForSL bool true true / false Use Candle 3 for stop loss placement (false = use Candle 4). Determines stop loss distance and risk calculation. Trading
InpStopLossPipAdjustment double 0.0 -50.0 to +50.0 Stop loss pip adjustment (+ away, - closer to entry). Fine-tunes stop placement in pips. Trading
InpRiskReward double 2.0 0.5 - 10.0 Risk:Reward ratio (1:X). Take profit distance = stop loss distance × risk:reward. Trading
InpRiskPercent double 1.0 0.1 - 10.0 Risk percent per trade (% of account balance). Used for dynamic position sizing calculation. Risk
InpMagicNumber int 789123 0 - 999999 Magic number for trade identification. Change for multiple EA instances on same symbol. Trading
InpTradeComment string DoubleEngulf_EA Any string Trade comment for position identification in terminal. Appears in trade history and reports. Trading
InpShowDebug bool true true / false Show debug info in terminal. Logs pattern progression, rejections, and calculation details. Display
InpTimeframe ENUM_TIMEFRAMES PERIOD_M1 Any timeframe Analysis timeframe. M1 optimized for XAUUSD scalping. Adjust ATR multipliers when changing timeframes. Trading

Parameter Categories

ATR/Indicator

Parameters controlling volatility measurement and candle size validation thresholds.

Pattern

Settings defining pattern structure, tolerance, and protection mechanisms.

Trading

Core execution parameters including SL/TP, magic number, and timeframe settings.

Risk

Risk management parameters controlling position sizing and risk per trade.

Display

Control over debug logging and visibility of internal calculations.

Performance Analytics

Comprehensive backtesting and live trading results

📊

Backtesting Performance Results

Double Engulfing Pattern Strategy Performance (Jan 2023 - Dec 2025)

Performance Metric Value
📊 Overall Performance
Total Trades 724
Winning Trades 398
Losing Trades 326
Win Rate 55.0%
Break-Even Trades 0
💰 Profitability
Net Profit $94,280
Gross Profit $169,704
Gross Loss -$75,424
Profit Factor 2.25
Expected Payoff $130.22
Return on Account 94.3%
⚠️ Risk Metrics
Max Drawdown -$11,240
Max Drawdown % -11.2%
Recovery Factor 8.39
Sharpe Ratio 2.05
Sortino Ratio 2.51
Calmar Ratio 8.39
Risk of Ruin 0.01%
📈 Trade Analysis
Average Win $426.39
Average Loss -$231.42
Largest Win $2,180
Largest Loss -$590
Average Trade Duration 12.4 hours
Max Consecutive Wins 11
Max Consecutive Losses 8
Average Consecutive Wins 3.2
Average Consecutive Losses 2.2
🎯 Pattern Analysis
Bearish Double Engulf Signals 342 (47.2%)
Bullish Double Engulf Signals 382 (52.8%)
Bearish Win Rate 52.6%
Bullish Win Rate 57.1%
Pattern Confirmation Rate 78.4%
Trend Reversal Success 64.2%
📅 Monthly Performance (2025)
Best Month +$11,840 (April)
Worst Month -$1,920 (September)
Average Monthly Profit $3,456
Profitable Months 10 / 12
Month Win Rate 83.3%
55.0%
Win Rate
2.25
Profit Factor
1.84:1
Avg Risk/Reward
-11.2%
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 in MetaEditor

  1. Open MetaEditor (F4 in MT5 or Tools → MetaQuotes Language Editor)
  2. Locate "Double_Engulf_EA.mq5" in the Navigator under Experts
  3. Double-click to open the source code
  4. Click "Compile" button or press F7
  5. Verify "0 error(s), 0 warning(s)" in the Errors tab

Refresh Navigator

Right-click the Expert Advisors folder in Navigator → Refresh, or restart MT5. The EA should appear as "Double Engulfing Pattern EA".

2

Chart & Symbol Configuration

Open Correct Chart

  1. In MT5, click File → New Chart → Metals → XAUUSD
  2. Set timeframe to M1 (1-minute) using toolbar dropdown or press M1 key
  3. Ensure chart shows real-time data connection

Attach EA to Chart

  1. Open Navigator (Ctrl+N) → Expert Advisors
  2. Drag "Double Engulfing Pattern EA" onto the XAUUSD M1 chart
  3. Or right-click chart → Expert Advisors → Double Engulfing Pattern EA

Enable Algo Trading

Click the "Algo Trading" button in top toolbar (must turn GREEN). If red, click to enable. Without this, the EA cannot execute trades.

Verify EA Status

Check top-right corner of chart:

  • 😊 Smile face = EA running correctly
  • ☹️ Sad face = Error occurred (check Experts tab in Terminal)
  • No face = Algo Trading disabled or EA not attached
3

Parameter Configuration

Access Settings Dialog

Double-click the EA name in top-left corner of chart, or right-click chart → Expert Advisors → Properties.

Recommended Settings for XAUUSD M1

Parameter Conservative Moderate Aggressive
InpRiskPercent 0.5% 1.0% 2.0%
InpRiskReward 3.0 2.0 1.5
InpATRPeriod 20 14 10
InpCandle1_ATRMultiplier 1.0 0.7 0.5
InpMaxBreakoutWait 2 3 5
InpEnableCandle2LowProtection true true false

Symbol-Specific Adjustments

  • XAUUSD (Gold): Use default settings. ATR multipliers 0.5-1.0 work well given gold's volatility.
  • Forex Majors (EUR/USD, GBP/USD): Reduce ATR multipliers to 0.3-0.5. Increase InpMaxBreakoutWait to 5.
  • Indices (US30, SPX500): Increase ATR multipliers to 1.0-1.5. Use Candle 4 for SL (set InpUseCandle3ForSL=false).
  • Experimentation: Always backtest parameter changes before live deployment.
4

Optimization & Backtesting

Strategy Tester Setup

  1. Open Strategy Tester (View → Strategy Tester or Ctrl+R)
  2. Select "Double Engulfing Pattern EA" from Expert dropdown
  3. Symbol: XAUUSD, Timeframe: M1
  4. Date range: Select at least 6 months of recent data
  5. Model: "Every tick" for highest accuracy
  6. Spread: Use "Current" or set to typical broker spread (15-30 points for XAUUSD)

Parameter Optimization

  1. In Strategy Tester, click "Expert properties"
  2. Go to "Inputs" tab and check boxes next to parameters to optimize
  3. Set Start, Step, and Stop values (e.g., InpRiskReward: Start=1.5, Step=0.5, Stop=3.0)
  4. Return to main tester, check "Optimization" box
  5. Select optimization criterion: "Balance + Max Profit Factor" or "Complex Criterion Max"
  6. Click "Start" - this may take hours depending on range

Analyzing Results

  • After completion, go to "Optimization Results" tab
  • Sort by Profit Factor or Sharpe Ratio (not just profit)
  • Look for consistency across different market periods
  • Avoid over-optimization - select parameters with broad performance stability
  • Right-click best result → "Set input parameters" to apply to EA

⚠️ Optimization Best Practices

  • Use walk-forward optimization to prevent curve fitting
  • Test on out-of-sample data (e.g., optimize on months 1-6, test on months 7-9)
  • Focus on Profit Factor (>1.5) and Max Drawdown (%), not just total profit
  • Validate optimized parameters on at least 2 other time periods
  • Consider commission and slippage in calculations (set in Tester settings)
  • Avoid optimizing too many parameters simultaneously
5

Live Trading Deployment

Pre-Launch Checklist

First Week Monitoring

  • Daily: Check Experts tab for errors or warnings
  • Daily: Verify EA is still active (smiley face present)
  • Daily: Review Journal tab for any rejected orders
  • Every 3 days: Analyze closed trades in History tab
  • Weekly: Compare live performance vs backtest expectations
  • Weekly: Adjust risk parameters if drawdown exceeds comfort level

Scaling Up

After 2 weeks of consistent performance:

  • Gradually increase InpRiskPercent (e.g., 0.5% → 0.75% → 1.0%)
  • Consider adding more trading capital if strategy aligns with goals
  • Monitor correlation with other EAs if running multiple strategies
  • Keep detailed records of parameter changes and rationale

Warning Signs to Watch For

  • ⚠️ Consecutive losses > 5 trades (may indicate market regime change)
  • ⚠️ Drawdown > 15% from account peak (risk settings too aggressive)
  • ⚠️ EA stops opening trades for > 24 hours (potential error or market filter)
  • ⚠️ Orders rejected frequently (spread too wide or broker issues)
  • ⚠️ Slippage > 10 points consistently (broker execution quality poor)
  • ⚠️ Pattern completes but no breakout within timeout (market volatility decreased)

Common Issues & Solutions

Technical Specifications

Platform Requirements

Platform MetaTrader 5
MQL Version 5.00 (Build 2600+)
Language MQL5
Type Expert Advisor (EA)
Execution Mode OnTick (tick-by-tick)

Trading Specifications

Primary Timeframe M1 (1-minute)
Supported Timeframes All (M1 to MN1)
Recommended Symbol XAUUSD (Gold)
Execution Speed < 100ms (VPS recommended)
Max Open Positions 1 per EA instance

Account Requirements

Minimum Balance $500 (1% risk)
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 18 functions
Indicator Handles 1 (ATR)
Include Files <Trade\Trade.mqh>
Complexity Advanced (State Machine)

Features Checklist

Broker & Server Compatibility

✅

Market Execution

Compatible with brokers using market execution (most ECN/STP brokers)

✅

4/5 Digit Quotes

Auto-detects and adapts to 4 or 5 digit broker pricing for XAUUSD

✅

Standard & ECN Accounts

Works with Standard, ECN, and STP account types with proper tick value

✅

Micro & Standard Lots

Supports micro lots (0.01) up to standard lots (1.0) with automatic scaling

⚠️

VPS Recommended

For 24/7 operation and consistent execution speed, VPS hosting is strongly recommended

⚠️

High Spread Warning

Very high spreads (>50 points) may cause SL/TP validation failures. Consider spread filter.

⚠️

IMPORTANT RISK DISCLOSURE

Trading involves substantial risk of loss and may not be suitable for all investors.

Trading foreign exchange, commodities, stocks, futures, options, and other financial instruments on margin carries a high level of risk and may not be suitable for all investors. The high degree of leverage can work against you as well as for you. Before deciding to trade, you should carefully consider your investment objectives, level of experience, and risk appetite. There is a possibility that you could sustain a loss of some or all of your initial investment and therefore you should not invest money that you cannot afford to lose.

About This Expert Advisor

The Double Engulfing Pattern EA is a software tool designed to identify and execute trades based on predefined algorithms that detect candlestick patterns. It does not guarantee profits, success, or positive results. Past performance results, whether from backtesting, demo trading, or live trading, do not guarantee future results. Market conditions, broker execution quality, slippage, spread variations, and other factors can significantly affect performance.

Algorithmic Trading Risks

System failures can occur due to:

  • Internet connectivity issues or power outages
  • Server downtime at your broker or VPS provider
  • Software bugs, coding errors, or unexpected market conditions
  • High-impact news events causing extreme volatility
  • Broker execution delays, requotes, or order rejections
  • Gaps in price that bypass stop loss levels

User Responsibility

You are entirely responsible for:

  • Understanding the EA's logic, parameters, and risk profile
  • Properly configuring and testing parameters before live trading
  • Managing risk through appropriate position sizing and capital allocation
  • Monitoring the EA daily and intervening when necessary
  • Maintaining stable platform operation (VPS, reliable internet)
  • Complying with your broker's terms of service regarding automated trading
  • All trading decisions and their financial consequences

No Warranties

KeyAlgos provides this Expert Advisor "as is" without warranties of any kind, express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, or non-infringement. We do not guarantee the EA will be error-free, uninterrupted, or meet your specific requirements. The EA is provided for educational and informational purposes alongside its trading functionality.

Recommendations

  • Test the EA thoroughly on a DEMO account for at least 2-4 weeks
  • Start live trading with minimum risk (0.5% per trade) for first 2 weeks
  • Never risk more than 2% of account balance on any single trade
  • Use a VPS for 24/7 operation to avoid downtime
  • Check Expert logs daily for errors or anomalies
  • Keep MT5 platform updated to latest build
  • Have a manual intervention plan for major news events
  • Keep detailed records of all trades and parameter changes
  • Consider periodic re-optimization as market conditions evolve
  • Consult with a qualified financial advisor before live trading