Precision algorithmic trading system detecting high-probability double engulfing patterns on XAUUSD with ATR-based validation and dynamic risk management
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.
State machine architecture ensures exact pattern matching with ATR-based candle validation
Tick-level processing during breakout phases for instant trade execution
Optional C2 low protection and flexible risk management with dynamic position sizing
Comprehensive debug logging and trade transaction tracking for detailed analysis
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.
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.
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.
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.
Currently implemented as fixed risk:reward exits. Future iterations may include trailing stops based on ATR or fractal levels.
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.
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.
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.
While optimized for M1, the EA supports any timeframe through the configurable InpTimeframe parameter. ATR calculations automatically adapt to selected timeframe volatility characteristics.
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.
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.
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 double engulfing patterns are identified and validated.
How open positions are monitored and closed based on risk:reward parameters.
Position sizing calculation and risk validation workflow.
High-level overview of EA components and their interactions.
State machine architecture tracks pattern progression through four distinct candles, ensuring precise double engulfing formation before trade execution.
Each candle must exceed dynamically calculated ATR thresholds, ensuring patterns form with significant market participation rather than noise.
Optional protective filter that invalidates patterns if price breaks Candle 2's extreme before pattern completion, preventing false breakouts.
Automatically calculates optimal lot size based on account balance, risk percentage, and actual stop loss distance for precise risk control.
Choose between Candle 3 or Candle 4 extremes for stop loss placement, with pip adjustment for fine-tuning distance.
Prevents stale patterns from executing by setting maximum wait time after pattern completion (default 3 candles).
Real-time debug information and trade transaction logging for complete transparency and post-analysis.
While optimized for XAUUSD, the EA automatically adapts to any symbol's pip structure and contract specifications.
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 |
Parameters controlling volatility measurement and candle size validation thresholds.
Settings defining pattern structure, tolerance, and protection mechanisms.
Core execution parameters including SL/TP, magic number, and timeframe settings.
Risk management parameters controlling position sizing and risk per trade.
Control over debug logging and visibility of internal calculations.
Comprehensive backtesting and live trading 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% |
⚠️ 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\
Right-click the Expert Advisors folder in Navigator → Refresh, or restart MT5. The EA should appear as "Double Engulfing Pattern EA".
Click the "Algo Trading" button in top toolbar (must turn GREEN). If red, click to enable. Without this, the EA cannot execute trades.
Check top-right corner of chart:
Double-click the EA name in top-left corner of chart, or right-click chart → Expert Advisors → Properties.
| 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 |
After 2 weeks of consistent performance:
| Platform | MetaTrader 5 |
| MQL Version | 5.00 (Build 2600+) |
| Language | MQL5 |
| Type | Expert Advisor (EA) |
| Execution Mode | OnTick (tick-by-tick) |
| 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 |
| Minimum Balance | $500 (1% risk) |
| 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 | 18 functions |
| Indicator Handles | 1 (ATR) |
| Include Files | <Trade\Trade.mqh> |
| Complexity | Advanced (State Machine) |
Compatible with brokers using market execution (most ECN/STP brokers)
Auto-detects and adapts to 4 or 5 digit broker pricing for XAUUSD
Works with Standard, ECN, and STP account types with proper tick value
Supports micro lots (0.01) up to standard lots (1.0) with automatic scaling
For 24/7 operation and consistent execution speed, VPS hosting is strongly recommended
Very high spreads (>50 points) may cause SL/TP validation failures. Consider spread filter.
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.
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.
System failures can occur due to:
You are entirely responsible for:
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.