//+------------------------------------------------------------------+
//|ha sw .mq4 
//| 
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_color1 CLR_NONE



extern string TimeFrame       = "Current time frame";

extern string BarsID          = "HA SW1";
extern color  ColorUp         = DodgerBlue;
extern color  ColorDn         = Red;
extern int    widthWick       = 1;
extern int    widthBody       = 2;
extern bool   HAOnFirst       = false;

extern string _               = "Alerts settings";
extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;

//
//
//
//
//

double Buffer1[];
double Buffer2[];
double Buffer3[];
double Buffer4[];
double trend[];

//
//
//
//
//

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

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

int init()
{
   IndicatorBuffers(5);
   SetIndexBuffer(0,Buffer1); 
   SetIndexBuffer(1,Buffer2); 
   SetIndexBuffer(2,Buffer3); 
   SetIndexBuffer(3,Buffer4);
   SetIndexBuffer(4,trend);
   
      
     //
     //
     //
     //
     //
      
     indicatorFileName = WindowExpertName();
     returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
     calculateValue    = (TimeFrame=="calculateValue"); 
     if (calculateValue)
     {
         int s = StringFind(BarsID,":",0);
               shortName = BarsID;
               BarsID = StringSubstr(BarsID,0,s);
               return(0);
     } 
     timeFrame = stringToTimeFrame(TimeFrame); 
            
     //
     //
     //
     //
     //

     shortName = BarsID+": "+timeFrameToString(timeFrame)+ "  heiken ashi sw";
   IndicatorShortName(shortName);
return(0);
}

//
//
//
//
//

int deinit()
{
   int lookForLength = StringLen(BarsID);
   
   for (int i=ObjectsTotal()-1; i>=0; i--) {
   
   string objectName = ObjectName(i);
   if (StringSubstr(objectName,0,lookForLength) == BarsID) ObjectDelete(objectName);
   }
    
   return (0);
}

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

int start()
{
   int counted_bars=IndicatorCounted();
   int pos,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit = MathMin(Bars - counted_bars,Bars-1);
           if (returnBars)  { Buffer1[0] = limit+1; return(0); }
           window = WindowFind(shortName);
   
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {

     for (pos=limit; pos >= 0; pos--)
     {
          
         double haClose = (Open[pos]+High[pos]+Low[pos]+Close[pos])/4;
         double haOpen  = (Buffer3[pos+1]+Buffer4[pos+1])/2;
         double haHigh  = MathMax(High[pos],MathMax(haOpen,haClose));
         double haLow   = MathMin(Low[pos], 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 (!calculateValue) drawBar(Time[pos],Buffer1[pos],Buffer2[pos],Buffer3[pos],Buffer4[pos]);     
          
         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 (HAOnFirst) displace = 1;
   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]);
      int x = iBarShift(NULL,timeFrame,Time[pos+displace]);
         trend[pos]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",4,y);
      if (x!=y)
      { 
         Buffer1[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",0,y);
         Buffer2[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",1,y);
         Buffer3[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",2,y);
         Buffer4[pos] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",3,y);
       }  
         drawBar(Time[pos],Buffer1[pos],Buffer2[pos],Buffer3[pos],Buffer4[pos]); 
   }
   manageAlerts();
   return(0);         
}

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

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  ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Heiken Ashi "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

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

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    = BarsID+":"+TimeToStr(bTime)+"w";
          
            if (ObjectFind(oName) == -1)
              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) ==  -1)
              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);
}