#property link      "www.forex-tsd.com"      
#property copyright "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

//
//
//
//
//

extern string TimeFrame       = "Current time frame";
extern int    MaPeriod        = 6;
extern ENUM_MA_METHOD MaMethod        = MODE_SMMA;
extern int    MaPeriod2       = 2;
extern ENUM_MA_METHOD MaMethod2       = MODE_LWMA;
extern color  BullColor       = RoyalBlue;
extern color  BearColor       = Red;
extern string UniqueID        = "Heiken Ashi separate 1";

extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = false;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;

//
//
//
//
//

double Buffer1[];
double Buffer2[];
double Buffer3[];
double Buffer4[];
double Buffer5[];
double Buffer6[];
double Buffer7[];
double Buffer8[];
double trend[];

string indicatorFileName;
bool   calculateHA;
bool   calculateValue;
bool   returnBars;
int    timeFrame;
color  BarsColor;
//+------------------------------------------------------------------+
//|                                                                  |
//|------------------------------------------------------------------|
//
//
//
//
//

int init()
{
   IndicatorBuffers(9);   
   SetIndexBuffer(0, Buffer3); SetIndexStyle(0,DRAW_LINE,EMPTY,EMPTY,clrNONE);
   SetIndexBuffer(1, Buffer4); SetIndexStyle(1,DRAW_LINE,EMPTY,EMPTY,clrNONE);
   SetIndexBuffer(2, Buffer1); SetIndexStyle(2,DRAW_LINE,EMPTY,EMPTY,clrNONE);
   SetIndexBuffer(3, Buffer2); SetIndexStyle(3,DRAW_LINE,EMPTY,EMPTY,clrNONE);
   SetIndexBuffer(8, trend);
   
   //
   //
   //
   //
   //
      
      indicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
      calculateHA       = (TimeFrame=="calculateHA");
      if (calculateHA)
      {
            SetIndexBuffer(4, Buffer5);
            SetIndexBuffer(5, Buffer6);
            SetIndexBuffer(6, Buffer7);
            SetIndexBuffer(7, Buffer8);
            return(0);
      }      
      timeFrame = stringToTimeFrame(TimeFrame);
   IndicatorShortName(UniqueID);
return(0);
}
void deinit()
{
   int lookFor = StringLen(UniqueID);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string name = ObjectName(i);
      if (StringSubstr(name,0,lookFor)==UniqueID) ObjectDelete(name);
   }
}

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

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)  { Buffer3[0] = limit+1; return(0); }
         if (calculateHA) { calculateHA(limit);   return(0); }
          
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {          
      for(int pos=limit; pos >= 0; pos--)
      {
         Buffer1[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateHA",MaPeriod,MaMethod,MaPeriod2,MaMethod2,0,pos);
         Buffer2[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateHA",MaPeriod,MaMethod,MaPeriod2,MaMethod2,1,pos);
         Buffer3[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateHA",MaPeriod,MaMethod,MaPeriod2,MaMethod2,2,pos);
         Buffer4[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateHA",MaPeriod,MaMethod,MaPeriod2,MaMethod2,3,pos);
         trend[pos] = trend[pos+1];
            if (Buffer3[pos] < Buffer4[pos]) trend[pos] =  1;
            if (Buffer3[pos] > Buffer4[pos]) trend[pos] = -1;
            if(Buffer1[pos]>Buffer2[pos])BarsColor=BearColor;
            else                         BarsColor=BullColor;
         DrawBarLines(Time[pos],"2", BarsColor, 2, Buffer3[pos], Buffer4[pos]);
         DrawBarLines(Time[pos],"1", BarsColor, 1, Buffer1[pos], Buffer2[pos]);
       }   
       manageAlerts();
       return(0);
    }
    
    //
    //
    //
    //
    //
   
    limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
    for(pos = limit; pos >= 0; pos--)
    {
     int y = iBarShift(NULL,timeFrame,Time[pos]);
        Buffer3[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",MaPeriod,MaMethod,MaPeriod2,MaMethod2,BullColor,BearColor,UniqueID,0,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,0,y);
        Buffer4[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",MaPeriod,MaMethod,MaPeriod2,MaMethod2,BullColor,BearColor,UniqueID,1,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,1,y);
    }   
 return(0);
 }
 
//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void calculateHA(int limit)
{
   for (int i=limit; i>=0; i--)
   {
      double maOpen  = iMA(NULL,0,MaPeriod,0,MaMethod,PRICE_OPEN ,i);
      double maClose = iMA(NULL,0,MaPeriod,0,MaMethod,PRICE_CLOSE,i);
      double maLow   = iMA(NULL,0,MaPeriod,0,MaMethod,PRICE_LOW  ,i);
      double maHigh  = iMA(NULL,0,MaPeriod,0,MaMethod,PRICE_HIGH ,i);
      double haOpen  = (Buffer5[i+1]+Buffer6[i+1])/2.0;
      double haClose = (maOpen+maHigh+maLow+maClose)/4;
      double haHigh  = MathMax(maHigh, MathMax(haOpen, haClose));
      double haLow   = MathMin(maLow,  MathMin(haOpen, haClose));

      if (haOpen<haClose) 
            { Buffer7[i]=haLow; Buffer8[i]=haHigh; } 
      else  { Buffer8[i]=haLow; Buffer7[i]=haHigh; } 
              Buffer5[i]=haOpen;
              Buffer6[i]=haClose;
   }
   for(i=limit; i>=0; i--)
   {
      double atr = iATR(NULL,0,100,i); if (atr==0) atr=1;
//      double atr = 1;
      double smOpen  = iMAOnArray(Buffer5,0,MaPeriod2,0,MaMethod2,i)/atr;
      double smClose = iMAOnArray(Buffer6,0,MaPeriod2,0,MaMethod2,i)/atr;
      double smHL1   = iMAOnArray(Buffer7,0,MaPeriod2,0,MaMethod2,i)/atr;
      double smHL2   = iMAOnArray(Buffer8,0,MaPeriod2,0,MaMethod2,i)/atr;
      double smMax   = MathMax(smClose, MathMax(smOpen, MathMax(smHL1, smHL2)));
      double smMin   = MathMin(smClose, MathMin(smOpen, MathMax(smHL1, smHL2)));
      double tem     = (smOpen+smClose)/2;
             smOpen -=tem;
             smClose-=tem;
             smHL1  -=tem;
             smHL2  -=tem;
           Buffer1[i]=smOpen;
           Buffer2[i]=smClose;
           Buffer3[i]=smHL1;
           Buffer4[i]=smHL2;
//           Buffer3[i]=smHL1;
//           Buffer4[i]=smHL2;
   }      
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//
void DrawBarLines(int t, string add, color Clr, int width, double PRICE1, double PRICE2) 
{ 
   int window = WindowFind(UniqueID);
   string name = UniqueID+t+add;
   ObjectDelete(name);
   ObjectCreate(name, OBJ_TREND, window, 0, 0);
      ObjectSet(name, OBJPROP_PRICE1, PRICE1);
      ObjectSet(name, OBJPROP_PRICE2, PRICE2);
      ObjectSet(name, OBJPROP_TIME1, t);
      ObjectSet(name, OBJPROP_TIME2, t);
      ObjectSet(name, OBJPROP_WIDTH, width);
      ObjectSet(name, OBJPROP_COLOR, Clr);
      ObjectSet(name, OBJPROP_BACK, true);
      ObjectSet(name, OBJPROP_RAY, false);
}
//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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 (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      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 =  timeFrameToString(Period())+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" - Heiken Ashi Smoothed Lines  "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Heiken Ashi Smoothed Lines "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}