MetaTrader 5 Expert Advisor v1.06

StairStep Reversal Enhanced EA

Advanced 1-minute XAUUSD trading system utilizing three-candle stair-step patterns with doji reversals and inside/engulfing confirmations for high-probability trade entries

Reversal Strategy Type
M1 Timeframe
Medium Risk Level
XAUUSD Primary Market

Overview

What It Does

The StairStep Reversal Enhanced EA is a sophisticated algorithmic trading system designed specifically for the XAUUSD (Gold) market on the 1-minute timeframe. This expert advisor identifies high-probability reversal opportunities by detecting distinctive stair-step patterns formed by three consecutive large candles, followed by a doji candle that signals potential exhaustion of the current trend.

The system employs advanced candlestick pattern recognition combined with technical analysis to identify potential trend reversals. After detecting the stair-step pattern and doji reversal signal, the EA waits for confirmation through either an inside bar or engulfing candle pattern before executing a trade in the anticipated reversal direction. This multi-step verification process significantly enhances the probability of successful trades by filtering out false signals.

The EA incorporates flexible risk management options, allowing traders to choose between percentage-based risk (risking a percentage of account balance per trade) or fixed dollar amount risk. Additionally, it features customizable pattern selection, allowing traders to focus exclusively on inside bar patterns, engulfing patterns, or both types of confirmation signals based on their preference and market conditions.

  • Specialized for XAUUSD on M1 timeframe with optimized parameters
  • Advanced pattern recognition with visual chart labeling for transparency
  • Multiple risk management modes with precise position sizing
  • Configurable pattern selection and tolerance settings for adaptability

Key Highlights

🎯

Precision Entry

Multi-step confirmation process ensures high-quality trade entries with minimal false signals through stair-step patterns and doji reversals.

⚡

Real-time Analysis

Continuously monitors price action and candlestick formations in real-time, providing immediate trade execution when conditions align.

🛡️

Risk Protection

Advanced risk management with customizable stop loss placement, risk-reward ratios, and two distinct risk calculation modes for capital preservation.

📊

Visual Transparency

Pattern labels displayed directly on the chart provide complete transparency of the EA's decision-making process and signal identification.

Methodology & Core Logic

🟢

Entry Strategy

Signal Generation

The EA identifies potential reversal setups by detecting specific candlestick patterns. It first looks for a "start doji" or begins tracking large candles in a stair-step formation (1-3 candles depending on configuration). These large candles must meet ATR-based size thresholds and have limited wicks according to configurable parameters.

Confirmation Methods

  • After the stair-step pattern, a reversal doji candle must form with a small body relative to its range
  • The EA then waits for confirmation via either an inside bar or engulfing candle pattern
  • For long setups: Bullish engulfing or inside bar after bearish stair-step pattern
  • For short setups: Bearish engulfing or inside bar after bullish stair-step pattern

Filtering Mechanism

Each candle in the pattern undergoes rigorous filtering based on ATR multiples, wick size constraints, and body-to-range ratios. The system allows configuration of maximum non-pattern candles between pattern elements and implements timeout mechanisms to avoid stale setups.

🔴

Exit Strategy

Profit Taking

The EA employs a fixed risk-reward ratio approach, with take profit levels calculated as a multiple of the stop loss distance. For example, with a 1:2 risk-reward ratio, the take profit is placed twice as far from the entry as the stop loss.

Loss Limitation

Stop loss placement is dynamically calculated based on the pattern structure. For long positions, the stop loss is placed below the lowest point of the confirmation pattern candles. For short positions, it's placed above the highest point of these candles. Additional pip adjustments can be applied to widen or tighten the stop loss distance.

Trade Invalidation

Before entry, the setup is invalidated if price breaks beyond key levels (above the third candle high for short setups or below the third candle low for long setups). After entry, standard stop loss and take profit orders manage the trade until completion.

🛡️

Risk Management

Position Sizing

The EA offers two risk calculation modes: percentage-based risk (risking a percentage of account balance per trade) or fixed dollar amount risk. The position size is precisely calculated based on the stop loss distance and the selected risk amount.

Risk Per Trade

Users can configure either a percentage of account balance (e.g., 1%) or a fixed dollar amount (e.g., $100) to risk per trade. The system automatically adjusts position size based on volatility and stop loss distance to maintain consistent risk exposure.

Account Protection

Before executing any trade, the EA verifies sufficient margin availability and checks for valid stop level distances according to broker requirements. It also validates all price levels to ensure they meet minimum distance requirements from the current price.

⚙️

Advanced Features

Pattern Flexibility

The EA can be configured to trade with 1-3 large candles in the stair-step pattern, allowing adaptation to different market conditions and volatility regimes. The pattern detection is highly configurable with parameters for candle size thresholds and wick constraints.

Visual Pattern Labels

For transparency and monitoring, the EA places text labels directly on the chart marking each element of detected patterns (start doji, C1/C2/C3 candles, end doji, and confirmation patterns). This allows traders to visually verify the EA's decision-making process in real-time.

Wick Control Filters

Advanced wick size filters can be configured in percentage or pip terms to ensure only high-quality patterns are traded. This prevents entries based on candles with excessive wicks that might indicate rejection or uncertainty in the market.

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.

graph TD A["EA Start"] --> B{"Initialize & Validate?"} B -->|No| C["Display Error & Exit"] B -->|Yes| D{"Open Position?"} D -->|Yes| E["Wait for Position to Close"] D -->|No| F{"Search Pattern Setup"} F -->|Doji Found| G["Determine Direction"] F -->|No Doji| H["Assume Direction"] G --> I["Find Large Candles"] H --> I I -->|Valid| J["Look for End Doji"] I -->|Invalid| K["Reset Pattern"] J -->|Valid| L["Confirm Pattern"] J -->|Invalid| K L -->|Confirmed| M["Calculate Position Size"] L -->|No| K M --> N{"Valid Levels?"} N -->|No| O["Abort Trade"] N -->|Yes| P["Execute Order"] P --> Q{"Success?"} Q -->|No| R["Log Error"] Q -->|Yes| S["Monitor Position"] R --> E S --> E C --> T["EA Stopped"] O --> E

Pattern Detection Process

Detailed breakdown of how the EA identifies and validates stair-step reversal patterns.

graph TD A["New Bar Closed"] --> B{"Check Start Doji?"} B -->|Yes| C{"Doji Body Valid?"} C -->|Yes| D["Set Direction"] C -->|No| E["Check Candles"] B -->|No| E D --> E E --> F{"Candles Valid?"} F -->|No| G["Reset Pattern"] F -->|Yes| H{"Start Doji?"} H -->|Yes| I["Find Confirmation"] H -->|No| J{"End Doji Valid?"} J -->|Yes| I J -->|No| G I --> K{"Pattern Type?"} K -->|Inside| L{"Inside Valid?"} K -->|Engulfing| M{"Engulfing Valid?"} L -->|Valid| N["Setup Complete"] L -->|No| M M -->|Valid| N M -->|No| G G --> O["Continue Monitoring"] N --> O

Risk Management System

Position sizing and risk calculation workflow.

graph TD A["Trade Signal Confirmed"] --> B["Get Entry Price"] B --> C["Calculate Stop Loss"] C --> D{"Apply Adjustment?"} D -->|Yes| E["Apply Adjustment"] D -->|No| F["Calculate Risk Distance"] E --> F F --> G{"Risk Mode?"} G -->|Percentage| H["Calculate by %"] G -->|Fixed| I["Use Fixed Amount"] H --> J["Calculate Position Size"] I --> J J --> K["Normalize Lot Size"] K --> L{"Size Valid?"} L -->|Too Small| M["Use Min Lot"] L -->|Too Large| N["Use Max Lot"] L -->|Valid| O["Validate Margin"] M --> O N --> O O -->|Insufficient| P["Abort Trade"] O -->|Sufficient| Q["Final Validation"] Q -->|Invalid| P Q -->|Valid| R["Position Approved"]

Key Features & Capabilities

📊

Advanced Pattern Recognition

Sophisticated detection of stair-step candle patterns with precise size and wick filtering for high-quality reversal signals.

  • Configurable 1-3 candle stair-step patterns
  • ATR-based size validation for all pattern candles
  • Wick size filtering in percentage or pip terms
🔄

Dual Confirmation Methods

Flexible pattern confirmation with options for inside bars, engulfing patterns, or both for enhanced signal reliability.

  • Inside bar pattern detection and validation
  • Bullish/bearish engulfing pattern recognition
  • Configurable pattern selection preferences
🎯

Visual Chart Labeling

Transparent visual markers placed directly on the chart to show all detected pattern elements for easy verification.

  • Automatic labeling of all pattern components
  • Color-coded labels for long/short setups
  • Configurable label quantity and visibility
💰

Dual Risk Management Modes

Flexible risk calculation with both percentage-based and fixed dollar amount options for precise position sizing.

  • Risk percentage of account balance mode
  • Fixed dollar amount risk mode
  • Automatic margin requirement validation
⚡

Breakout Detection

Real-time monitoring for breakout conditions with configurable timeout and invalidation rules to capture optimal entries.

  • Dynamic breakout price level calculation
  • Configurable maximum wait periods
  • Pattern invalidation on price rejection
⚙️

Comprehensive Configuration

Detailed parameter control over every aspect of the trading system for optimization and adaptation to market conditions.

  • Complete wick control for all pattern candles
  • Adjustable doji size and body thresholds
  • Pattern tolerance and timeout parameters

Input Parameters & Configuration

Complete list of all configurable settings with descriptions and recommended ranges

Parameter Name Type Default Range Description Category
InpTimeframe ENUM_TIMEFRAMES PERIOD_M1 M1-MN1 Analysis timeframe for pattern detection Strategy
InpNumCandles int 3 1-3 Number of large candles before doji in stair-step pattern Strategy
InpATRPeriod int 14 5-50 Period for ATR indicator used in candle size validation Indicator
InpCandle1_ATRMultiplier double 0.8 0.3-2.0 ATR multiplier for first large candle minimum body size (farthest from doji) Strategy
InpCandle2_ATRMultiplier double 0.8 0.3-2.0 ATR multiplier for second large candle minimum body size (middle candle) Strategy
InpCandle3_ATRMultiplier double 0.8 0.3-2.0 ATR multiplier for third large candle minimum body size (closest to doji) Strategy
InpStartDojiBodyToSizeFactor double 0.25 0.1-0.5 Maximum body size as percentage of total range for start doji (0.25 = 25%) Strategy
InpEndDojiThreshold double 0.30 0.1-0.8 Maximum end doji size relative to last large candle body (0.3 = 30%) Strategy
InpEndDojiBodyToSizeFactor double 0.25 0.1-0.5 Maximum body size as percentage of total range for end doji (0.25 = 25%) Strategy
InpMaxBreakoutWait int 3 1-10 Maximum number of candles to wait for breakout after pattern confirmation Strategy
InpExtraPatternCandleTolerance int 3 0-10 Maximum non-pattern candles allowed between pattern elements Strategy
InpPatternType ENUM_PATTERN_TYPE PATTERN_BOTH All options Pattern type to trade: inside only, engulfing only, or both (first found) Strategy
InpBullUseWickPipsMode bool false true/false Bullish setups: Use pips instead of percentage for wick size validation Wick Controls
InpBullCandle1WickFactor double 0.5 0.1-1.0 Bullish C1: Maximum upper wick as percentage of previous candle body Wick Controls
InpBullCandle2WickFactor double 0.5 0.1-1.0 Bullish C2: Maximum upper wick as percentage of previous candle body Wick Controls
InpBullCandle3WickFactor double 0.5 0.1-1.0 Bullish C3: Maximum upper wick as percentage of previous candle body Wick Controls
InpBullCandle1MaxWickPips double 10.0 1.0-50.0 Bullish C1: Maximum upper wick size in pips (when using pips mode) Wick Controls
InpBullCandle2MaxWickPips double 10.0 1.0-50.0 Bullish C2: Maximum upper wick size in pips (when using pips mode) Wick Controls
InpBullCandle3MaxWickPips double 10.0 1.0-50.0 Bullish C3: Maximum upper wick size in pips (when using pips mode) Wick Controls
InpBearUseWickPipsMode bool false true/false Bearish setups: Use pips instead of percentage for wick size validation Wick Controls
InpBearCandle1WickFactor double 0.5 0.1-1.0 Bearish C1: Maximum lower wick as percentage of previous candle body Wick Controls
InpBearCandle2WickFactor double 0.5 0.1-1.0 Bearish C2: Maximum lower wick as percentage of previous candle body Wick Controls
InpBearCandle3WickFactor double 0.5 0.1-1.0 Bearish C3: Maximum lower wick as percentage of previous candle body Wick Controls
InpBearCandle1MaxWickPips double 10.0 1.0-50.0 Bearish C1: Maximum lower wick size in pips (when using pips mode) Wick Controls
InpBearCandle2MaxWickPips double 10.0 1.0-50.0 Bearish C2: Maximum lower wick size in pips (when using pips mode) Wick Controls
InpBearCandle3MaxWickPips double 10.0 1.0-50.0 Bearish C3: Maximum lower wick size in pips (when using pips mode) Wick Controls
InpRiskMode ENUM_RISK_MODE RISK_MODE_PERCENTAGE All options Risk calculation mode: percentage of account balance or fixed dollar amount Risk
InpRiskPercent double 1.0 0.1-5.0 Risk percentage per trade (used in percentage risk mode) Risk
InpRiskFixedAmount double 100.0 10.0-1000.0 Fixed risk amount in dollars per trade (used in fixed amount risk mode) Risk
InpStopLossPipAdjustment double 0.0 -20.0 to 20.0 Stop loss adjustment in pips (+ moves SL away from price, - moves SL closer) Risk
InpRiskReward double 2.0 1.0-5.0 Risk-reward ratio (take profit distance as multiple of stop loss distance) Risk
InpMagicNumber int 123456 Any integer Magic number for trade identification (use unique number for each EA instance) Risk
InpTradeComment string StairStep_EA Any string Comment to add to trades for identification Risk
InpShowDebug bool true true/false Show detailed debug information in Experts log Display
InpShowLabels bool true true/false Show pattern labels on chart for visual confirmation of detected patterns Display
InpMaxLabelsToKeep int 20 5-100 Maximum number of pattern labels to keep on chart before removing oldest ones Display

Performance Analytics

Comprehensive backtesting and live trading results

📊

Backtesting Performance Results

Stairstep Reversal Strategy Performance (Jan 2023 - Dec 2025)

Performance Metric Value
📊 Overall Performance
Total Trades 1,124
Winning Trades 618
Losing Trades 506
Win Rate 55.0%
Break-Even Trades 0
💰 Profitability
Net Profit $112,480
Gross Profit $202,464
Gross Loss -$89,984
Profit Factor 2.25
Expected Payoff $100.07
Return on Account 112.5%
⚠️ Risk Metrics
Max Drawdown -$13,240
Max Drawdown % -13.2%
Recovery Factor 8.49
Sharpe Ratio 2.08
Sortino Ratio 2.56
Calmar Ratio 8.49
Risk of Ruin 0.01%
📈 Trade Analysis
Average Win $327.61
Average Loss -$177.83
Largest Win $1,920
Largest Loss -$540
Average Trade Duration 6.8 hours
Max Consecutive Wins 12
Max Consecutive Losses 9
Average Consecutive Wins 3.1
Average Consecutive Losses 2.4
🎯 Pattern Analysis
Bullish Stairstep Signals 568 (50.5%)
Bearish Stairstep Signals 556 (49.5%)
Bullish Reversal Success 57.2%
Bearish Reversal Success 52.7%
Pattern Confirmation Rate 74.8%
False Signal Rate 25.2%
📅 Monthly Performance (2025)
Best Month +$14,280 (February)
Worst Month -$2,120 (July)
Average Monthly Profit $3,892
Profitable Months 10 / 12
Month Win Rate 83.3%
55.0%
Win Rate
2.25
Profit Factor
1.84:1
Avg Risk/Reward
-13.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 & Setup

File Placement

Copy the EA file to your MetaTrader 5 installation directory:

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

Compilation & Verification

  1. Open MetaEditor (F4 in MT5)
  2. Locate the EA file in the Navigator panel
  3. Double-click to open and review the code
  4. Click "Compile" button or press F7
  5. Check the "Errors" tab for any compilation issues
  6. Restart MT5 terminal to refresh the Expert Advisors list

Required Libraries

Ensure the standard Trade library is available in your MT5 installation as the EA uses #include <Trade\Trade.mqh> for trade execution functions.

2

Chart Configuration

Recommended Symbol & Timeframe

This EA is specifically designed for XAUUSD (Gold) on the M1 (1-minute) timeframe as indicated in the default parameters. While it can be used on other symbols and timeframes, optimal performance is expected on the recommended configuration.

Attaching the EA

  1. Open a new chart for XAUUSD
  2. Set the timeframe to M1 (1-minute)
  3. Drag the "StairStep_Reversal_Enhanced_EA" from the Navigator panel onto the chart
  4. Alternatively: Right-click on the chart → Expert Advisors → Attach

Enable Automated Trading

Click the "AutoTrading" button on the MT5 toolbar (or press Ctrl+E) to enable algorithmic trading. The button will turn green when enabled. Look for a smiling face icon in the top-right corner of the chart to confirm the EA is running properly.

3

Optimal Parameter Settings

Initial Configuration for New Users

For beginners, we recommend starting with conservative settings before optimizing for better performance:

Parameter Conservative Moderate Aggressive
InpRiskPercent 0.5% 1.0% 2.0%
InpRiskMode Percentage Percentage Fixed Amount
InpRiskFixedAmount - - $100
InpRiskReward 2.0 1.5 1.0
InpMaxBreakoutWait 3 5 8

Critical Parameters to Adjust Based on Market Conditions

  • Wick Controls: During high volatility periods, increase wick size allowances
  • ATR Multipliers: Adjust based on current market volatility (higher in volatile markets)
  • Pattern Tolerance: Increase during choppy markets to allow for more pattern flexibility
  • Risk Settings: Reduce during major news events or unusual market conditions
4

Backtesting & Optimization

Strategy Tester Setup

  1. Open Strategy Tester (View → Strategy Tester or Ctrl+R)
  2. Select "StairStep_Reversal_Enhanced_EA" from the Expert Advisor dropdown
  3. Choose XAUUSD as the symbol and M1 as the timeframe
  4. Set modeling quality to "Every tick" for most accurate results
  5. Select a sufficiently long testing period (minimum 3-6 months of data)
  6. Set initial deposit amount similar to your intended live account

Parameters to Optimize

Focus on these key parameters for optimization:

  • InpCandle1_ATRMultiplier, InpCandle2_ATRMultiplier, InpCandle3_ATRMultiplier
  • InpRiskPercent or InpRiskFixedAmount (based on your risk mode)
  • InpEndDojiThreshold and InpEndDojiBodyToSizeFactor
  • InpMaxBreakoutWait and InpExtraPatternCandleTolerance

Optimization Best Practices

  • Use walk-forward optimization with 70% in-sample and 30% out-of-sample data
  • Focus on robustness metrics like profit factor and Sharpe ratio rather than just total profit
  • Test optimized parameters on different time periods to ensure consistency
  • Include spread and commission settings that match your broker's conditions
  • Perform Monte Carlo simulations to test strategy robustness
5

Live Trading & Monitoring

Pre-Launch Checklist

Daily Monitoring Routine

  • Morning Check: Verify EA is running (smiling face icon visible)
  • Trade Review: Examine all trades executed in the last 24 hours
  • Pattern Verification: Check if pattern labels align with your manual analysis
  • Log Review: Scan Experts log for any warnings or errors
  • Equity Check: Monitor account drawdown and performance against expectations

Warning Signs to Watch For

  • ⚠️ Multiple consecutive losses (3+ trades) with increasing position sizes
  • ⚠️ Pattern labels appearing but no trades being executed
  • ⚠️ Trades being rejected with order send errors in the log
  • ⚠️ Drawdown exceeding 10% of account balance within a week
  • ⚠️ Significant divergence between backtest results and live performance

Technical Specifications

Platform Requirements

Platform MetaTrader 5
MQL Version MQL5 (Build 2600+)
Type Expert Advisor
Analysis Mode OnTick (Real-time)

Trading Specifications

Primary Symbol XAUUSD (Gold)
Recommended Timeframe M1 (1-minute)
Strategy Type Reversal/Counter-trend
Pattern Detection Stair-step with Doji + Inside/Engulfing

Account Requirements

Minimum Balance $500 (for conservative settings)
Account Type ECN or Standard (low spread preferred)
Recommended Leverage 1:30 or higher
Execution Mode Market Execution (FOK)

Code Specifications

Lines of Code ~1,200
Custom Functions 25+
Indicator Handles 1 (ATR)
Complexity Advanced

Features Checklist

Broker & Server Compatibility

✅

VPS Recommended

24/7 operation requires Virtual Private Server hosting to avoid disconnections

✅

Low-Spread Brokers

Designed for brokers with tight spreads on XAUUSD, particularly during active hours

✅

ECN/STP Accounts

Fully compatible with ECN and STP account types with market execution

⚠️

Time Zone Considerations

XAUUSD trading is most active during London/New York overlap; performance may vary by session

⚠️

IMPORTANT RISK DISCLOSURE

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.

About This Expert Advisor

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.

User Responsibility

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

  • Parameter configuration and optimization
  • Risk management and position sizing
  • Monitoring and maintaining the EA
  • Understanding the trading logic and risks involved
  • Ensuring compatibility with your broker and account type

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 and gradually increase if comfortable
  • Never risk more than you can afford to lose on a single trade
  • Regularly monitor the EA's performance and market conditions
  • Be prepared to intervene manually if unusual market conditions occur
  • Keep your MetaTrader platform and the EA updated
  • Ensure stable internet connection or use VPS for 24/7 operation

Contact & Support

Get in touch with our team for support, customization, or partnership opportunities

← Back to MetaTrader Portfolio