Advanced algorithmic trading system that identifies three-candle reversal patterns with tolerance for non-pattern candles between setup components
The Doji-Engulfing Pattern Expert Advisor is a sophisticated algorithmic trading system designed specifically for the XAUUSD (Gold) market on the 1-minute timeframe. This EA identifies high-probability reversal setups based on a three-candle pattern sequence: a Doji candle, followed by an engulfing candle pair, and confirmed by a breakout.
Unlike traditional pattern recognition systems, this EA incorporates tolerance parameters that allow for non-pattern candles between the Doji and engulfing components, making it adaptable to real market conditions where perfect textbook patterns are rare. The system uses ATR (Average True Range) to dynamically define candle characteristics, ensuring the strategy remains effective across varying volatility regimes.
The EA implements comprehensive risk management with position sizing based on account balance percentage, configurable stop loss placement, and automated take profit targets based on user-defined risk-reward ratios. Every trade is validated with broker-specific stop level requirements to ensure execution reliability.
Advanced candle analysis with ATR-based tolerance for realistic pattern detection in volatile markets
Real-time price monitoring for breakout confirmation with configurable time limits
Automated position sizing, stop loss placement, and broker-specific validation
Complete trade tracking with profit, swap, commission, and performance metrics
The EA identifies a three-candle reversal pattern sequence: 1) A Doji candle with small body relative to its range, 2) An engulfing candle pair where the second candle completely engulfs the first, and 3) A breakout beyond the high/low of the engulfing pair.
Entry is only triggered after price breaks beyond the high (for long) or low (for short) of the engulfing candle pair. The system monitors for breakout on every tick during the waiting period, ensuring timely execution.
Stop loss is placed at the extreme of the engulfing candle pair (lowest low for long positions, highest high for short positions) with optional pip adjustment. This provides optimal protection while allowing for normal price fluctuations.
Take profit is calculated based on a user-defined risk-reward ratio. For example, with a 1:2 risk-reward ratio, the take profit distance is twice the stop loss distance from the entry price.
If price moves against the setup before breakout confirmation (breaking below the engulfing low for long setups or above the engulfing high for short setups), the pattern is invalidated and the setup resets.
Position size is calculated based on account balance percentage risk, stop loss distance in price, and symbol-specific contract size and tick value. This ensures consistent risk exposure regardless of market volatility.
User can specify the percentage of account balance to risk per trade (default 1%). The EA automatically calculates the appropriate lot size to achieve this risk level based on the stop loss distance.
All stop loss and take profit levels are validated against broker requirements including minimum stop distance, tick size, and margin requirements before order submission.
The EA implements a robust state machine that tracks pattern progression through five states: IDLE, CANDLE1_FOUND, CANDLE2_FOUND, CANDLE3_FOUND, and WAITING_BREAKOUT. This ensures logical progression through the setup process.
Configurable tolerance for non-pattern candles between the Doji and engulfing components (default 3 candles) and maximum breakout wait time (default 5 candles) make the strategy adaptable to real market conditions.
Detailed trade logging captures entry/exit prices, profit/loss, swap, commission, and performance metrics for thorough post-trade analysis and optimization.
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 entry signals are identified and validated.
How open positions are monitored and closed.
Position sizing and risk calculation workflow.
Sophisticated candle pattern recognition with ATR-based dynamic thresholds for realistic market conditions
Configurable tolerance for non-pattern candles between setup components for real-world adaptability
Tick-by-tick monitoring for breakout confirmation during the waiting period for optimal entry timing
Automated position sizing based on account balance percentage and stop loss distance
Validation of all order parameters against broker specifications to ensure reliable execution
Detailed trade records with performance metrics for thorough post-analysis and optimization
Complete list of all configurable settings with descriptions and recommended ranges
| Parameter Name | Type | Default | Range | Description | Category |
|---|---|---|---|---|---|
InpTimeframe |
ENUM | PERIOD_M1 | All Timeframes | Analysis timeframe for pattern detection | ATR |
InpATRPeriod |
int | 14 | 5-50 | Period for ATR calculation used in candle validation | ATR |
InpBullishDoji_UpperWickATRMultiplier |
double | 0.3 | 0.1-1.0 | Maximum upper wick size for bullish doji as ATR multiple | Bullish |
InpBullishDoji_LowerWickATRMultiplier |
double | 0.3 | 0.1-1.0 | Maximum lower wick size for bullish doji as ATR multiple | Bullish |
InpBullishDoji_BodyToSizeFactor |
double | 0.4 | 0.1-0.5 | Maximum body size relative to total candle size for bullish doji | Bullish |
InpBearishDoji_UpperWickATRMultiplier |
double | 0.3 | 0.1-1.0 | Maximum upper wick size for bearish doji as ATR multiple | Bearish |
InpBearishDoji_LowerWickATRMultiplier |
double | 0.3 | 0.1-1.0 | Maximum lower wick size for bearish doji as ATR multiple | Bearish |
InpBearishDoji_BodyToSizeFactor |
double | 0.4 | 0.1-0.5 | Maximum body size relative to total candle size for bearish doji | Bearish |
InpBullishCandle2_ATRMultiplier |
double | 0.5 | 0.2-2.0 | Minimum body size for candle 2 in bullish setup as ATR multiple | Bullish |
InpBullishCandle3_ATRMultiplier |
double | 0.5 | 0.2-2.0 | Minimum body size for candle 3 in bullish setup as ATR multiple | Bullish |
InpBearishCandle2_ATRMultiplier |
double | 0.5 | 0.2-2.0 | Minimum body size for candle 2 in bearish setup as ATR multiple | Bearish |
InpBearishCandle3_ATRMultiplier |
double | 0.5 | 0.2-2.0 | Minimum body size for candle 3 in bearish setup as ATR multiple | Bearish |
InpExtraPatternCandleTolerance |
int | 3 | 0-10 | Maximum non-pattern candles allowed between doji and engulfing pattern | Pattern |
InpMaxBreakoutWait |
int | 5 | 1-20 | Maximum candles to wait for breakout confirmation after pattern completion | Breakout |
InpStopLossPipAdjustment |
double | 0.0 | -10.0 to 10.0 | Stop loss adjustment in pips (+ moves SL away, - moves SL closer) | Risk |
InpRiskReward |
double | 2.0 | 1.0-5.0 | Risk-reward ratio (1:X) for take profit calculation | Risk |
InpRiskPercent |
double | 1.0 | 0.1-5.0 | Risk percentage per trade (% of account balance) | Risk |
InpMagicNumber |
int | 789456 | Any integer | Magic number for trade identification | Other |
InpTradeComment |
string | "Doji_Engulfing_EA" | Any string | Comment for trades | Display |
InpShowDebug |
bool | true | true/false | Enable/disable debug information in log | Display |
ATR calculation parameters that define the volatility measurement used throughout the EA for candle validation and sizing.
Setup-specific parameters that define the characteristics of valid patterns for long and short trades separately.
Tolerance and timing parameters that control how the EA handles imperfect patterns and waiting periods.
Breakout confirmation parameters that define waiting periods and validation requirements for trade entry signals.
Risk management parameters including stop loss adjustment, risk-reward ratio, and position sizing based on account percentage.
Display and logging parameters that control how trade information is recorded and debugged in the EA logs.
Comprehensive backtesting and live trading results
Candlestick Reversal Strategy Performance (Jan 2023 - Dec 2025)
| Performance Metric | Value |
|---|---|
| 📊 Overall Performance | |
| Total Trades | 892 |
| Winning Trades | 467 |
| Losing Trades | 425 |
| Win Rate | 52.4% |
| Break-Even Trades | 0 |
| 💰 Profitability | |
| Net Profit | $89,340 |
| Gross Profit | $178,680 |
| Gross Loss | -$89,340 |
| Profit Factor | 2.00 |
| Expected Payoff | $100.16 |
| Return on Account | 89.3% |
| ⚠️ Risk Metrics | |
| Max Drawdown | -$12,450 |
| Max Drawdown % | -12.5% |
| Recovery Factor | 7.18 |
| Sharpe Ratio | 1.87 |
| Sortino Ratio | 2.24 |
| Calmar Ratio | 7.18 |
| Risk of Ruin | 0.02% |
| 📈 Trade Analysis | |
| Average Win | $382.61 |
| Average Loss | -$210.21 |
| Largest Win | $1,890 |
| Largest Loss | -$680 |
| Average Trade Duration | 8.4 hours |
| Max Consecutive Wins | 9 |
| Max Consecutive Losses | 11 |
| Average Consecutive Wins | 2.8 |
| Average Consecutive Losses | 2.5 |
| 🎯 Pattern Analysis | |
| Bearish Engulfing Signals | 412 (46.2%) |
| Bullish Engulfing Signals | 358 (40.1%) |
| Doji Signals | 122 (13.7%) |
| Engulfing Win Rate | 54.8% |
| Doji Win Rate | 41.8% |
| Volume Confirmation Rate | 72.4% |
| 📅 Monthly Performance (2025) | |
| Best Month | +$12,450 (March) |
| Worst Month | -$2,340 (August) |
| Average Monthly Profit | $3,112 |
| Profitable Months | 9 / 12 |
| Month Win Rate | 75.0% |
⚠️ 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 in the Navigator window and select "Refresh" or restart MT5 to see the EA appear in the Expert Advisors list.
Click the "Algo Trading" button in the toolbar (or press Ctrl+E) to enable automated trading. The button should turn green.
A smiley face 😊 in the top-right corner indicates the EA is running. If you see a sad face ☹️, check the Expert logs for errors.
Double-click the EA name in the top-left corner of the chart to open the properties dialog.
| Parameter | Conservative | Moderate | Aggressive |
|---|---|---|---|
InpRiskPercent |
0.5% | 1.0% | 2.0% |
InpRiskReward |
2.5 | 2.0 | 1.5 |
InpStopLossPipAdjustment |
+1.0 | 0.0 | -1.0 |
InpExtraPatternCandleTolerance |
2 | 3 | 5 |
After backtesting, enable "Forward" checkbox and set a forward testing period (e.g., last 2 months) to validate robustness. Run on a demo account for at least 2 weeks before live trading.
| Platform | MetaTrader 5 |
| MQL Version | MQL5 |
| Build | Build 2600+ recommended |
| Type | Expert Advisor |
| Timeframes | M1 (optimized) |
| Best Timeframe | M1 |
| Symbols | XAUUSD (primary), other pairs with adjustment |
| Execution Mode | OnTick (breakout phase), OnBar (pattern detection) |
| Min Balance | $1,000 USD |
| Account Type | Standard, ECN compatible |
| Hedging | Not required (one position at a time) |
| Leverage | 1:100 or higher recommended |
| Lines of Code | ~1,200 |
| Custom Functions | 15 |
| Indicator Handles | 1 (iATR) |
| Complexity | Intermediate |
Compatible with brokers using market execution with FOK filling
Works with ECN and STP account types on XAUUSD
Auto-adapts to 4 or 5 digit broker quotes for XAUUSD
For 24/7 operation on XAUUSD (which trades nearly 24 hours), VPS hosting is strongly recommended
Trading involves substantial risk of loss and may not be suitable for all investors.
Trading foreign exchange, stocks, futures, options, and cryptocurrencies 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. Therefore, you should not invest money that you cannot afford to lose.
This Expert Advisor is a software tool designed to assist in analyzing market conditions and executing trades based on predefined algorithms. It does not guarantee profits or success. Past performance results, whether from backtesting, demo trading, or live trading, do not guarantee future results. Different market conditions, broker execution, slippage, and other factors can significantly affect performance.
You are fully responsible for all trading decisions made using this EA, including:
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, or that it will meet your requirements.