Fuzzy Hammer Candlestick Pattern MQL5 Indicator

Candlestick patterns are imprecise and vague. So are most of the indicators like MACD, RSI and Stochastic that give a lot of false signals. Moving averages are of no help as they always lag behind price action. What to do then? This is the dilemma that faces every trader how to find the buy/sell signal by using candlestick patterns in combination with oscillators like MACD or RSI. In this post I will discuss in detail how we can use MQL5 Fuzzy Logic Library in developing EAs and Indicators. MQL5 Fuzzy Logic Library is a great tool that many traders are simply unaware of. Watch this documentary on the day in the life of a currency trader.

You see in conventional logic systems we only talk of TRUE or FALSE. But we know from our real life experiences most of the things that we encounter in our lives are shades of grey. There is no clear cut black or white answer. In the forex trading, most of the time we are dealing with shades of grey. There is no system that is 100% accurate. When we open a trade we are not sure whether it will work or not. Most of the trade setups that we think are high probability that some element of uncertainty in it. When the market is ranging we are not sure when it will start trending. We try to guess by looking at different indicators like MACD, RSI, Stochastics etc. Sometimes our guess comes out to be true but other times you have a very good trade setup but the trade fails when price hits stop loss. Did you read the post on how to make 200 pips with 20 pip stop loss?

In this post I am going to discuss in detail how we can model uncertainty in the trade setup. When we talk of uncertainty we think of probabilities. Probability is one method of quantifying uncertainty. Fuzzy logic is another method. Fuzzy logic takes a totally different approach to quantify uncertainty. So we have two very different approaches to quantify uncertainty. Fuzzy logic is being successfully used in industrial applications. Japan was the first country to apply fuzzy logic in industry. Bullet trains in Japan are being controlled using fuzzy logic so are many other industrial applications. Still confused how ton use fuzzy logic in your trading? Read the Million Dollar Trading Challenge Plan.

Let’s start with a simple example. We are talking with each other about John. I say John is a tall. But tall is a subjective term that we can refine more into very tall, tall, medium, short and very short. So these using these adjectives we can refine our logic base. We can define a membership function that can classify an individual as a tall as well as medium. We can say John is 0.7 tall and 0.3 medium. So there is a fuzziness in John’s height that we can use in our modelling. Then we apply a rule base to our membership function database to draw inferences. Once we have the inferences we defuzziify them to get the predictions.

Fuzzy systems are used in modelling when we have uncertainty and we don’t have an exact formalization of the things that we are studying. Now like any model, fuzzy systems also depend a lot of the knowledge of the person who is using fuzzy logic to do the modelling. The same thing happens in computer programming. It is the man who writes the code that makes the difference. In the same manner, if you build a poor model than don’t expect it to give superior results. Watch this documentary on hedge fund trading strategies.

In simple terms this is how fuzzy logic works. In the first step we define the inputs and outputs of the system. Then we define the knowledge base. In the end we we need to select fuzzy inference method which can be Mamdani or Sugeno ( more on that later when we build the model). Now compare this with how traditional logic works. It always have crisp values of 0 and 1, 0 stands for false and 1 stands for true. So everything is either true or false. We all know this is not the case in real life. It can rain means maybe it will rain. We cannot say with 100% certainty that it will rain. We can use these adjectives, will, can, maybe, not sure to define a fuzzy membership function that we can then use to develop our fuzzy logic model for rain. You will need to go through a few examples to understand how fuzzy logic works.

Candlestick Patterns

Modelling Hammer and Inverted Hammer Candlestick Pattern Using MQL5 Fuzzy Logic Library

MQL5 now has a full fledged fuzzy logic library. This fuzzy logic library allows you to make two type of fuzzy systems namely the Mamdani and the Sugeno. Both can be used to create fuzzy systems. Best method of learn how to use this fuzzy logic library is to practically build a fuzzy system using it. I will use a simple candlestick pattern that is very important in trading namely the Hammer and the Inverted Hammer also known as the Shooting Star.

Candlestick patterns are vague and imprecise. One of the most important patterns is hammer and inverted hammer pattern. I use it a lot in my trading. When a hammer candlestick pattern appears in a downtrend, it is a signal for a potential trend change. In the same manner, when an inverted hammer candlestick pattern appears in an uptrend, it is a potential signal for a start of a downtrend. Of course, we cannot trade solely based on hammer candlestick pattern. We need to use one more indicator for confirmation. In the above figure you can see the hammer pattern that apears in a downtrend and the shooting star patter that appeas in an uptrend. Shooting star pattern is also known as an Inverted Hammer.  Let’s start coding a fuzzy hammer candlestick patterns indicator. First I give you the code then I explain the different blocks in the code.

//+------------------------------------------------------------------+
//|                                                  FuzzyHammer.mq5 |
//|                                                        Hassam    |
//|                                        http://www.doubledoji.com |
//+------------------------------------------------------------------+
#property copyright "Ahmad Hassam" //A
#property version "1.0"
#property strict
#property link "http://www.doubledoji.com/"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Red
#property indicator_plots   1

//--- input parameters
input int      NoOfBars=10;

//+------------------------------------------------------------------+
//| Connecting libraries                                             |
//+------------------------------------------------------------------+


#include <Math\Fuzzy\MamdaniFuzzySystem.mqh> //B

//--- indicator buffers
double         Buffer1[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,Buffer1,INDICATOR_DATA);
  
   
//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,        // C
                const int prev_calculated,
                const datetime &Time[],
                const double &Open[],
                const double &High[],
                const double &Low[],
                const double &Close[],
                const long &TickVolume[],
                const long &Volume[],
                const int &Spread[])
                
  {
  
  //---
   
   ArraySetAsSeries(Buffer1,true);
   ArraySetAsSeries(Open,true);
   ArraySetAsSeries(High,true);
   ArraySetAsSeries(Low,true);
   ArraySetAsSeries(Close,true);
  
 
   
   int bars = rates_total - 1;
   if(prev_calculated > 0) bars = rates_total - prev_calculated;
   
   for(int i = bars; i >= 0; i--)   // D
   {
   
      double      avgBody[];
      double      avgupperShadow[];
      double      avglowerShadow[];
   	for ( int k=1; k<=NoOfBars; k++) { 

// calculate the average size of the candle body 
double avgbody= MathAbs(Close[k] - Open[k]); avgBody[i] += avgbody; 

// calculate the average size of the upper shadow 
double avguppershadow; if (Close[k] > Open[k]) {
         avguppershadow= High[k]-Close[k];
     }
        else {
         avguppershadow=High[k] - Open[k];
         
      }
   	   avgupperShadow[i] += avguppershadow;
   	
   	
   	
   	// calculate the average size of the lower shadow
   	double avglowershadow;
         if (Close[k] > Open[k]) {
         avglowershadow= High[k]-Close[k];
     }
        else {
         avglowershadow=High[k] - Open[k];
         
      }
   	   avglowerShadow[i] += avglowershadow;
   	
   	}
   	
   	double fuzzyCandle= Candle(Open[i], High[i], Low[i], Close[i], //E
               avgupperShadow[i],avgBody[i], avglowerShadow[i]);
   	
   	Buffer1[i] = fuzzyCandle;
   	
   	if (Buffer1[i]==1.0) PlotIndexSetInteger(0,PLOT_ARROW,0,clrRed);
   	if (Buffer1[i]==0.0)  PlotIndexSetInteger(0,PLOT_ARROW,0,clrBlue);
   
   }
   
//--- return value of prev_calculated for next call
   return(rates_total);
  
  
  }

In the above code, first we have the preprocessor statements in A. These statements include the developer name and the plus the link to this website. After that we have the the #property chart window statement that tells the compiler that the indicator will be displayed in the price window instead of a separate window.

In B we have this statement #include <Math\Fuzzy\MamdaniFuzzySystem.mqh>. This statement tells the compiler to include the MamdaniFuzzySystem.mqh header file which is located in the include folder Math folder sub folder Fuzzy. With this statement the compiler immediately knows where to look for the MamdaniFuzzySystem.mqh file. Fuzzy is an MQL5 library which includes the following files: dictionary.mqh, fuzzyrules.mqh, fuzzyterm.mqh, fuzzyvariable.mqh,genericfuzzysystem.mqh, helper.mqh, inferencemethod.mqh, mamdanifuzzysystem.mqh, membershipfunction.mqh, ruleparser.mqh, sugenofuzzysystem.mqh and sugenovariable.mqh. It is always a good idea to take a look at these files and see what these files are supposed to do. If you are not familiar with fuzzy logic you should watch a few videos on youtube on fuzzy logic.

Under C you can find the OnCalculate() function which is must for an indicator. This indicator provides you with the Open, High, Low, Close and Spread arrays. Next we use ArraySetAsSeries() function for Open, High, Low and Close arrays so that we have a time series that we can use in our coding.

Candlestick Patterns

Now D is important. Here we define 3 variables that are the candlestick Upper Shadow, Body and Lower Shadow. In the figure above, you can see a bullish and a bearish candlestick with the real body, upper shadow and the lower shadow marked.This is what I have done. I calculate the average Upper Shadow, average Body and average Lower Shadow for the last 10 candles. This is done so that I have an average size of these variables so that I can use them in building fuzzy membership functions for that . Take a look at this function at E. I call it here in the main program. Let’s define this fuzzy candle function below!

  //--- Mamdani Candlestick Patterns Fuzzy System 
  //+----------------------------------------------------------------------------------------+
 //| Functions for creating calculating the Candlestick Patterns system based on fuzzy logic |
 //+-----------------------------------------------------------------------------------------+
 
 
    //---Create function to determine whether the candle is hammer or not
 
 double   Candle(double open, double high, double low, double close,
               double avgupperShadow, double avgBody, double avglowerShadow) //F
 
 {
 // create the return variable   // G
 double rr;
 // calculate the upper shadow of the candle
 double upperShadow;
 if ( close > open) {
         upperShadow= high-close;
     }
  else {
         upperShadow=high - open;
         
      }
 // calculate the body of the candle 
 double Body=MathAbs(close - open);
 
 //calculate the lower body of the candle
 double lowerShadow;
 if ( close > open) {
         lowerShadow = open - low;
     }
  else {
         lowerShadow =close - low;
         
      }
 // calculate the ceiling for upper shadow, lower shadow and the candle body     
   avgupperShadow = MathCeil(avgupperShadow);
   avgBody = MathCeil(avgBody);
   avglowerShadow = MathCeil(avglowerShadow);  //G
   
   
 // create the mumdani fuzzy system for the hammer candlestick pattern
 
 CMamdaniFuzzySystem *fsCandle=new CMamdaniFuzzySystem(); //H  
 
   
    //--- Create upper shadow input variables for the CandlestickPatterns system--I
 CFuzzyVariable *fvupperShadow=new CFuzzyVariable("upperShadow",0.0,avgupperShadow);
 fvupperShadow.Terms().Add(new CFuzzyTerm("Large", 
new CTriangularMembershipFunction(0.7*avgupperShadow, 0.9*avgupperShadow, avgupperShadow)));
 fvupperShadow.Terms().Add(new CFuzzyTerm("Medium", 
new CTriangularMembershipFunction(0.2*avgupperShadow, 0.5*avgupperShadow , 
0.8*avgupperShadow)));
 fvupperShadow.Terms().Add(new CFuzzyTerm("Small", 
new CTriangularMembershipFunction(0.0,0.15*avgupperShadow, 0.3*avgupperShadow)));
 fsCandle.Input().Add(fvupperShadow);
 
 //--- Create body input variables for the CandlestickPatterns system--J
 CFuzzyVariable *fvBody=new CFuzzyVariable("Body",0.0,avgBody);
 fvBody.Terms().Add(new CFuzzyTerm("large", 
new CTriangularMembershipFunction(0.8*avgBody, 0.9*avgBody , avgBody)));
 fvBody.Terms().Add(new CFuzzyTerm("Medium", 
new CTriangularMembershipFunction(0.1*avgBody, 0.5*avgBody , 0.9*avgBody)));
 fvBody.Terms().Add(new CFuzzyTerm("small", 
new CTriangularMembershipFunction(0.0, 0.1*avgBody , 0.2*avgBody)));
 fsCandle.Input().Add(fvBody);
 
 //--- Create lower shadow input variable for the CandlestickPatterns system--K
 CFuzzyVariable *fvlowerShadow=new CFuzzyVariable("lowerShadow",0.0,avglowerShadow);
 fvlowerShadow.Terms().Add(new CFuzzyTerm("large", 
new CTriangularMembershipFunction(0.8*avglowerShadow, 0.9*avglowerShadow, avglowerShadow)));
 fvlowerShadow.Terms().Add(new CFuzzyTerm("Medium", 
new CTriangularMembershipFunction(0.1*avglowerShadow, 0.5*avglowerShadow, 

0.9*avglowerShadow)));
 fvlowerShadow.Terms().Add(new CFuzzyTerm("small", 
new CTriangularMembershipFunction(0.0, 0.1*avglowerShadow, 0.2*avglowerShadow)));
 fsCandle.Output().Add(fvlowerShadow);
   
   //--- Create Output candle variable--L
   CFuzzyVariable *fvCandle=new CFuzzyVariable("candle",0.0,1.0);
   fvCandle.Terms().Add(new CFuzzyTerm("Hammer", new CConstantMembershipFunction(1.0)));
   fvCandle.Terms().Add(new CFuzzyTerm("Candlestick", new CConstantMembershipFunction(0.5)));
   fvCandle.Terms().Add(new CFuzzyTerm("Inverted Hammer", new CConstantMembershipFunction(
0.0)));
   fsCandle.Output().Add(fvCandle);
   
   //--- Create Mamdani fuzzy rule--M
   CMamdaniFuzzyRule *rule1 = fsCandle.ParseRule("if (upperShadow is small ) 
and (Body is small) and (lowerShadow is large) then (candle is Hammer)"); 
   CMamdaniFuzzyRule *rule2 = fsCandle.ParseRule("if ((upperShadow is large)) 
and (Body is small) and (lowerShadow is small) then (candle is Inverted Hammer)");
   
   //--- Add three Mamdani fuzzy rule in system--N
   fsCandle.Rules().Add(rule1);
   fsCandle.Rules().Add(rule2);
 
   //--- Set input value--O
   CList *in=new CList;
   CDictionary_Obj_Double *p_od_upperShadow=new CDictionary_Obj_Double;
   CDictionary_Obj_Double *p_od_Body=new CDictionary_Obj_Double;
   CDictionary_Obj_Double *p_od_lowerShadow=new CDictionary_Obj_Double;
   p_od_upperShadow.SetAll(fvupperShadow, upperShadow);
   p_od_Body.SetAll(fvBody, Body);
   p_od_lowerShadow.SetAll(fvBody, Body);
   
   in.Add(p_od_upperShadow);
   in.Add(p_od_Body);
   in.Add(p_od_lowerShadow);
   
   
  //--- Get result
   CList *result;
   CDictionary_Obj_Double *p_od_Candle;
   result=fsCandle.Calculate(in);
   p_od_Candle=result.GetNodeAtIndex(0);
   Print("Candlestick Pattern is, %: ",p_od_Candle.Value());
   rr =p_od_Candle.Value();
   delete in;
   delete result;
   delete fsCandle; 
  
   return (rr);
   
   }

In the above code, we first define the the candle function in F. This function takes 7 parameters that are the open, high, low and close plus the average upper shadow, average real and the average lower shadow that we had calculated in D. In G we once again calculate the real body, upper shadow and the lower shadow. This time we do it only for one candle. We will fuzzify this candle using the average real body, upper shadow and the lower shadow that we had calculated before. In H we define fsCandle rhis is a new Mamdani Fuzzy System. We have three inputs for the system. These inputs are fvupperShadow, fvBody and fvlowerShadow. Output of this Mamdani Fuzzy System is the fvCandle. Each fuzzy variable is created by specifying the maximum and the minimum values for each one of them. Let’s discuss them in detail below.

In I, we define the fvupperShadow fuzzy function. We use three linguistic variables small, medium and large. All these linguistic variables have a triangular membership functions. The highest and lowest values are defined for this fuzzy variable. In J we define fvBody fuzzy variable. This fvBody fuzzy variable has also got three linguistic terms that are the small, medium and large. All these linguistic terms have triangular membership functions. In K, we define the fvlowerShadow fuzzy variable. This fvlowerShadow fuzzy variable also have three linguistic terms that are small, medium and large. These linguistic terms also have triangular membership functions.

In L I have created the output fuzzy variable fvCandle.This fuzzy variable has got three fuzzy terms that are Hammer, Inverted Hammer and Ordinary Candlestick. The membership function for these fuzzy terms that I have used is constant membership functions. I am rushing through everything. Dictionary is concept that needs elaboration. I will return to this post after a few days and update it. So keep tuned. As far as this Fuzzy Hammer Candlestick Pattern Indicator is concerned. It is just for educational purposes. The idea is to make you familiar with fuzzy logic and how to use it in your trading strategy. In the meantime, you can take a look at my Million Dollar Trading Challenge.

Leave A Response