Home System Trading Post

Creating a Stochastic-Based EA for Hammer and Hanging Man Patterns in MetaTrader 5

Attachments
314.zip (6.58 KB, Download 2 times)

Are you looking to enhance your trading strategy with some powerful candlestick patterns? The MQL5 Wizard is a fantastic tool that lets you create Expert Advisors (EAs) using the built-in classes available in the MetaTrader 5 client terminal. It allows you to quickly test your trading ideas by creating your own trading signals class. For more on this, check out the article on MQL5 Wizard: How to Create a Module of Trading Signals.

The concept is straightforward: your trading signals class will be based on CExpertSignal. You’ll need to override the LongCondition() and ShortCondition() methods with your own logic.

In the book "Strategies of Best Traders" (in Russian), various trading strategies are discussed, and we will focus on reversal candlestick patterns, particularly the Hammer and Hanging Man patterns, confirmed by the Stochastic, CCI, MFI, and RSI oscillators.

A great approach is to create a separate class derived from CExpertSignal to check for candlestick pattern formations. To confirm the trading signals generated by these patterns, simply write a class derived from CCandlePattern and add the necessary features, such as confirmation from oscillators.

In this post, we’ll focus on signals based on the "Hammer" and "Hanging Man" reversal candlestick patterns, verified by the Stochastic indicator. The module for trading signals relies on the CCandlePattern class, which provides a straightforward example for creating trade signals using candlestick patterns.

1. Understanding the "Hammer" and "Hanging Man" Patterns

1.1. Hammer Pattern

The "Hammer" is a candlestick with a small body and a long lower wick, which forms after a downward price move. This pattern signals the potential end of a bearish trend.

The color of the candlestick body isn't crucial, but a bullish hammer suggests stronger bullish potential. Typically, the body of the Hammer pattern forms near the low of the previous candle. A longer lower wick and a shorter upper wick indicate a higher likelihood of a reversal.

Fig. 1. Hammer candlestick pattern

Fig. 1. Hammer candlestick pattern

The recognition of the Hammer pattern is implemented in the CheckPatternHammer() method of the CCandlePattern class:

//+------------------------------------------------------------------+
//| Checks formation of "Hammer" candlestick pattern |
//+------------------------------------------------------------------+
bool CCandlePattern::CheckPatternHammer()
  {
//--- Hammer
   if((MidPoint(1)<CloseAvg(2)) 
                                 && // down trend
      (MathMin(Open(1),Close(1)>(High(1)-(High(1)-Low(1))/3.0)) && // body in upper 1/3
      (Close(1)<Close(2)) && (Open(1)<Open(2))) 
      return(true);
//---
   return(false);
  }

The CheckCandlestickPattern(CANDLE_PATTERN_HAMMER) method of CCandlePattern class is used to check the formation of the "Hammer" candlestick pattern.

1.2. Hanging Man Pattern

The "Hanging Man" is similar to the Hammer but forms after an upward price move. This pattern signifies the potential end of a bullish trend.

Again, the color of the body isn't key, but a bearish candle indicates greater bearish potential. The Hanging Man's body typically forms near the high of the previous candle. A longer lower wick and shorter upper wick signify a higher chance of a reversal.

Fig. 2. Hanging Man candlestick pattern

Fig. 2. Hanging Man candlestick pattern

The recognition of the Hanging Man pattern is implemented in the CheckPatternHangingMan() method of the CCandlePattern class:

//+------------------------------------------------------------------+

//| Checks formation of "Hanging Man" candlestick pattern |
//+------------------------------------------------------------------+
bool CCandlePattern::CheckPatternHangingMan()
  {
//--- Hanging man
   if((MidPoint(1)>CloseAvg(2)) 
                                && // up trend
      (MathMin(Open(1),Close(1)>(High(1)-(High(1)-Low(1))/3.0)) && // body in upper 1/3
      (Close(1)>Close(2)) && (Open(1)>Open(2))) 
      return(true);
//---
   return(false);
  }

The CheckCandlestickPattern(CANDLE_PATTERN_HANGING_MAN) method of CCandlePattern class is used to check the formation of the "Hanging Man" candlestick pattern.

2. Trading Signals Confirmed by the Stochastic Indicator

To open long or short positions, the trading signals must be confirmed by the Stochastic oscillator. The %D line should be above or below the critical levels (30 or 70).

Closing an open position depends on the values of the %D indicator, which can occur in two scenarios:

  • When the %D line reaches the opposite critical level (80 for long positions and 20 for short positions).
  • If the reversal signal isn't confirmed (when the %D line reaches levels of 20 for long positions and 80 for short positions).

Fig. 3. Hammer pattern confirmed by Stochastic indicator

Fig. 3. Hammer pattern confirmed by Stochastic indicator

  • int CH_HM_Stoch::LongCondition() - checks conditions to open a long position (returns 80) and close a short position (returns 40);
  • int CH_HM_Stoch::ShortCondition() - checks conditions to open a short position (returns 80) and close a long position (returns 40).

2.1. Opening a Long Position / Closing a Short Position

  1. The formation of the "Hammer" pattern must be confirmed by the Stochastic indicator: StochSignal(1) < 30 (the signal line of the Stochastic indicator for the last completed bar must be less than 30).

  2. The short position should be closed if the Stochastic signal line crosses upward through the 20 or 80 levels.

//+------------------------------------------------------------------+
//| Checks conditions for entry and exit from market |
//| 1) Market entry (open long position, result=80) |
//| 2) Market exit (close short position, result=40) |
//+------------------------------------------------------------------+
int CH_HM_Stoch::LongCondition()
  {
   int result=0;
   //--- idx can be used to determine EA work mode
   //--- idx=0 - checks trade conditions at each tick
   //--- idx=1 - checks trade conditions only at news bars
  int idx   =StartIndex();
   //--- checking conditions to open long position
   //--- formation of Hammer pattern and signal line<30
  if (CheckCandlestickPattern(CANDLE_PATTERN_HAMMER) && (StochSignal(1)<30))
     result=80;
   //--- checking conditions to close short position
   //--- signal line crossover of overbought/oversold levels (downward 20, upward 80)
   if((((StochSignal(1)>20) && (StochSignal(2)<20)) ||
       ((StochSignal(1)>80) && (StochSignal(2)<80))))
     result=40;
   //--- return result
   return(result);
  }

2.2. Opening a Short Position / Closing a Long Position

  1. The formation of the "Hanging Man" pattern must be confirmed by the Stochastic indicator: StochSignal(1) > 70 (the signal line of the Stochastic indicator for the last completed bar must be more than 70).

  2. The long position should be closed if the Stochastic signal line crosses downward through the 80 or 20 levels.

//+------------------------------------------------------------------+
//| Checks conditions for entry and exit from market |
//| 1) Market entry (open short position, result=80) |
//| 2) Market exit (close long position, result=40) |
//+------------------------------------------------------------------+
int CH_HM_Stoch::ShortCondition()
  {
   int result=0;
   //--- idx can be used to determine EA work mode
   //--- idx=0 - checks trade conditions at each tick
   //--- idx=1 - checks trade conditions only at news bars
  int idx   =StartIndex();
   //--- checking conditions to open short position
   //--- formation of Hanging Man pattern and signal line>70
  if (CheckCandlestickPattern(CANDLE_PATTERN_HANGING_MAN) && (StochSignal(1)>70))
     result=80;
   //--- checking conditions to close long position
   //--- signal line crossover of overbought/oversold levels (downward 80, upward 20)
   if((((StochSignal(1)<80) && (StochSignal(2)>80)) ||
       ((StochSignal(1)<20) && (StochSignal(2)>20))))
     result=40;
   //--- return result
   return(result);
  }

2.3. Creating Your EA Using MQL5 Wizard

The CH_HM_Stoch class isn’t part of the Standard Library classes. To use it, download the ach_hm_stoch.mqh file (see attachments) and save it in your client_terminal_data\folder\MQL5\Include\Expert\Signal\MySignals. Do the same with the candlepatterns.mqh file. Once saved, you can use it in MQL5 Wizard after restarting the MetaEditor.

To create your EA, launch the MQL5 Wizard:

Fig. 4. Creating Expert Advisor using MQL5 Wizard

Fig. 4. Creating Expert Advisor using MQL5 Wizard

Name your Expert Advisor:

Fig. 5. General properties of the Expert Advisor

Fig. 5. General properties of the Expert Advisor

Next, select the modules of trade signals to be used.

Fig. 6. Signal properties of the Expert Advisor

Fig. 6. Signal properties of the Expert Advisor

In this case, we will use only one module of trade signals.

Add the "Signals based on Hammer/Hanging Man confirmed by Stochastic" module of trading signals:

Fig. 7. Signal properties of the Expert Advisor

Fig. 7. Signal properties of the Expert Advisor

Module of trade signals added:

Fig. 8. Signal properties of the Expert Advisor

Fig. 8. Signal properties of the Expert Advisor

You can select any trailing properties; however, we will use "Trailing Stop not used":

Fig. 9. Trailing properties of the Expert Advisor

Fig. 9. Trailing properties of the Expert Advisor

Regarding money management properties, we will use "Trading with fixed trade volume":

Fig. 10. Money management properties of the Expert Advisor

Fig. 10. Money management properties of the Expert Advisor

By clicking the "Finish" button, you will receive the code of the generated Expert Advisor, saved as Expert_AH_HM_Stoch.mq5 in the terminal_data_folder\MQL5\Experts.

The default input parameters of the generated Expert Advisor:

//--- inputs for main signal
input int            Signal_ThresholdOpen   =10;     // Signal threshold value to open [0...100]
input int            Signal_ThresholdClose  =10;     // Signal threshold value to close [0...100]
input double         Signal_PriceLevel      =0.0;    // Price level to execute a deal
input double         Signal_StopLevel       =50.0   // Stop Loss level (in points)
input double         Signal_TakeLevel       =50.0    // Take Profit level (in points)

must be replaced with:

//--- inputs for main signal
input int            Signal_ThresholdOpen   =40;     // Signal threshold value to open [0...100]
input int            Signal_ThresholdClose  =20;     // Signal threshold value to close [0...100]
input double         Signal_PriceLevel      =0.0    // Price level to execute a deal
input double         Signal_StopLevel       =0.0    // Stop Loss level (in points)
input double         Signal_TakeLevel       =0.0    // Take Profit level (in points)

The Signal_ThresholdOpen/Signal_ThresholdClose input parameters allow you to set threshold levels for opening and closing positions.

In the code of the LongCondition() and ShortCondition() methods of the trade signals class, we specified fixed values for the threshold:

  • Open position: 80;
  • Close position: 40.

The Expert Advisor generated by MQL5 Wizard opens and closes positions using the "votes" from the trade signal modules. The vote from the main module (which acts as a container for all added modules) is also used, but its LongCondition() and ShortCondition() methods always return 0.

The results from the main module are also considered in averaging the votes. In this case, we have one main module plus one module of trade signals, so we need to account for this when setting the threshold values. Hence, the ThresholdOpen and ThresholdClose must be set to 40=(0+80)/2 and 20=(0+40)/2.

The values of the Signal_StopLevel and Signal_TakeLevel input parameters are set to 0, which means closing positions will only occur when closing conditions are met.


2.4. History Backtesting Results

Let’s examine the backtesting of the Expert Advisor on historical data (EURUSD H1, testing period: 2010.01.01-2011.03.04, PeriodK=47, PeriodD=9, PeriodSlow=13, MA_period=5).

In the creation of the Expert Advisor, we used a fixed volume (Trading Fixed Lot, 0.1), and the Trailing Stop algorithm is not used (Trailing not used).

Fig. 11. Testing results of the Expert Advisor, based on Hammer/Hanging Man + Stochastic

Fig. 11. Testing results of the Expert Advisor, based on Hammer/Hanging Man + Stochastic


To find the best set of input parameters, utilize the Strategy Tester in the MetaTrader 5 client terminal.

The code of the Expert Advisor created by MQL5 Wizard is attached as expert_ah_hm_stoch.mq5.

Related Posts

Comments (0)