//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"
// original idea fr this indicator by Dan Valcu
//------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  LimeGreen
#property indicator_color2  Red
#property indicator_color3  DimGray
#property indicator_color4  Goldenrod
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_width4  2
#property indicator_level1  0

//
//
//
//
//

extern string TimeFrame           = "Current time frame";
extern bool   BetterFormula       = false;
extern int    SmoothLength        = 40;
extern int    AdaptPeriod         = 21;
extern int    SignalPeriod        = 14;
extern int    SignalMethod        = MODE_LWMA;
extern bool   alertsOn            = false;
extern bool   alertsOnZeroCross   = true;
extern bool   alertsOnSignalCross = true;
extern bool   alertsOnCurrent     = true;
extern bool   alertsMessage       = true;
extern bool   alertsSound         = false;
extern bool   alertsEmail         = false;
extern bool   alertsNotify        = false;

//
//
//
//
//

double upHaD[];
double dnHaD[];
double bhaOpn[];
double bhaClo[];
double haDelta[];
double haSignal[];
double trendz[];
double trends[];


string indicatorFileName;
bool   returnBars;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorDigits(6);
   IndicatorBuffers(8);
   SetIndexBuffer(0, upHaD); SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1, dnHaD); SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexBuffer(2, haDelta);
   SetIndexBuffer(3, haSignal);
   SetIndexBuffer(4, bhaOpn);
   SetIndexBuffer(5, bhaClo);
   SetIndexBuffer(6, trendz);
   SetIndexBuffer(7, trends);

      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
   IndicatorShortName(timeFrameToString(timeFrame)+" haDelta ("+SignalPeriod+")");
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { upHaD[0] = MathMin(limit+1,Bars-1); return(0); }
          
   //
   //
   //
   //
   //
   
   if (timeFrame == Period())
   {
      for (int i=limit; i >= 0; i--)
      {
         double dev = iStdDev(NULL,0,AdaptPeriod,0,MODE_SMA,PRICE_CLOSE,i);
         double avg = iSma(dev,AdaptPeriod,i,0);
         if (dev!=0) 
                double period = SmoothLength*avg/dev;
         else          period = SmoothLength; 
         if (period<3) period = 3;
         
         //
         //
         //
         //
         //
         
         double prOpen  = Open[i];
         double prClose = Close[i];
         double prLow   = Low[i];
         double prHigh  = High[i];

         if (BetterFormula) {
               if (prHigh!=prLow)
                     double haClose = (prOpen+prClose)/2.0+(((prClose-prOpen)/(prHigh-prLow))*MathAbs((prClose-prOpen)/2.0));
                     else   haClose = (prOpen+prClose)/2.0; }
         else               haClose = (prOpen+prHigh+prLow+prClose)/4;
                     double haOpen  = (bhaOpn[i+1]+bhaClo[i+1])/2.0;
                          bhaOpn[i] = haOpen;
                          bhaClo[i] = haClose;
                         haDelta[i] = iSmooth(haClose-haOpen,period,i,0);
                         }
                         
                         for (i=limit; i >= 0; i--)
                         {
                            haSignal[i] = iMAOnArray(haDelta,0,SignalPeriod,0,SignalMethod,i);
                              upHaD[i]  = EMPTY_VALUE;
                              dnHaD[i]  = EMPTY_VALUE;
                              trendz[i] = trendz[i+1];
                              trends[i] = trends[i+1];
                              if (haDelta[i]>haSignal[i]) trends[i] = 1;
                              if (haDelta[i]<haSignal[i]) trends[i] =-1;
                              if (haDelta[i]>0)           trendz[i] = 1;
                              if (haDelta[i]<0)           trendz[i] =-1;
                              if (trendz[i] == 1)         upHaD[i]  = haDelta[i];
                              if (trendz[i] ==-1)         dnHaD[i]  = haDelta[i];
      }
      manageAlerts();
      return(0);
    }
     
   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for (i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         haDelta[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",BetterFormula,SmoothLength,AdaptPeriod,SignalPeriod,SignalMethod,2,y);
         haSignal[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",BetterFormula,SmoothLength,AdaptPeriod,SignalPeriod,SignalMethod,3,y);
         trendz[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",BetterFormula,SmoothLength,AdaptPeriod,SignalPeriod,SignalMethod,6,y);
         trends[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",BetterFormula,SmoothLength,AdaptPeriod,SignalPeriod,SignalMethod,7,y);
         upHaD[i]  = EMPTY_VALUE;
         dnHaD[i]  = EMPTY_VALUE;
         trendz[i] = trendz[i+1];
         trends[i] = trends[i+1];
            if (haDelta[i]>haSignal[i]) trends[i] = 1;
            if (haDelta[i]<haSignal[i]) trends[i] =-1;
            if (haDelta[i]>0)           trendz[i] = 1;
            if (haDelta[i]<0)           trendz[i] =-1;
            if (trendz[i] == 1)         upHaD[i]  = haDelta[i];
            if (trendz[i] ==-1)         dnHaD[i]  = haDelta[i];
   }
   manageAlerts();
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workSmooth[][5];
double iSmooth(double price, double length, int r, int instanceNo=0)
{
   if (ArrayRange(workSmooth,0)!=Bars) ArrayResize(workSmooth,Bars); instanceNo *= 5; r = Bars-r-1;
 	if(r<=2) { workSmooth[r][instanceNo] = price; workSmooth[r][instanceNo+2] = price; workSmooth[r][instanceNo+4] = price; return(price); }
   
   //
   //
   //
   //
   //
   
	double alpha = 0.45*(length-1.0)/(0.45*(length-1.0)+2.0);
   	  workSmooth[r][instanceNo+0] =  price+alpha*(workSmooth[r-1][instanceNo]-price);
	     workSmooth[r][instanceNo+1] = (price - workSmooth[r][instanceNo])*(1-alpha)+alpha*workSmooth[r-1][instanceNo+1];
	     workSmooth[r][instanceNo+2] =  workSmooth[r][instanceNo+0] + workSmooth[r][instanceNo+1];
	     workSmooth[r][instanceNo+3] = (workSmooth[r][instanceNo+2] - workSmooth[r-1][instanceNo+4])*MathPow(1.0-alpha,2) + MathPow(alpha,2)*workSmooth[r-1][instanceNo+3];
	     workSmooth[r][instanceNo+4] =  workSmooth[r][instanceNo+3] + workSmooth[r-1][instanceNo+4]; 
   return(workSmooth[r][instanceNo+4]);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

double workSma[][2];
double iSma(double price, int period, int r, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= Bars) ArrayResize(workSma,Bars); instanceNo *= 2; r = Bars-r-1;

   //
   //
   //
   //
   //
      
   workSma[r][instanceNo] = price;
   if (r>=period)
          workSma[r][instanceNo+1] = workSma[r-1][instanceNo+1]+(workSma[r][instanceNo]-workSma[r-period][instanceNo])/period;
   else { workSma[r][instanceNo+1] = 0; for(int k=0; k<period && (r-k)>=0; k++) workSma[r][instanceNo+1] += workSma[r-k][instanceNo];  
          workSma[r][instanceNo+1] /= k; }
   return(workSma[r][instanceNo+1]);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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 char = StringGetChar(s, length);
         if((char > 96 && char < 123) || (char > 223 && char < 256))
                     s = StringSetChar(s, length, char - 32);
         else if(char > -33 && char < 0)
                     s = StringSetChar(s, length, char + 224);
   }
   return(s);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      
      //
      //
      //
      //
      //
      
      static datetime time1 = 0;
      static string   mess1 = "";
         if (alertsOnZeroCross && trendz[whichBar] != trendz[whichBar+1])
         {
            if (trendz[whichBar] ==  1) doAlert(time1,mess1,whichBar," haDelta crossed zero line up");
            if (trendz[whichBar] == -1) doAlert(time1,mess1,whichBar," haDelta crossed zero line down");
         }            
      static datetime time2 = 0;
      static string   mess2 = "";
         if (alertsOnSignalCross && trends[whichBar] != trends[whichBar+1])
         {
            if (trends[whichBar] ==  1) doAlert(time2,mess2,whichBar," haDelta crossed signal line up");
            if (trends[whichBar] == -1) doAlert(time2,mess2,whichBar," haDelta crossed signal line down");
         }            
   }
}   

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, int forBar, string doWhat)
{
   string message;
   
      if (previousAlert != doWhat || previousTime != Time[forBar]) {
          previousAlert  = doWhat;
          previousTime   = Time[forBar];

          //
          //
          //
          //
          //

          message =  Symbol()+" "+timeFrameToString(timeFrame)+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"haDelta "),message);
             if (alertsNotify)  SendNotification(StringConcatenate(Symbol(), Period() ," haDelta " +" "+message));
             if (alertsSound)   PlaySound("alert2.wav");
      }
}