//+------------------------------------------------------------------+
//|                                            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_chart_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            = 0;
extern bool   BetterFormula   = true;

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 Buffer1[];
double Buffer2[];
double Buffer3[];
double Buffer4[];
double trend[];

//
//
//
//
//

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

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

int init()
{
   IndicatorBuffers(5);
   SetIndexBuffer(0,Buffer1); SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1,Buffer2); SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexBuffer(2,Buffer3); SetIndexStyle(2,DRAW_HISTOGRAM);
   SetIndexBuffer(3,Buffer4); SetIndexStyle(3,DRAW_HISTOGRAM);
   SetIndexBuffer(4,trend);
   
      //
      //
      //
      //
      //
      
      indicatorFileName = WindowExpertName();
      calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //
      
      IndicatorShortName(timeFrameToString(timeFrame)+"   Heiken ashi - adaptive smoother");  
return(0);
}

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

int start()
{
   double haOpen, haClose, haLow, haHigh;
   int    pointModifier;
   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) { Buffer1[0] = limit+1; return(0); }   
         if (Digits==3 || Digits==5)
               pointModifier = 10;
         else  pointModifier = 1;               
          
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
     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  = (Buffer3[pos+1]+Buffer4[pos+1])/2;
                 haHigh  = MathMax(maHigh, MathMax(haOpen,haClose));
                 haLow   = MathMin(maLow,  MathMin(haOpen,haClose));

        if (haOpen<haClose) { Buffer1[pos]=haLow;  Buffer2[pos]=haHigh; } 
        else                { Buffer1[pos]=haHigh; Buffer2[pos]=haLow;  } 
                              Buffer3[pos]=haOpen;
                              Buffer4[pos]=haClose;
      
        //
        //
        //
        //
        //

        if (Step>0)
        {
           if( MathAbs(Buffer1[pos]-Buffer1[pos+1]) < Step*pointModifier*Point) Buffer1[pos]=Buffer1[pos+1];
           if( MathAbs(Buffer2[pos]-Buffer2[pos+1]) < Step*pointModifier*Point) Buffer2[pos]=Buffer2[pos+1];
           if( MathAbs(Buffer3[pos]-Buffer3[pos+1]) < Step*pointModifier*Point) Buffer3[pos]=Buffer3[pos+1];
           if( MathAbs(Buffer4[pos]-Buffer4[pos+1]) < Step*pointModifier*Point) Buffer4[pos]=Buffer4[pos+1];
        }
                  
        trend[pos] = trend[pos+1];
        if (Buffer3[pos]<Buffer4[pos]) trend[pos] = -1;
        if (Buffer3[pos]>Buffer4[pos]) trend[pos] =  1;
     }  
    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)
          { 
             Buffer1[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,0,y);
             Buffer2[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,1,y);
             Buffer3[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,2,y);
             Buffer4[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",SmoothLength,AdaptPeriod,Step,BetterFormula,3,y);
          }
          else
          {
             Buffer1[pos] = EMPTY_VALUE;
             Buffer2[pos] = EMPTY_VALUE;
             Buffer3[pos] = EMPTY_VALUE;
             Buffer4[pos] = EMPTY_VALUE;
          }                 
    }
manageAlerts();
return(0);         
}

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

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");
   }
}