//+------------------------------------------------------------------
//|                   Engulfing Candle Ma Touch
//|                          By: K.Trim
//+------------------------------------------------------------------


#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1  DodgerBlue

#property indicator_width1  1


//
//
//

string TimeFrame       = "Current time frame";

extern int    MaPeriod        = 30;
extern int    MaMethod        = 1;
extern int    MaPrice         = 0;

extern string Alert_Settings  = "Alert Settings";
extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = true;
extern bool   alertsNotify    = false;
extern bool   alertsEmail     = false;

extern string arrowsIdentifier= "CPatternArrows";
extern bool   ShowArrows      = true;
extern double arrowsUpperGap  = 0.6;
extern double arrowsLowerGap  = 0.2;
extern color  arrowsUpColor1  = LimeGreen;
extern color  arrowsDnColor1  = Red;
extern color  arrowsUpCode    = 241;
extern color  arrowsDnCode    = 242;
extern int    arrowsUpSize    = 1;
extern int    arrowsDnSize    = 1;            

extern string BuyAlert        = " -  BUY  -  ";
extern string SellAlert       = " -  SELL  -  ";

extern int    History         = 5000;

//
//
//

double ma1[];
double UpH[];
double DnH[]; 
double btrend[];
double strend[];


string indicatorFileName;
bool   returnBars;
int    timeFrame;



//+------------------------------------------------------------------
//|
//+------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers (5);
      SetIndexBuffer(0,ma1);   
      SetIndexBuffer(1,UpH);   
      SetIndexBuffer(2,DnH);     
      SetIndexBuffer(3,btrend);
      SetIndexBuffer(4,strend);       
       
  
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         returnBars        = (TimeFrame=="returnBars"); if (returnBars) return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
  IndicatorShortName(timeFrameToString(timeFrame)+": Engulfing Candle Ma Touch ("+MaPeriod+")  ");
  return ( 0 );
}

int deinit() 
{  
deleteArrows();
return(0); 
}



//+------------------------------------------------------------------
//|
//+------------------------------------------------------------------
int start()
{
   int limit,counted_bars=IndicatorCounted();
   
   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-counted_bars,Bars-1);
           if (limit>History) limit = History;
           if (returnBars) { UpH[0] = limit+1; return(0); }
           if (timeFrame!=Period()) limit = MathMax(limit,MathMin(History,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));

   //
   //
   
   for(int i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         ma1[i] = iMA(NULL,timeFrame,MaPeriod,0,MaMethod,MaPrice,y);            
         
  
  double BullishCndl= Close[i+1]>Open[i+1] && (((High[i+1]-Close[i+1])+(Open[i+1]-Low[i+1]))<(Close[i+1]-Open[i+1]));
  double BearishCndl= Close[i+1]<Open[i+1] && (((High[i+1]-Open[i+1])+(Close[i+1]-Low[i+1]))<(Open[i+1]-Close[i+1]));
  
  double EngulfingUp   = Close[i+2]<Open[i+2] && BullishCndl && (Close[i+1]-Open[i+1])>(High[i+2]-Close[i+2]);
  double EngulfingDown = Close[i+2]>Open[i+2] && BearishCndl && (Open[i+1]-Close[i+1])>(Open[i+2]-Low[i+2]);  



//--------------------------------------------------------------------------------------------------------------------------//
//NOTE ARROWS INDICATING THAT A SUCCESSFUL CANDLE PATTERN HAS FORMED SHOWS UP ON THE CANDLE AFTER THE PATTERN
//--------------------------------------------------------------------------------------------------------------------------//



//ENGULFING CANDLE PATTERN--------------------------------------------------------------------------------------------------//                               
                   
               if (EngulfingUp && Open[i+1]<ma1[i+1] && High[i+1]>ma1[i]) btrend[i] = 1;       
               if (btrend[i]==1 && btrend[i+1]!=1)  UpH[i+1] = 1;
          else
              btrend[i] = 0;
          

               if (EngulfingDown && Open[i+1]>ma1[i+1] && Low[i+1]<ma1[i]) strend[i] = -1;       
               if (strend[i]==-1 && strend[i+1]!=-1)  DnH[i+1] = 1;
          else
              strend[i] = 0;
                      
//-------------------------------------------------------------------------------------------------------------------------//          

          
manageArrow(i);
   }
 
   manageAlerts();
   return(0);
} 



//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
void manageAlerts() 
{
   if (alertsOn) 
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      
         if (UpH[whichBar + 1] == 1) doAlert(whichBar,BuyAlert);
         if (DnH[whichBar + 1] == 1) doAlert(whichBar,SellAlert);
    
   }
}

//
//

void doAlert(int forBar, string doWhat) 
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       message =  StringConcatenate(Symbol(),doWhat,timeFrameToString(timeFrame),"  Engulfing Candle Ma Touch ");
          if (alertsMessage) Alert(message);
          if (alertsNotify)  SendNotification(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"Engulfing Candle Ma Touch "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}



//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
void manageArrow(int i)
{
   if (ShowArrows)
   {
      deleteArrow(Time[i]);

         if (UpH[i+1] == 1) drawArrow(i+1,arrowsUpColor1,arrowsUpCode,arrowsUpSize,false);
         if (DnH[i+1] == 1) drawArrow(i+1,arrowsDnColor1,arrowsDnCode,arrowsDnSize, true);
    }
}               


void drawArrow(int i,color theColor,int theCode,int theWidth, bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = iATR(NULL,0,20,i);   
   
//
//
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         ObjectSet(name,OBJPROP_WIDTH,theWidth);
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i+1] + arrowsUpperGap * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i+1]  - arrowsLowerGap * gap);
}

//
//

void deleteArrows()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}

//
//

void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}



//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

//
//
//
//
//

int stringToTimeFrame(string tfs) {
   tfs = stringUpperCase(tfs);
   for (int i=ArraySize(iTfTable)-1; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[i],Period()));
                                                      return(Period());
}
string timeFrameToString(int tf) {
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//
//
//
//
//

string stringUpperCase(string str) {
   string   s = str;

   for (int length=StringLen(str)-1; length>=0; length--) {
      int tchar = StringGetChar(s, length);
         if((tchar > 96 && tchar < 123) || (tchar > 223 && tchar < 256))
                     s = StringSetChar(s, length, tchar - 32);
         else if(tchar > -33 && tchar < 0)
                     s = StringSetChar(s, length, tchar + 224);
   }
   return(s);
}


