//+------------------------------------------------------------------+
//|                                            Heiken Ashi Ma T3.mq4 |
//+------------------------------------------------------------------+
//|                                                      mod by Raff |
//|                                               2009 mod by mladen |
//+------------------------------------------------------------------+
#property copyright "Copyright � 2008,Forex-TSD.com"
#property link      "http://www.forex-tsd.com/"

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  Red
#property indicator_color2  RoyalBlue
#property indicator_color3  Red
#property indicator_color4  RoyalBlue
#property indicator_width1  1
#property indicator_width2  1
#property indicator_width3  2
#property indicator_width4  2

//
//
//
//
//

extern string TimeFrame       = "Current time frame";
extern int    SmoothLength    = 20;
extern int    AdaptPeriod     = 10;
extern int    Step            = 1;
extern bool   BetterFormula   = false;
extern string BarsID          = "HA separate 1";
extern color  ColorUp         = RoyalBlue;
extern color  ColorDn         = Red;
extern int    widthWick       = 1;
extern int    widthBody       = 3;
extern bool   CandlesOnFirst  = false;
extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = false;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;
extern bool   alertsNotify    = false;

//
//
//
//
//

double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double ExtMapBuffer4[];
double trend[];


string      indicatorName;
int         window;

//
//
//
//
//

string indicatorFileName;
bool   calculateValue;
bool   returnBars;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//|------------------------------------------------------------------|
//
//
//
//
//

int init()
{
   IndicatorBuffers(5);
   SetIndexBuffer(0, ExtMapBuffer1); SetIndexStyle(0,DRAW_NONE);
   SetIndexBuffer(1, ExtMapBuffer2); SetIndexStyle(1,DRAW_NONE);
   SetIndexBuffer(2, ExtMapBuffer3); SetIndexStyle(2,DRAW_NONE);
   SetIndexBuffer(3, ExtMapBuffer4); SetIndexStyle(3,DRAW_NONE);
   SetIndexBuffer(4, trend);
   
   //
   //
   //
   //
   //

      indicatorFileName = WindowExpertName();
      calculateValue    = (TimeFrame=="CalculateValue"); if (calculateValue) return(0);
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);

   indicatorName=BarsID+" - "+" Heiken Ashi ";
   IndicatorShortName(indicatorName);
   return(0);
}

//
//
//
//
//

int deinit()
{
   string lookFor       = BarsID+":";
   int    lookForLength = StringLen(lookFor);
   for (int i = ObjectsTotal(); i>= 0; i--)
   {
      string name = ObjectName(i);
      if (StringSubstr(name,0,lookForLength)==lookFor) ObjectDelete(name);
   }
   return (0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   double haOpen, haClose, haLow, haHigh;
   int    counted_bars=IndicatorCounted();
   int    pointModifier;
 
   //
   //
   //
   //
   //

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { ExtMapBuffer1[0] = limit+1; return(0); }
         window = WindowFind(indicatorName);
          
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
      if (Digits==3 || Digits==5)
            pointModifier = 10;
      else  pointModifier = 1;               
      
      //
      //
      //
      //
      //
      
      for(int pos=limit; pos >= 0; pos--)
      {
        double dev = iStdDev(NULL,0,AdaptPeriod,0,MODE_SMA,PRICE_CLOSE,pos);
        double avg = iSma(dev,AdaptPeriod,pos,0);
        if (dev!=0) 
               double period = SmoothLength*avg/dev;
        else          period = SmoothLength; 
        if (period<3) period = 3;
         
        //
        //
        //
        //
        //
      
        double maOpen  = iSmooth(Open[pos], period,pos,0);
        double maClose = iSmooth(Close[pos],period,pos,1);
        double maLow   = iSmooth(Low[pos],  period,pos,2);
        double maHigh  = iSmooth(High[pos], period,pos,3);
   
         //
         //
         //
         //
         //
        
         if (BetterFormula) {
               if (maHigh!=maLow)
                     haClose = (maOpen+maClose)/2+(((maClose-maOpen)/(maHigh-maLow))*MathAbs((maClose-maOpen)/2));
               else  haClose = (maOpen+maClose)/2; }
         else        haClose = (maOpen+maHigh+maLow+maClose)/4;
                     haOpen   = (ExtMapBuffer3[pos+1]+ExtMapBuffer4[pos+1])/2;
                     haHigh   = MathMax(maHigh, MathMax(haOpen,haClose));
                     haLow    = MathMin(maLow,  MathMin(haOpen,haClose));

         if (haOpen<haClose) { ExtMapBuffer1[pos]=haLow;  ExtMapBuffer2[pos]=haHigh; } 
         else                { ExtMapBuffer1[pos]=haHigh; ExtMapBuffer2[pos]=haLow;  } 
                               ExtMapBuffer3[pos]=haOpen;
                               ExtMapBuffer4[pos]=haClose;
      
         //
         //
         //
         //
         //

         if (Step>0)
         {
            if(MathAbs(ExtMapBuffer1[pos]-ExtMapBuffer1[pos+1]) < Step*pointModifier*Point ) ExtMapBuffer1[pos]=ExtMapBuffer1[pos+1];
            if(MathAbs(ExtMapBuffer2[pos]-ExtMapBuffer2[pos+1]) < Step*pointModifier*Point ) ExtMapBuffer2[pos]=ExtMapBuffer2[pos+1];
            if(MathAbs(ExtMapBuffer3[pos]-ExtMapBuffer3[pos+1]) < Step*pointModifier*Point ) ExtMapBuffer3[pos]=ExtMapBuffer3[pos+1];
            if(MathAbs(ExtMapBuffer4[pos]-ExtMapBuffer4[pos+1]) < Step*pointModifier*Point ) ExtMapBuffer4[pos]=ExtMapBuffer4[pos+1];
         }
         trend[pos] = trend[pos+1];
            if (ExtMapBuffer3[pos]<ExtMapBuffer4[pos]) trend[pos] = 1;
            if (ExtMapBuffer3[pos]>ExtMapBuffer4[pos]) trend[pos] =-1;         
         if (!calculateValue) drawBar(Time[pos],ExtMapBuffer1[pos],ExtMapBuffer2[pos],ExtMapBuffer3[pos],ExtMapBuffer4[pos]);
         
      }
      manageAlerts();
      return(0);
   }      
   
   //
   //
   //
   //
   //
   
   int displace = -1; if (CandlesOnFirst) displace = 1;
   limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
    for (pos=limit;pos>=0; pos--)
    {
       int y = iBarShift(NULL,timeFrame,Time[pos]);
       int x = iBarShift(NULL,timeFrame,Time[pos+displace]);
          trend[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,4,y);
          if (x!=y)
          { 
             ExtMapBuffer1[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,0,y);
             ExtMapBuffer2[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,1,y);
             ExtMapBuffer3[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,2,y);
             ExtMapBuffer4[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,3,y);
          }
          else
          {
             ExtMapBuffer1[pos] = EMPTY_VALUE;
             ExtMapBuffer2[pos] = EMPTY_VALUE;
             ExtMapBuffer3[pos] = EMPTY_VALUE;
             ExtMapBuffer4[pos] = EMPTY_VALUE;
          }                 
         drawBar(Time[pos],ExtMapBuffer1[pos],ExtMapBuffer2[pos],ExtMapBuffer3[pos],ExtMapBuffer4[pos]);
            
   }
   manageAlerts();
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void drawBar(int bTime, double prHigh, double prLow, double prOpen, double prClose)
{
   color wickColor = ColorUp; if (prHigh >prLow)  wickColor = ColorDn;
   color barColor  = ColorUp; if (prClose<prOpen) barColor  = ColorDn;
   string oName;
          oName = BarsID+":"+TimeToStr(bTime)+"w";
            if (ObjectFind(oName) < 0) ObjectCreate(oName,OBJ_TREND,window,bTime,0,bTime,0);
                 ObjectSet(oName, OBJPROP_PRICE1, prHigh);
                 ObjectSet(oName, OBJPROP_PRICE2, prLow);
                 ObjectSet(oName, OBJPROP_COLOR, wickColor);
                 ObjectSet(oName, OBJPROP_WIDTH, widthWick);
                 ObjectSet(oName, OBJPROP_RAY, false);
                 ObjectSet(oName, OBJPROP_BACK, true);
           
         oName = BarsID+":"+TimeToStr(bTime)+"b";
            if (ObjectFind(oName) < 0)ObjectCreate(oName,OBJ_TREND,window,bTime,0,bTime,0);
                 ObjectSet(oName, OBJPROP_PRICE1, prOpen);
                 ObjectSet(oName, OBJPROP_PRICE2, prClose);
                 ObjectSet(oName, OBJPROP_COLOR, barColor);
                 ObjectSet(oName, OBJPROP_WIDTH, widthBody);
                 ObjectSet(oName, OBJPROP_RAY, false);
                 ObjectSet(oName, OBJPROP_BACK, true);
}

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

double workSmooth[][20];
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 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);
}

//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] == 1) doAlert(whichBar,"buy");
         if (trend[whichBar] ==-1) doAlert(whichBar,"sell");
      }         
   }
}   

//
//
//
//
//

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()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," - ",timeFrameToString(timeFrame)+" heiken ashi adaptive smoother ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsNotify)  SendNotification(StringConcatenate(Symbol(), Period() ," heiken ashi adaptive smoother " +" "+message));
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," heiken ashi adaptive smoother "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}