//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  LimeGreen
#property indicator_color2  PaleVioletRed
#property indicator_color3  LimeGreen
#property indicator_color4  PaleVioletRed
#property indicator_width3  2
#property indicator_width4  2

//
//
//
//
//

extern string TimeFrame          = "Current time frame";
extern double Nbr_Periods        = 2.5;
extern double Multiplier         = 2.0;
extern bool   ShowText           = true;
extern bool   alertsOn           = false;
extern bool   alertsOnCurrent    = false;
extern bool   alertsMessage      = true;
extern bool   alertsNotification = true;
extern bool   alertsSound        = false;
extern bool   alertsEmail        = false;
extern int    TextPositionX      = 630;
extern int    TextPositionY      = 15;
extern color  upTextcolor        = Blue;
extern color  dnTextcolor        = Red;
extern int    Fontsize           = 9;

//
//
//
//
//

double SThu[];
double SThd[];
double STbu[];
double STbd[];
double Up[];
double Dn[];
double Direction[];
string TextDir = "ST2";


string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(7);
      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,Up);
      SetIndexBuffer(5,Dn);
      SetIndexBuffer(6,Direction);
      
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
       
      //
      //
      //
      //
      //
      
      IndicatorShortName(timeFrameToString(timeFrame)+" SuperTrend");
     

  return(0);

}

int deinit() 
{ 
   ObjectDelete(TextDir);return(0); 
}
//
//
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

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) { SThu[0] = limit+1; return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame==Period())
   {
      for(int i=limit; i>=0; i--)
      {
         double atr    = iATR(NULL,0,Nbr_Periods,i);
         double cprice = Close[i];
         double mprice = iMA(NULL,0,1,0,MODE_SMA,PRICE_MEDIAN,i);
                Up[i]  = mprice+Multiplier*atr;
                Dn[i]  = mprice-Multiplier*atr;
         
         //
         //
         //
         //
         //

         SThu[i] = EMPTY_VALUE; 
         SThd[i] = EMPTY_VALUE;
         STbu[i] = EMPTY_VALUE;
         STbd[i] = EMPTY_VALUE;
         Direction[i] = Direction[i+1];
            if (cprice > Up[i+1])  Direction[i] =  1;
            if (cprice < Dn[i+1])  Direction[i] = -1;
            if (Direction[i] > 0) { Dn[i] = MathMax(Dn[i],Dn[i+1]); }
            else                  { Up[i] = MathMin(Up[i],Up[i+1]); }
            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]);
            } 
            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[0]== 1) Commenter( 1);  
      if (Direction[0]==-1) Commenter(-1); 
      manageAlerts();
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for (i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         Direction[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Nbr_Periods,Multiplier,ShowText,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,TextPositionX,TextPositionY,upTextcolor,dnTextcolor,Fontsize,6,y);
         SThu[i] = EMPTY_VALUE; 
         SThd[i] = EMPTY_VALUE;
         STbu[i] = EMPTY_VALUE;
         STbd[i] = EMPTY_VALUE;
         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]);
         } 
         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]);
         }
   }
   return(0);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar=0;
      if (Direction[whichBar] != Direction[whichBar+1])
      {
         if (Direction[whichBar] ==  1) doAlert("up"  );
         if (Direction[whichBar] == -1) doAlert("down");
      }
   }
}

//
//
//
//
//

void doAlert(string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[0]) {
       previousAlert  = doWhat;
       previousTime   = Time[0];

       //
       //
       //
       //
       //

       message =  timeFrameToString(Period())+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" super trend changed to "+doWhat;
          if (alertsMessage)      Alert(message);
          if (alertsEmail)        SendMail(Symbol()+" super trend",message);
          if (alertsNotification) SendNotification(message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M10","M15","M30","H1","H2","H3","H4","H8","D1","W1","MN"};
int    iTfTable[] = {1,5,10,15,30,60,120,180,240,480,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 Commenter(int Dir) 
{
    if (ShowText)
    {
      ObjectCreate(TextDir,OBJ_LABEL,0,0,0);
      ObjectSet(TextDir,OBJPROP_XDISTANCE,TextPositionX);
      ObjectSet(TextDir,OBJPROP_YDISTANCE,TextPositionY);
      if (Dir == 1) ObjectSetText(TextDir,"STREND BUY",Fontsize,"Arial Black", upTextcolor);
      if (Dir ==-1) ObjectSetText(TextDir,"STREND SELL",Fontsize,"Arial Black",dnTextcolor);
   }
   
return; 
}



