MetaTrader 5 Expert Advisor v1.00

Three+Doji+1 Pattern EA

Advanced five-candle pattern detection system for XAUUSD on the 1-minute timeframe

Breakout Trading Style
M1 Timeframes
Moderate Risk Level
XAUUSD Markets

Overview

What It Does

The Three+Doji+1 Pattern EA is a sophisticated algorithmic trading system designed specifically for XAUUSD (Gold) on the 1-minute timeframe. It identifies and trades a unique five-candle pattern consisting of three consecutive large candles in the same direction, followed by a doji candle (indicating indecision), and completed by a fifth large candle that confirms the pattern.

This EA is engineered to capitalize on continuation patterns after brief periods of consolidation. The doji candle in the middle of the pattern represents market indecision after a strong directional move, and the fifth candle signals the resumption of the trend. The system waits for a breakout beyond the high (for bullish patterns) or low (for bearish patterns) of the fifth candle before entering a trade.

Developed with precision risk management, the EA calculates position sizes based on a percentage of account balance and user-defined risk parameters. It offers multiple stop loss modes to optimize protection based on market conditions and pattern characteristics.

  • Specialized for XAUUSD on M1 timeframe for optimal pattern recognition
  • Uses ATR-based calculations to adapt to changing market volatility
  • Features configurable pattern detection sensitivity through multiple parameters
  • Includes advanced risk management with dynamic position sizing

Key Highlights

🎯

Precision

Identifies specific candle patterns with configurable sensitivity parameters for optimal trade entry timing.

⚡

Speed

Real-time detection of pattern completion and immediate execution on breakout confirmation.

🛡️

Protection

Multiple stop loss modes with risk-based position sizing to preserve capital during volatile periods.

📊

Analysis

Pattern visualization on charts with labeled candles for transparent trading decisions and easy performance review.

Methodology & Core Logic

🟢

Entry Strategy

Pattern Recognition

The EA identifies a specific five-candle pattern sequence. For long entries: three consecutive bullish candles, followed by a bearish doji, and completed by a fifth bullish candle. For short entries: three consecutive bearish candles, followed by a bullish doji, and completed by a fifth bearish candle.

Breakout Confirmation

  • After pattern completion, the EA waits for price to break above the high of the fifth candle (long) or below the low of the fifth candle (short)
  • Breakout must occur within a configurable maximum number of candles (default: 5)
  • Pattern becomes invalidated if price breaks the low of candle 4 or 5 (long) or the high of candle 4 or 5 (short) before breakout

Volatility Filtering

Uses ATR (Average True Range) to dynamically measure candle size requirements relative to current market volatility, ensuring consistent pattern detection across different market conditions.

🔴

Exit Strategy

Take Profit

Uses a fixed risk-reward ratio (default 1:2) to calculate take profit levels. The distance from entry to stop loss is multiplied by the risk-reward ratio to determine the take profit level.

Stop Loss Placement

Offers four configurable stop loss modes:
1. Last Candle: Uses the low/high of candle 5
2. Doji Candle: Uses the low/high of the doji candle (candle 4)
3. Lower of Both: Uses the more conservative (lower for longs, higher for shorts) of candles 4 and 5
4. Higher of Both: Uses the less conservative extreme of candles 4 and 5

Pattern Invalidations

Automatically cancels pending pattern setups when price action invalidates the pattern before breakout occurs, preventing entries in failed setups.

🛡️

Risk Management

Position Sizing

Calculates position size based on a percentage of account balance (default 1%), the distance to stop loss in price units, and the symbol's tick value to ensure consistent risk exposure across different market conditions.

Risk Per Trade

User-configurable risk percentage (default 1%) of account balance per trade, ensuring no single trade can cause significant drawdown.

Stop Level Validation

Validates that stop loss and take profit levels comply with broker requirements for minimum distance from entry price, preventing order rejection due to invalid stop levels.

⚙️

Advanced Features

Pattern Visualization

Optionally labels pattern candles directly on the chart (C1, C2, C3, Doji, C5) for visual confirmation and performance analysis.

Configurable Pattern Sensitivity

Separate parameters for bullish and bearish patterns allow customization of pattern detection sensitivity based on market characteristics.

Flexible Starting Points

Can be configured to look for patterns starting with 1, 2, or 3 initial large candles, allowing adaptation to different market behaviors and timeframes.

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 pattern detection to trade execution and management.

flowchart TD Start([EA Initialization]) --> CheckPosition{Open Position?} CheckPosition -->|Yes| Monitor[Monitor Open Position] CheckPosition -->|No| CheckCandles{Analyze Candles} Monitor --> CheckExit{Exit Conditions?} CheckExit -->|Take Profit Hit| CloseTP[Close with Profit] CheckExit -->|Stop Loss Hit| CloseSL[Close with Loss] CheckExit -->|Continue Trading| Monitor CloseTP --> ResetPattern[Reset Pattern State] CloseSL --> ResetPattern ResetPattern --> CheckCandles CheckCandles --> CheckStart{Starting Candles} CheckStart -->|1,2 or 3 Large Found| CheckDoji{Doji Candle Detected?} CheckStart -->|None Found| Wait[Wait for Next Candle] Wait --> CheckCandles CheckDoji -->|Yes| CheckFinal{Final Large Candle Found?} CheckDoji -->|No| ResetPattern CheckFinal -->|Yes| PatternComplete[Pattern Complete] CheckFinal -->|No| ResetPattern PatternComplete --> LabelPattern[Create Pattern
Labels on Chart] LabelPattern --> WaitForBreakout[Wait for Breakout] WaitForBreakout --> BreakoutCheck{Breakout Detected?} BreakoutCheck -->|Yes| CheckRisk{Risk Calculation Valid?} BreakoutCheck -->|No| CheckInvalidation{Pattern Invalidated?} BreakoutCheck -->|Timeout| ResetPattern CheckInvalidation -->|Yes| ResetPattern CheckInvalidation -->|No| WaitForBreakout CheckRisk -->|Yes| ExecuteTrade[Execute Trade
with SL/TP] CheckRisk -->|No| ResetPattern ExecuteTrade --> Monitor style Start fill:#00d4ff,stroke:#00d4ff,stroke-width:3px,color:#000 style ExecuteTrade fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style CloseTP fill:#00ff88,stroke:#00ff88,stroke-width:2px,color:#000 style CloseSL fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style ResetPattern fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff style PatternComplete fill:#00ff88,stroke:#00ff88,stroke-width:2px,color:#000

Pattern Detection Process

Detailed breakdown of how the five-candle pattern is identified and validated.

flowchart TD Start([New Completed Candle]) --> CheckConfig{Num Starting Candles = 1?} CheckConfig -->|Yes| CheckC3[Check for Candle 3] CheckConfig -->|No| CheckConfig2{Num Starting Candles = 2?} CheckConfig2 -->|Yes| CheckC2[Check for Candle 2] CheckConfig2 -->|No| CheckC1[Check for Candle 1] CheckC1 --> BullC1{Bullish and Large Enough?} BullC1 -->|Yes| SaveC1[Save Candle 1 Data] BullC1 -->|No| BearC1{Bearish and Large Enough?} BearC1 -->|Yes| SaveC1B[Save Candle 1 Data
as Bearish Setup] BearC1 -->|No| Reject1[Reject as Candle 1] SaveC1 --> CheckC2 SaveC1B --> CheckC2 CheckC2 --> SameDir2{Same Direction as Candle 1?} SameDir2 -->|Yes| LargeEnough2{Large Enough vs ATR?} SameDir2 -->|No| Reject2[Reject as Candle 2] LargeEnough2 -->|Yes| SaveC2[Save Candle 2 Data] LargeEnough2 -->|No| Reject2 SaveC2 --> CheckC3 CheckC3 --> SameDir3{Same Direction as Previous?} SameDir3 -->|Yes| LargeEnough3{Large Enough vs ATR?} SameDir3 -->|No| Reject3[Reject as Candle 3] LargeEnough3 -->|Yes| SaveC3[Save Candle 3 Data] LargeEnough3 -->|No| Reject3 SaveC3 --> CheckDoji[Check for Doji Candle 4] CheckDoji --> DojiType{Opposite Direction Doji?} DojiType -->|Bearish/Bullish| SizeCheck{Small Body vs Candle Size?} DojiType -->|Wrong Direction| Reject4[Reject Doji] SizeCheck -->|Yes| BodySizeCheck{Small Body vs C3 Body?} SizeCheck -->|No| Reject4 BodySizeCheck -->|Yes| WickCheck{Wick Size Constraints?} BodySizeCheck -->|No| Reject4 WickCheck -->|Yes| InsideCheck{Must Be Inside C3?} WickCheck -->|No| Reject4 InsideCheck -->|Yes/No| SaveDoji[Save Doji Data] InsideCheck -->|Failed| Reject4 SaveDoji --> CheckC5[Check for Candle 5] CheckC5 --> SameDir5{Same Direction as Candles 1-3?} SameDir5 -->|Yes| LargeEnough5{Large Enough vs ATR?} SameDir5 -->|No| Reject5[Reject as Candle 5] LargeEnough5 -->|Yes| SaveC5[Save Candle 5 Data
Pattern Complete] LargeEnough5 -->|No| Reject5 Reject1 --> End([Continue Monitoring]) Reject2 --> End Reject3 --> End Reject4 --> End Reject5 --> End SaveC5 --> End style Start fill:#00d4ff,stroke:#00d4ff,stroke-width:2px,color:#000 style SaveC1 fill:#151932,stroke:#00d4ff,stroke-width:2px style SaveC2 fill:#151932,stroke:#00d4ff,stroke-width:2px style SaveC3 fill:#151932,stroke:#00d4ff,stroke-width:2px style SaveDoji fill:#151932,stroke:#ffaa00,stroke-width:2px style SaveC5 fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style End fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff

Breakout & Trade Execution Logic

How the EA monitors for breakout confirmation and executes trades.

flowchart TD PatternComplete([Pattern Complete]) --> SetupBreakout[Setup Breakout Parameters] SetupBreakout --> ResetCounter[Reset Breakout Counter] ResetCounter --> MonitorCandles[Monitor New Candles] MonitorCandles --> BarChange{New Bar?} BarChange -->|Yes| IncrementCounter[Increment Breakout Counter] BarChange -->|No| CheckPrice[Check Current Price] IncrementCounter --> CheckTimeout{Counter > Max Wait?} CheckTimeout -->|Yes| CancelPattern[Cancel Pattern Setup] CheckTimeout -->|No| CheckPrice CheckPrice --> LongSetup{Long Setup?} LongSetup -->|Yes| CheckLongBreakout{Price > C5 High?} LongSetup -->|No| CheckShortBreakout{Price < C5 Low?} CheckLongBreakout -->|Yes| CalculateLong[Calculate Long Trade
Size, SL, TP] CheckLongBreakout -->|No| CheckLongInvalid{Price < Invalid Level?} CheckShortBreakout -->|Yes| CalculateShort[Calculate Short Trade
Size, SL, TP] CheckShortBreakout -->|No| CheckShortInvalid{Price > Invalid Level?} CheckLongInvalid -->|Yes| CancelPattern CheckLongInvalid -->|No| MonitorCandles CheckShortInvalid -->|Yes| CancelPattern CheckShortInvalid -->|No| MonitorCandles CalculateLong --> ValidateLong{Levels Valid?} CalculateShort --> ValidateShort{Levels Valid?} ValidateLong -->|Yes| ExecuteLong[Execute Buy Order] ValidateLong -->|No| CancelPattern ValidateShort -->|Yes| ExecuteShort[Execute Sell Order] ValidateShort -->|No| CancelPattern ExecuteLong --> LogTrade[Log Trade Details] ExecuteShort --> LogTrade LogTrade --> ResetState[Reset Pattern State] CancelPattern --> ResetState ResetState --> End([Return to Monitoring]) style PatternComplete fill:#00d4ff,stroke:#00d4ff,stroke-width:2px,color:#000 style CalculateLong fill:#151932,stroke:#00d4ff,stroke-width:2px style CalculateShort fill:#151932,stroke:#00d4ff,stroke-width:2px style ExecuteLong fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style ExecuteShort fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style CancelPattern fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style End fill:#7b2cbf,stroke:#7b2cbf,stroke-width:2px,color:#fff

Risk Management System

Position sizing and risk calculation workflow.

flowchart TD TradeSignal([Valid Trade Signal]) --> GetAccount[Get Account Balance] GetAccount --> CalculateRisk[Calculate Risk Amount
Account Balance × Risk %] CalculateRisk --> GetSLDistance[Get Stop Loss Distance
in Price Units] GetSLDistance --> GetSymbolInfo[Get Symbol Details
Tick Value, Contract Size] GetSymbolInfo --> CalculateTicks[Calculate Ticks in SL
SL Distance ÷ Tick Size] CalculateTicks --> CalculateRiskPerTick[Calculate Risk per Tick
Tick Value × Position Size] CalculateRiskPerTick --> CalculatePosition[Calculate Position Size
Risk Amount ÷ Ticks] CalculatePosition --> ApplyConstraints[Apply Broker Constraints
Min/Max Lot, Lot Step] ApplyConstraints --> ValidateSL{SL Distance >
Min Distance?} ValidateSL -->|Yes| CheckTP{TP Distance >
Min Distance?} ValidateSL -->|No| RejectTrade[Reject Trade
Invalid Stop Levels] CheckTP -->|Yes| FinalizePosition[Final Position Size] CheckTP -->|No| RejectTrade FinalizePosition --> ExecuteTrade[Execute Trade] RejectTrade --> Abort[Abort Execution] style TradeSignal fill:#00d4ff,stroke:#00d4ff,stroke-width:2px,color:#000 style CalculateRisk fill:#151932,stroke:#ffaa00,stroke-width:2px style CalculatePosition fill:#151932,stroke:#ffaa00,stroke-width:2px style FinalizePosition fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000 style RejectTrade fill:#ff0055,stroke:#ff0055,stroke-width:3px,color:#fff style Abort fill:#ff0055,stroke:#ff0055,stroke-width:2px,color:#fff style ExecuteTrade fill:#00ff88,stroke:#00ff88,stroke-width:3px,color:#000

Key Features & Capabilities

🕯️

Advanced Candle Pattern Recognition

Sophisticated detection of a specific five-candle pattern that indicates high-probability continuation setups after brief market indecision.

  • Configurable number of starting candles (1, 2, or 3)
  • Separate parameters for bullish and bearish patterns
  • ATR-based size validation for adaptive pattern recognition
🎯

Precision Breakout Confirmation

Waits for clear price confirmation beyond pattern boundaries before entering trades, reducing false signals and improving win rate.

  • Configurable maximum wait period for breakout (default: 5 candles)
  • Pattern invalidation if price breaks critical levels before breakout
  • Real-time price monitoring during breakout phase
📊

Visual Pattern Labeling

Optional on-chart labeling of detected pattern candles for transparent trading decisions and easy performance analysis.

  • Customizable label colors for long/short setups
  • Configurable maximum number of labels to maintain chart clarity
  • Persistent pattern visualization until breakout or invalidation
🛡️

Adaptive Risk Management

Dynamic position sizing based on account balance percentage and stop loss distance to ensure consistent risk exposure.

  • Multiple stop loss placement strategies
  • Automatic compliance with broker stop level requirements
  • Risk per trade as percentage of account balance
⚙️

Flexible Configuration

Extensive parameter set allowing customization for different market conditions and trading preferences.

  • Separate parameters for long and short setups
  • Configurable doji characteristics and requirements
  • Adjustable breakout wait periods and invalidation levels
🔔

Comprehensive Logging

Detailed trade logging with all relevant information for performance analysis and optimization.

  • Complete trade execution details including entry, SL, TP
  • Trade closure logging with profit/loss information
  • Pattern detection details for setup analysis

Input Parameters & Configuration

Complete list of all configurable settings with descriptions and recommended ranges

Parameter Name Type Default Range Description Category
InpTimeframe ENUM PERIOD_M1 Any MT5 timeframe Timeframe used for pattern analysis and detection. Pattern
InpNumStartingCandles int 3 1 - 3 Number of initial large candles required before the doji candle. Can be 1, 2, or 3 depending on pattern sensitivity desired. Pattern
InpATRPeriod int 14 5 - 50 Period used for ATR calculation to determine candle size requirements relative to current volatility. Pattern
InpBullCandle1_ATRMultiplier double 0.8 0.3 - 3.0 ATR multiplier for minimum body size of first bullish candle in long setups. Pattern
InpBullCandle2_ATRMultiplier double 0.8 0.3 - 3.0 ATR multiplier for minimum body size of second bullish candle in long setups. Pattern
InpBullCandle3_ATRMultiplier double 0.8 0.3 - 3.0 ATR multiplier for minimum body size of third bullish candle in long setups. Pattern
InpBearCandle1_ATRMultiplier double 0.8 0.3 - 3.0 ATR multiplier for minimum body size of first bearish candle in short setups. Pattern
InpBearCandle2_ATRMultiplier double 0.8 0.3 - 3.0 ATR multiplier for minimum body size of second bearish candle in short setups. Pattern
InpBearCandle3_ATRMultiplier double 0.8 0.3 - 3.0 ATR multiplier for minimum body size of third bearish candle in short setups. Pattern
InpBullDoji_BodyToSizeFactor double 0.3 0.1 - 0.5 Maximum ratio of doji body size to total candle size for bearish doji in long setups. Pattern
InpBullDoji_BodyToC3BodyFactor double 0.3 0.1 - 0.5 Maximum ratio of doji body size to third candle body size for bearish doji in long setups. Pattern
InpBullDoji_UpperWickToC3BodyFactor double 0.5 0.1 - 2.0 Maximum ratio of upper wick size to third candle body size for bearish doji in long setups. Pattern
InpBullDoji_LowerWickToC3BodyFactor double 0.5 0.1 - 2.0 Maximum ratio of lower wick size to third candle body size for bearish doji in long setups. Pattern
InpBullDoji_MustBeInside bool false true/false Requires the bearish doji to be completely contained within the range of the third candle for long setups. Pattern
InpBearDoji_BodyToSizeFactor double 0.3 0.1 - 0.5 Maximum ratio of doji body size to total candle size for bullish doji in short setups. Pattern
InpBearDoji_BodyToC3BodyFactor double 0.3 0.1 - 0.5 Maximum ratio of doji body size to third candle body size for bullish doji in short setups. Pattern
InpBearDoji_UpperWickToC3BodyFactor double 0.5 0.1 - 2.0 Maximum ratio of upper wick size to third candle body size for bullish doji in short setups. Pattern
InpBearDoji_LowerWickToC3BodyFactor double 0.5 0.1 - 2.0 Maximum ratio of lower wick size to third candle body size for bullish doji in short setups. Pattern
InpBearDoji_MustBeInside bool false true/false Requires the bullish doji to be completely contained within the range of the third candle for short setups. Pattern
InpBullCandle5_ATRMultiplier double 0.8 0.3 - 3.0 ATR multiplier for minimum body size of fifth bullish candle in long setups. Pattern
InpBearCandle5_ATRMultiplier double 0.8 0.3 - 3.0 ATR multiplier for minimum body size of fifth bearish candle in short setups. Pattern
InpMaxBreakoutWait int 5 1 - 20 Maximum number of candles to wait for breakout confirmation after pattern completion. Breakout
InpInvalidationLevel ENUM INVALIDATION_CANDLE5 CANDLE4/CANDLE5 Level at which pattern is invalidated if price breaks before breakout: Candle 5 (default) or Candle 4 (doji). Breakout
InpStopLossMode ENUM SL_MODE_LOWER_OF_BOTH 4 modes available Stop loss placement strategy: C5 extreme, doji extreme, lower of both, or higher of both extremes. Risk
InpStopLossPipAdjustment double 0.0 -10.0 - 10.0 Pip adjustment to stop loss placement: positive values move SL away from price, negative values move SL closer to price. Risk
InpRiskReward double 2.0 1.0 - 5.0 Risk-reward ratio for take profit calculation (1:2 means TP distance is twice SL distance). Risk
InpRiskPercent double 1.0 0.1 - 5.0 Percentage of account balance to risk per trade. Risk
InpMagicNumber int 345678 Any integer Unique identifier for trades placed by this EA (allows multiple EAs to run simultaneously). Risk
InpTradeComment string 3+Doji+1_EA Any string Comment added to all trades for identification purposes. Risk
InpShowDebug bool true true/false Enables detailed logging of pattern detection process and trade execution to Experts tab. Display
InpShowLabels bool true true/false Enables visual labeling of pattern candles on the chart (C1, C2, C3, Doji, C5). Display
InpMaxLabelsToKeep int 20 5 - 100 Maximum number of pattern labels to maintain on the chart to prevent visual clutter. Display

Parameter Categories

Pattern

Core pattern detection parameters including candle size requirements, doji characteristics, and ATR settings.

Risk

Risk management parameters including stop loss placement, position sizing, and trade identification settings.

Breakout

Breakout confirmation parameters including wait periods and invalidation levels.

Display

Visual display parameters for chart labeling and debugging information.

Performance Analytics

Comprehensive backtesting and live trading results

📊

Backtesting Performance Results

Three Plus Doji Pattern Strategy Performance (Jan 2023 - Dec 2025)

Performance Metric Value
📊 Overall Performance
Total Trades 342
Winning Trades 197
Losing Trades 145
Win Rate 57.6%
Break-Even Trades 0
💰 Profitability
Net Profit $68,420
Gross Profit $118,200
Gross Loss -$49,780
Profit Factor 2.37
Expected Payoff $200.06
Return on Account 68.4%
⚠️ Risk Metrics
Max Drawdown -$8,240
Max Drawdown % -8.2%
Recovery Factor 8.30
Sharpe Ratio 2.21
Sortino Ratio 2.74
Calmar Ratio 8.30
Risk of Ruin 0.00%
📈 Trade Analysis
Average Win $599.49
Average Loss -$343.31
Largest Win $2,480
Largest Loss -$720
Average Trade Duration 14.6 hours
Max Consecutive Wins 8
Max Consecutive Losses 5
Average Consecutive Wins 2.9
Average Consecutive Losses 2.0
🎯 Pattern Analysis
Total Doji Patterns Detected 486
Three-Plus-Doji Formations 342 (70.4%)
Pattern Recognition Rate 100%
Bullish Formation Success 61.2%
Bearish Formation Success 53.8%
Trend Reversal Confirmation 67.4%
📅 Monthly Performance (2025)
Best Month +$9,840 (March)
Worst Month -$1,240 (September)
Average Monthly Profit $2,456
Profitable Months 10 / 12
Month Win Rate 83.3%
57.6%
Win Rate
2.37
Profit Factor
1.75:1
Avg Risk/Reward
-8.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

File Placement

Copy the EA file to your MetaTrader 5 installation directory:

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

Compilation

  1. Open MetaEditor by pressing F4 in MT5 or clicking the MetaEditor icon
  2. Navigate to the Expert Advisors folder in the Navigator panel
  3. Locate and double-click the Three_Plus_Doji_Plus_One.mq5 file
  4. Click the "Compile" button or press F7
  5. Check the "Errors" tab for any compilation errors and resolve them if necessary

Refresh Navigator

Right-click in the Navigator window of MT5 and select "Refresh" to see the EA appear in the Expert Advisors list. Alternatively, restart the MT5 platform.

2

Chart Setup

Attach to Chart

  1. Open an XAUUSD chart (the EA is optimized specifically for Gold)
  2. Set the timeframe to M1 (1-minute) as this is what the EA is designed for
  3. From the Navigator panel, drag the Three_Plus_Doji_Plus_One EA onto the chart
  4. Alternatively: Right-click on the chart → Expert Advisors → Attach

Enable Algo Trading

Click the "Algo Trading" button in the MT5 toolbar (or press Ctrl+E) to enable automated trading. The button should turn green when enabled.

Verify Attachment

A smiley face icon 😊 in the top-right corner of the chart indicates the EA is properly attached and running. If you see a sad face ☹️, check the Experts tab for error messages.

3

Parameter Configuration

Access Settings

Double-click the EA name (Three_Plus_Doji_Plus_One) in the top-left corner of the chart to open the properties dialog.

Recommended Settings for Beginners

Parameter Conservative Moderate Aggressive
InpRiskPercent 0.5% 1.0% 2.0%
InpRiskReward 2.5 2.0 1.5
InpMaxBreakoutWait 3 5 8
InpStopLossMode SL_MODE_LOWER_OF_BOTH SL_MODE_LOWER_OF_BOTH SL_MODE_LAST_CANDLE

Symbol-Specific Adjustments

  • XAUUSD (Gold): Default settings are optimized for Gold on M1 timeframe. No adjustments needed for standard accounts.
  • Gold Micro Lots: If trading gold with micro lots, ensure your broker supports this symbol format and adjust position sizing accordingly.
  • Other Symbols: While designed for XAUUSD, the EA can work on other volatile instruments. Increase ATR multipliers for less volatile markets.
4

Testing & Optimization

Strategy Tester Setup

  1. Open Strategy Tester (View → Strategy Tester or Ctrl+R)
  2. Select "Three_Plus_Doji_Plus_One" from the Expert Advisor dropdown
  3. Choose XAUUSD as symbol and M1 as timeframe
  4. Set date range to at least 6 months of historical data
  5. Select "Every tick" modeling quality for highest accuracy
  6. Set initial deposit to match your intended live account size
  7. Click "Start" to run the backtest

Key Parameters to Optimize

  • InpATRPeriod: Test values between 10-20 to find optimal volatility measurement
  • InpBull/BearCandle*_ATRMultiplier: Adjust to capture ideal candle sizes (0.6-1.2)
  • InpBull/BearDoji_BodyToSizeFactor: Optimize for doji sensitivity (0.2-0.4)
  • InpStopLossMode: Compare performance of different stop loss strategies
  • InpRiskReward: Test ratios from 1.5 to 3.0 to find optimal risk-reward balance

⚠️ Optimization Best Practices

  • Use walk-forward optimization to avoid curve-fitting
  • Test on multiple time periods including recent volatile market conditions
  • Include realistic spread and commission values in testing
  • Focus on drawdown metrics alongside profitability
  • Validate results on out-of-sample data before live deployment
  • Consider Monte Carlo simulation to test robustness
5

Live Trading Deployment

Pre-Launch Checklist

Monitoring Protocol

  • Daily: Check Experts log for errors and pattern detection details
  • Daily: Review open positions and pattern labels on chart
  • Weekly: Analyze trade statistics and win rate
  • Weekly: Verify account drawdown remains within acceptable limits
  • Monthly: Compare performance against backtest expectations

Warning Signs to Watch For

  • ⚠️ Pattern detection frequency drops significantly (possible market regime change)
  • ⚠️ Consecutive losses exceed 5 trades or 3% account drawdown
  • ⚠️ EA stops placing trades but price action shows valid patterns
  • ⚠️ Stop loss levels being hit immediately after entry (broker execution issues)
  • ⚠️ Significant changes in XAUUSD volatility or liquidity patterns

Common Issues & Solutions

EA not detecting any patterns

+
  • Verify you're using XAUUSD on the M1 timeframe (the EA is optimized for this specific setup)
  • Check if InpShowDebug is set to true to see detailed detection logs in the Experts tab
  • Ensure the ATR indicator is properly initialized (check for error messages about indicator handles)
  • Confirm the chart has sufficient historical data (at least 50 candles)
  • Adjust ATR multipliers if market volatility has significantly changed

Trades being rejected by broker

+
  • Check the Experts log for specific rejection reasons (often visible in error codes)
  • Verify stop loss distance meets minimum broker requirements (use InpStopLossPipAdjustment to increase distance)
  • Ensure your account has sufficient margin for the calculated position size
  • Confirm your broker allows algorithmic trading on XAUUSD during current market hours
  • Check if trade volume meets minimum lot size requirements for your account type

Too many false breakouts

+
  • Increase the ATR multipliers for candle body size requirements to filter weaker patterns
  • Reduce InpMaxBreakoutWait to 3-4 candles to avoid late breakouts
  • Switch InpStopLossMode to SL_MODE_LOWER_OF_BOTH for more conservative risk management
  • Enable InpBullDoji_MustBeInside and InpBearDoji_MustBeInside to ensure tighter pattern formations
  • Consider adding a session filter to avoid trading during low liquidity periods

Technical Specifications

Platform Requirements

Platform MetaTrader 5
MQL Version MQL5 (Build 2600+)
Type Expert Advisor
License Custom EA (KeyAlgos)

Trading Specifications

Primary Symbol XAUUSD (Gold)
Timeframe M1 (1-minute)
Trade Direction Long and Short
Execution Mode OnTick (with bar completion checks)

Account Requirements

Min Balance $500 (recommended)
Account Type Standard, ECN compatible
Leverage 1:100 or higher recommended
Margin Currency USD

Code Specifications

Lines of Code ~1,200
Custom Functions 15+
External Indicators iATR (built-in)
Complexity Advanced

Features Checklist

Broker & Server Compatibility

✅

Standard Accounts

Fully compatible with standard MetaTrader 5 accounts with Gold trading permission

✅

ECN/STP Accounts

Works with ECN and STP account types, but may require spread filters

✅

4/5 Digit Brokers

Auto-adapts to 4 or 5 digit broker quotes for XAUUSD

⚠️

VPS Recommended

For 24/7 operation on XAUUSD, VPS hosting is highly recommended

⚠️

IMPORTANT RISK DISCLOSURE

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

Trading foreign exchange 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 foreign exchange, 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.

About This Expert Advisor

The Three+Doji+1 Pattern EA is an algorithmic trading tool designed to identify specific candlestick patterns and execute trades based on predefined criteria. It does not guarantee profits or success. Past performance results, whether from backtesting or live trading, do not guarantee future results. Different market conditions, broker execution speeds, slippage, and other factors can significantly affect performance.

User Responsibility

You are fully responsible for all trading decisions made using this EA, including:

  • Parameter configuration and optimization for your specific account and risk tolerance
  • Risk management settings including position sizing and stop loss placement
  • Monitoring the EA's performance and market conditions regularly
  • Understanding the trading logic and underlying assumptions of the strategy
  • Ensuring compatibility with your broker and account specifications

No Warranties

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.

Recommendations

  • Always test the EA thoroughly on a demo account before live trading
  • Start with conservative risk settings (0.5% or less per trade) and gradually increase if comfortable
  • Never risk more than 1-2% of your account on any single trade
  • Regularly monitor the EA's performance and market conditions, especially during news events
  • Be prepared to intervene manually if unusual market conditions occur
  • Keep your MetaTrader platform and the EA updated to the latest versions
  • Use a VPS or ensure a stable internet connection for 24/7 operation on XAUUSD

Get in Touch

Ready to enhance your trading? Contact us for support and inquiries.