Search code examples
mql4tradingalgorithmic-tradingmetatrader4

Rectangle is not drawing the bullish engulfing pattern


I wrote the following code to look through the last 100 candlesticks and draw a rectangle around a bullish engulfing candlestick patterns. I hope extend it for bearish engulfing pattern too. I don't know why, but the rectangles don't draw. Please take a look at the code below

bool isBullishEngulfing(int current)  {

   if((iClose(_Symbol,0,current) > iOpen(_Symbol,0,current)) && (iClose(_Symbol,0,current + 1) < iOpen(_Symbol,0,current + 1))  && 
      (iOpen(_Symbol,0,current) < iClose(_Symbol,0,current + 1)) && (iClose(_Symbol,0,current) > iOpen(_Symbol,0,current + 1)))
         return true;
      return false;         

}

void showRectangles() {

   for (int i=100;i<=1;i--)   {
      if(isBullishEngulfing(i)) {

        drawBullRectangle(i,iHigh(_Symbol,0,i),iLow(_Symbol,0,i));
    }
   }
}

bool drawBullRectangle(int candleInt,const double top,const double bottom)
{
    const datetime starts=iTime(_Symbol,0,candleInt); 
    const datetime ends=starts+PeriodSeconds()*Numbars; //Numbars shows how long the rectangle should draw
    const string name=prefix+"_"+(candleInt>0?"DEMAND":"SUPPLY")+"_"+TimeToString(starts);

    if(!ObjectCreate(0,name,OBJ_RECTANGLE,0,0,0,0,0))
    {
        printf("%i %s: failed to create %s. error=%d",__LINE__,__FILE__,name,_LastError);
        return false;
    }
    ObjectSetInteger(0,name,OBJPROP_TIME1,starts);
    ObjectSetInteger(0,name,OBJPROP_TIME2,ends);
    ObjectSetDouble(0,name,OBJPROP_PRICE1,top);
    ObjectSetDouble(0,name,OBJPROP_PRICE2,bottom);

    ObjectSetInteger(0,name,OBJPROP_COLOR, clrAqua);

   ObjectSetInteger(0,name,OBJPROP_STYLE, STYLE_SOLID);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,1);

   ObjectSetInteger(0,name,OBJPROP_FILL, true);

    return true;
}

void OnDeinit(const int reason){ObjectsDeleteAll(0,prefix);}
void OnTick()
{
    if(!isNewBar())
        return;     //not necessary but waste of time to check every second


    showRectangles();
}

bool isNewBar()
{
   static datetime lastbar;
   datetime curbar = (datetime)SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE);
   if(lastbar != curbar)
   {
      lastbar = curbar;
      return true;
   }
   return false;
}

I would appreciate help to resolve this.


Solution

  • The error is mainly in the loop, it should be for (int i=100;i>=1;i--)

    The other "possible" error is in the logic of theisBullishEngulfing() function.

    Usually, the Close of the previous bar is equal to the Open of the current bar, so the following condition doesn't get fulfilled(most of the time)

    iOpen(_Symbol,0,current) < iClose(_Symbol,0,current + 1)
    

    (So, I suggest to remove this line, but this is just a suggestion, note there are occasions that your condition get fulfilled as well)