//------------------------------------------------------------------
#property copyright "copyleft www.forex-tsd.com"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1  LimeGreen
#property indicator_color2  PaleVioletRed
#property indicator_color3  LimeGreen
#property indicator_color4  PaleVioletRed
#property indicator_width3  3
#property indicator_width4  3

//
//
//
//
//

extern string  TimeFrame       = "Current time frame";
extern int     CCIperiod       = 50;
extern int     ATRperiod       = 5;
extern int     applied_price   = 5; 
extern bool    noIntermediate  = true;
extern bool    alertsOn        = false;
extern bool    alertsOnCurrent = true;
extern bool    alertsMessage   = true;
extern bool    alertsSound     = false;
extern bool    alertsEmail     = false;

//
//
//
//
//

double   SThu[];
double   SThd[];
double   STbu[];
double   STbd[];
double   Trend[];
double   Direction[];

int      timeFrame;
bool     calculateValue;
bool     returnBars;
string   indicatorFileName;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(6);
      SetIndexBuffer(0,SThu); SetIndexStyle(0,DRAW_HISTOGRAM);
      SetIndexBuffer(1,SThd); SetIndexStyle(1,DRAW_HISTOGRAM);
      SetIndexBuffer(2,STbu); SetIndexStyle(2,DRAW_HISTOGRAM);
      SetIndexBuffer(3,STbd); SetIndexStyle(3,DRAW_HISTOGRAM);
      SetIndexBuffer(4,Trend);
      SetIndexBuffer(5,Direction);
      
         //
         //
         //
         //
         //
                  
         indicatorFileName = WindowExpertName();
         calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
         returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
         
         //
         //
         //
         //
         //

   IndicatorShortName("SuperTrend Histo"+timeFrameToString(timeFrame));
return(0);    
}
int deinit()
{
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars = IndicatorCounted();
      if(counted_bars < 0) return(-1);
      if(counted_bars > 0) counted_bars--;
         int limit = MathMax(Bars-counted_bars,Bars-1);
         if (returnBars) { SThu[0] = limit+1; return(0); }
   
   //
   //
   //
   //
   //

   if (calculateValue || timeFrame==Period())
   {
      for(int i=limit; i >= 0; i--)
      {
         double cciTrend  = iCCI(NULL, 0, CCIperiod, applied_price, i);
         
         //
         //
         //
         //
         //
         
         SThu[i] = EMPTY_VALUE; 
         SThd[i] = EMPTY_VALUE;
         STbu[i] = EMPTY_VALUE;
         STbd[i] = EMPTY_VALUE;
         Trend[i]     = Trend[i+1];
         Direction[i] = Direction[i+1];
            if (cciTrend > 0) { Trend[i] = MathMax(Low[i]  - iATR(NULL, 0, ATRperiod, i),Trend[i+1]); Direction[i] =  1; }
            if (cciTrend < 0) { Trend[i] = MathMin(High[i] + iATR(NULL, 0, ATRperiod, i),Trend[i+1]); Direction[i] = -1; }
            if (!noIntermediate)
            {
               if (Direction[i]==-1 && Direction[i+1]==-1) 
               { 
                  SThu[i] = Low[i]; 
                  SThd[i] = High[i];
                  STbu[i] = MathMin(Open[i],Close[i]);
                  STbd[i] = MathMax(Open[i],Close[i]);
               }
               if (Direction[i]== 1 && Direction[i+1]== 1) 
               {
                  SThu[i] = High[i];
                  SThd[i] = Low[i];
                  STbu[i] = MathMax(Open[i],Close[i]);
                  STbd[i] = MathMin(Open[i],Close[i]);
               }
            }
            else
            {
               if (Direction[i] == -1) 
               {
                  SThu[i] = Low[i];
                  SThd[i] = High[i];
                  STbu[i] = MathMin(Open[i],Close[i]);
                  STbd[i] = MathMax(Open[i],Close[i]);
               }
               if (Direction[i] ==  1)
               { 
                  SThu[i] = High[i]; 
                  SThd[i] = Low[i];
                  STbu[i] = MathMax(Open[i],Close[i]);
                  STbd[i] = MathMin(Open[i],Close[i]);
               }
            }         
      }
      manageAlerts();
      return(0);
   }      

   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
      if (!noIntermediate)
      {
         if (Direction[limit] == -1 && Direction[limit+1] == -1) 
         {
            SThu[i] = Low[i];
            SThd[i] = High[i];
            STbu[i] = MathMin(Open[i],Close[i]);
            STbd[i] = MathMax(Open[i],Close[i]);
         }
         if (Direction[limit] ==  1 && Direction[limit+1] ==  1) 
         { 
            SThu[i] = High[i]; 
            SThd[i] = Low[i];
            STbu[i] = MathMax(Open[i],Close[i]);
            STbd[i] = MathMin(Open[i],Close[i]);
         }
      }
      else
      {
         if (Direction[limit] == -1) 
         {
            SThu[i] = Low[i];
            SThd[i] = High[i];
            STbu[i] = MathMin(Open[i],Close[i]);
            STbd[i] = MathMax(Open[i],Close[i]);
         }
         if (Direction[limit] ==  1)
         { 
            SThu[i] = High[i]; 
            SThd[i] = Low[i];
            STbu[i] = MathMax(Open[i],Close[i]);
            STbd[i] = MathMin(Open[i],Close[i]);
         }
      }         
   
   //
   //
   //
   //
   //
   
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
      SThu[i] = EMPTY_VALUE; 
      SThd[i] = EMPTY_VALUE;
      STbu[i] = EMPTY_VALUE;
      STbd[i] = EMPTY_VALUE;
      Trend[i]     = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CCIperiod,ATRperiod,applied_price,noIntermediate,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,4,y);
      Direction[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CCIperiod,ATRperiod,applied_price,noIntermediate,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,5,y);
      int pDir     = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",CCIperiod,ATRperiod,applied_price,noIntermediate,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,5,y+1);
         if (!noIntermediate)
         {
            if (Direction[i]==-1 && pDir==-1)
            {
              SThu[i] = Low[i];
              SThd[i] = High[i];
              STbu[i] = MathMin(Open[i],Close[i]);
              STbd[i] = MathMax(Open[i],Close[i]);
            }
            if (Direction[i]== 1 && pDir== 1) 
            { 
              SThu[i] = High[i]; 
              SThd[i] = Low[i];
              STbu[i] = MathMax(Open[i],Close[i]);
              STbd[i] = MathMin(Open[i],Close[i]);
            }
         }
         else
         {
            if (Direction[i] == -1) 
            {
              SThu[i] = Low[i];
              SThd[i] = High[i];
              STbu[i] = MathMin(Open[i],Close[i]);
              STbd[i] = MathMax(Open[i],Close[i]);
            }
            if (Direction[i] ==  1) 
            { 
              SThu[i] = High[i]; 
              SThd[i] = Low[i];
              STbu[i] = MathMax(Open[i],Close[i]);
              STbd[i] = MathMin(Open[i],Close[i]);
            }
         }         
   }
   return(0);         
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
            int forBar = 0;
      else      forBar = 1;
      
      //
      //
      //
      //
      //
      
      if (noIntermediate)
      {
         if (Direction[forBar]!=Direction[forBar+1])
         {
            if (Direction[forBar]== 1) doAlert(0,"up");
            if (Direction[forBar]==-1) doAlert(0,"down");
         }            
      }
      else
      {
         if (Direction[forBar]==Direction[forBar+1] && Direction[forBar]!=Direction[forBar+2])
         {
            if (Direction[forBar]== 1) doAlert(0,"up");
            if (Direction[forBar]==-1) doAlert(0,"down");
         }            
      }         
   }
} 

//
//
//
//
//

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)+" super trend to "+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol()," super trend"),message);
             if (alertsSound)   PlaySound("alert2.wav");
      }
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

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);
}