MQL5 - Language of trade strategies built-in the MetaTrader 5 client terminal

Source code library - Expert Advisors, Indicators and Scripts

MetaTrader Market - the place where newest trading robots appear
To post a new code, please log in or register

Interesting script?
So post a link to it -
let others appraise it

You liked the script? Try it in the MetaTrader 5 terminal

2011.03.16 14:33
MQL5 Wizard - Trade Signals Based on Bullish Harami/Bearish Harami + Stochastic

MQL5 Wizard - Trade Signals Based on Bullish Harami/Bearish Harami + Stochastic - expert for MetaTrader 5

| English Russian Chinese Spanish Portuguese

Views:
1300
Rating:
votes: 6
Files:
\MQL5\Include\Expert\Signal\MySignals\

Description:

The MQL5 Wizard allows creating ready-made Expert Advisors based on the Standard library classes delivered together with the client terminal (see Creating Ready-Made Expert Advisors in MQL5 Wizard for the details). It allows to check your trade ideas quickly, all you need is to create your own trading signals class. The structure of this class and example can be found in the article MQL5 Wizard: How to Create a Module of Trading Signals.

The generic idea is the following: the class of trading signals is derived from CExpertSignal, the next, it's necessary to override the LongCondition() and ShortCondition() virtual methods with your own methods.

There is a book "Strategies of best traders" (in Russian), there are many trading strategies are considered there, we will focus on reversal candlestick patterns, confirmed by Stochastic, CCI, MFI and RSI oscillators.

The best way is to create the separate class, derived from CExpertSignal for checking of formation of candlestick patterns. For confirmation of trade signals, generated by candlestick patterns, it's sufficient to write the class, derived from CCandlePattern and add the necessary features (for example, confirmation by oscillators) there.

Here we will consider the signals, based "Bullish Harami/Bearish Harami" reversal candlestick pattern, confirmed by Stochastic indicator. The module of trade signals is based on the CCandlePattern class, it's simple example of its use for creation of trade signals with candlestick patterns.


1. "Bullish Harami and "Bearish Harami" reversal candlestick patterns

1.1. Bullish Harami

The Bullish Harami reversal pattern forms in downward trend when large candlestick is followed by a smaller candlestick whose body is located within the vertical range of the larger body. This pattern indicates that the falling trend (downtrend) may be reversing, it signals that it's a good time to enter into a long position. The second candlestick is opened with a gap up.

The smaller the second (white) candlestick, the more likely the reversal.

Fig. 1. "Bullish Harami" candlestick pattern

Fig. 1. "Bullish Harami" candlestick pattern

The recognition of "Bullish Harami" pattern is implemented in CheckPatternBullishHarami() method of CCandlePattern class:

//+------------------------------------------------------------------+
//| Checks formation of "Bullish Harami" candlestick pattern         |
//+------------------------------------------------------------------+
bool CCandlePattern::CheckPatternBullishHarami()
  {
//--- Bullish Harami
   if((Close(1)>Open(1))              && // the last completed bar is bullish (white day)
     ((Open(2)-Close(2))>AvgBody(1))  && // the previous candle is bearish, its body is greater than average (long black)
     ((Close(1)<Open(2))              && // close price of the bullish candle is lower than open price of the bearish candle 
      (Open(1)>Close(2)))             && // open price of the bullish candle is higher than close price of the bearish candle
      (MidPoint(2)<CloseAvg(2)))         // down trend
      return(true);
//---
   return(false);
  }

The CheckCandlestickPattern(CANDLE_PATTERN_BULLISH_HARAMI) method of CCandlePattern class is used to check formation of "Bullish Harami" candlestick pattern.


1.2. Bearish Harami

The Bearish Harami reversal pattern forms in upward trend when large candlestick is followed by a smaller candlestick whose body is located within the vertical range of the larger body. This pattern indicates that the rising trend (uptrend) may be reversing, it signals that it's a good time to enter into a short position. The second candlestick is opened with a gap down.

The smaller the second (black) candlestick, the more likely the reversal.

Fig. 2. "Bearish Harami" candlestick pattern

Fig. 2. "Bearish Harami" candlestick pattern

The recognition of "Bearish Harami" pattern is implemented in CheckPatternBearishHarami() method of CCandlePattern class:

//+------------------------------------------------------------------+
//| Checks formation of "Bearish Harami" candlestick pattern         |
//+------------------------------------------------------------------+
bool CCandlePattern::CheckPatternBearishHarami()
  {
//--- Bearish Harami
   if((Close(1)<Open(1))              && // last completed bar is bearish (black day)
     ((Close(2)-Open(2))>AvgBody(1))  && // the previous candle is bullish, its body is greater than average (long white)
     ((Close(1)>Open(2))              && // close price of the bearish candle is higher than open price of the bullish candle 
      (Open(1)<Close(2)))             && // open price of the bearish candle is lower than close price of the bullish candle
      (MidPoint(2)>CloseAvg(2)))         // up trend
      return(true);
//---
   return(false);
  }

The CheckCandlestickPattern(CANDLE_PATTERN_BEARISH_HARAMI) method of CCandlePattern class is used to check formation of "Bearish Harami" candlestick pattern.


2. Trade signals, confirmed by Stochastic indicator

The trading signals to open long or short position must be confirmed by Stochastic oscillator. The signal %D line must be greater/lower then corresponding critical level (30 or 70).

The closing of opened position depends on the values of %D indicator. It can be done in 2 cases:

  1. if %D line has reached the opposite critical level (80 for long position and 20 for short position)
  2. if the reverse signal isn't confirmed (when %D line reaches the following levels: 20 for long position and 80 for short position)

Fig. 3. "Bearish Harami" candlestick pattern, confirmed by Stochastic indicator

Figure 3. "Bearish Harami" candlestick pattern, confirmed by Stochastic indicator

Checking of trade conditions for entry and exit is implemented in two methods:

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

2.1. Open long position/Close short position

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

  2. The short position must be closed if the signal line of Stochastic indicator has crossed upward 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 CBH_BH_Stoch::LongCondition()
  {
   int result=0;
//--- idx can be used to determine Expert Advisor work mode
//--- idx=0 - in this case EA checks trade conditions at each tick
//--- idx=1 - in this case EA checks trade consition only at news bars
   int idx   =StartIndex();
//--- checking of conditions to open long position
//--- formation of Bullish Harami pattern and signal line<30
  if (CheckCandlestickPattern(CANDLE_PATTERN_BULLISH_HARAMI) && (StochSignal(1)<30))
     result=80;
//--- checking of 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. Open short position/Close long position

  1. The formation of "Bearish Harami" pattern must be confirmed by Stochastic indicator: StochSignal(1)>70 (the value of the signal line of Stochastic indicator of the last completed bar must be greater than 70).

  2. The long position must be closed if the signal line of Stochastic indicator has crossed downward 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 CBH_BH_Stoch::ShortCondition()
  {
   int result=0;
//--- idx can be used to determine Expert Advisor work mode
//--- idx=0 - in this case EA checks trade conditions at each tick
//--- idx=1 - in this case EA checks trade consition only at news bars
   int idx   =StartIndex();
//--- checking of conditions to open short position
//--- formation of Bearish Harami pattern and signal line>70
  if (CheckCandlestickPattern(CANDLE_PATTERN_BEARISH_HARAMI) && (StochSignal(1)>70))
     result=80;
//--- checking of 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 Expert Advisor using MQL5 Wizard

The CBH_BH_Stoch class isn't included in the Standard Library classes, to use it, it's necessary to download the acbh_bh_stoch.mqh file (see attachments) and save it to the client_terminal_data\folder\MQL5\Include\Expert\Signal\MySignals. The same should be done with the candlepatterns.mqh file. You can use it in MQL5 Wizard after restart of the MetaEditor.

To create an Expert Advisor launch MQL5 Wizard:

Fig. 4. Creating Expert Advisor using MQL5 Wizard

Fig. 4. Creating Expert Advisor using MQL5 Wizard

Let's specify the name of the Expert Advisor:

Fig. 5. General properties of the Expert Advisor

Fig. 5. General properties of the Expert Advisor

After that we need to select the modules of trade signals used.

Fig. 6. Signal properties of the Expert Advisor

Fig. 6. Signal properties of the Expert Advisor

In our case we use only one module of trade signals.

Adding the "Signals based on Bullish Harami/Bearish Harami 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, but we will use "Trailing Stop not used":

Fig. 9. Trailing properties of the Expert Advisor

Fig. 9. Trailing properties of the Expert Advisor

Concerning the 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 pressing the "Finish" button, we will get the code of the generated Expert Advisor, located in Expert_ABH_BH_Stoch.mq5, it will be saved in 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 to:

//--- 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 to specify threshold levels for open and close of positions.

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

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

The Expert Advisor, generated by MQL5 Wizard open and close position using the "votes" from the modules of trade signals. The vote of the main module (as container, it consist of all the modules added) is also used, but its LongCondition() and ShortCondition() methods always return 0.

The vote results of the main module is also used in "votes" averaging. In our case we have:  main module + 1 module of trade signals, so we need to take this fact into account when setting of the threshold values. Because of this fact the ThresholdOpen and ThresholdClose must be set as 40=(0+80)/2 and 20=(0+40)/2.

The values of  Signal_StopLevel and Signal_TakeLevel input parameters is set to 0, it means that closing of the positions will be done only when closing conditions will be true.


2.4. History backtesting results

Let's consider 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 creation of Expert Advisor we used the fixed volume (Trading Fixed Lot, 0.1), Trailing Stop algorithm is not used (Trailing not used).

Fig. 11. Testing results of the Expert Advisor, based on &quotBullish/Bearish Harami + Stochastic"

Fig. 11. Testing results of the Expert Advisor, based on &quotBullish/Bearish Harami + Stochastic"


The best set of input parameters can be found using the Strategy Tester of MetaTrader 5 client terminal.

The code of the Expert Advisor, created by MQL5 Wizard is attached in expert_abh_bh_stoch.mq5.


Translated from Russian by MetaQuotes Software Corp.
Original code: http://www.mql5.com/ru/code/310

Last comments | Go to discussion (1)
Sergey Golubev
newdigital | 26 Nov 2013 at 21:37

Trade the Harami Candlestick Pattern (based on dailyfx article)

Talking Points

  • Candlestick analysis can be worked into any active Forex trading strategy.
  • The Harami pattern can lead to trend changes and potential breakouts
  • Traders can look for profit taking or retracement trading opportunities

Once traders understand the basics, they can then begin to compile a series of candles to form patterns to confirm potential changes and market direction. One of the most used candle patterns is known as the Harami. Today we will review the Harami pattern and how it can be implemented into your trading strategy.


The Harami Candle Pattern

The Harami candle pattern may be new to some but for many it may already be known as a derivation of an “Inside Bar”. Pictured above we can see a traditional Harami which can be defined by a few distinct characteristics. First the Harami is comprised of two candles. The first candle shoulddepicta large bullish candle such as a bullish engulfing candle. This blue candle is then followed up by a second smaller candle. The key to identifying a Harami is to have this second candle not close outside of the previous candles body. To add validity to the pattern, the second candle should close above half the traded value of the first candles body.

A bearish Harami will show a bull market stopping dead in its tracks as in the example below. However, these patterns can be considered weak, because even if the pair pulls back after a Harami it does not necessarily dictate a full market reversal. Because of this, the pattern often incorporates a third candle for confirmation, creating a Three Inside Down pattern.

Let’s look at a current example.


Uses in Trading

Above we can see a Bearish Harami in action on the EURCAD currency pair. The daily graph has been in a long standing established uptrend, but prices have a tendency to retrace along the way. This last retracement was started with the formation of a Harami. With its creation, the market put in its current high then quickly descended 556 pips to for a higher low on the chart.

Traders looking to take advantage of the Bearish Harami pattern can add it into any existing trending market plan. Traders can look to take profits on any existing long trades, or even consider trading a full out reversal once this pattern appears. Regardless of your trading plan, when adding new components to your strategy you should be tracking your results with a trade journal. This way over time you can gauge the effectiveness of price action and candle analysis in your trading.