//------------------------------------------------------------------
#property copyright "Copyright 2016, mladen - MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//------------------------------------------------------------------
#property copyright "www,forex-station.com"
#property link      "www,forex-station.com"

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1  clrLimeGreen
#property indicator_color2  clrRed
#property indicator_width1  3
#property indicator_width2  3
#property indicator_minimum 0
#property indicator_maximum 1
#property strict

enum enCalcType
{
   st_atr, // Use atr
   st_std, // Use standard deviation 
   st_ste, // Use standard error
   st_sam, // Custom standard deviation - with sample correction
   st_nos  // Custom standard deviation - without sample correction
   
};
extern ENUM_TIMEFRAMES TimeFrame  = PERIOD_CURRENT;  // Time frame to use
extern int        period          = 66;              // Super trend period
extern double     multiplier      = 2.236;           // Super trend multiplier
extern int        midPricePeriod  = 10;              // Mid price period (1 for original super trend)
extern enCalcType Type            = st_atr;          // Calculate using?
extern bool       alertsOn        = false;           // Turn alerts on?
extern bool       alertsOnCurrent = false;           // Alerts on still opened bar?
extern bool       alertsMessage   = true;            // Alerts should display message?
extern bool       alertsSound     = false;           // Alerts should play a sound?
extern bool       alertsNotify    = false;           // Alerts should send a notification?
extern bool       alertsEmail     = false;           // Alerts should send an email?
extern string     soundFile       = "alert2.wav";    // Sound file


double UpH[],DnH[],Trend[],Direction[],Up[],Dn[],count[];
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,period,multiplier,midPricePeriod,Type,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,_buff,_ind)
string indicatorFileName;
bool   returnBars;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int OnInit()
{
   IndicatorBuffers(7);
      SetIndexBuffer(0,UpH,INDICATOR_DATA); SetIndexStyle(0,DRAW_HISTOGRAM);
      SetIndexBuffer(1,DnH,INDICATOR_DATA); SetIndexStyle(1,DRAW_HISTOGRAM);
      SetIndexBuffer(2,Up);
      SetIndexBuffer(3,Dn);
      SetIndexBuffer(4,Trend);
      SetIndexBuffer(5,Direction);
      SetIndexBuffer(6,count);
      
      indicatorFileName = WindowExpertName();
      TimeFrame         = fmax(TimeFrame,_Period);
      
   IndicatorSetString(INDICATOR_SHORTNAME,timeFrameToString(TimeFrame)+" SuperTrend");
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason) { }

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double   &open[],
                const double   &high[],
                const double   &low[],
                const double   &close[],
                const long     &tick_volume[],
                const long     &volume[],
                const int      &spread[])
{
   int i=fmin(rates_total-prev_calculated+1,rates_total-1); count[0] = i;
      if (TimeFrame != _Period)
      {
         i = (int)fmax(i,fmin(rates_total-1,_mtfCall(6,0)*TimeFrame/Period()));
         for (; i>=0 && !_StopFlag; i--)
         {
            int y = iBarShift(NULL,TimeFrame,time[i]);
            UpH[i] = _mtfCall(0,y);
            DnH[i] = _mtfCall(1,y);
         }
   return(rates_total);
   }
              
   //
   //
   //
   //
   //
   
   for (; i>=0 && !_StopFlag; i--)
   {
      double val=0;
         switch (Type)
         {
            case st_atr : val = iATR(NULL,0,period,i);                           break;
            case st_std : val = iStdDev(NULL,0,period,0,MODE_SMA,PRICE_CLOSE,i); break;
            case st_ste : val = iStdError(close[i],period,i);                    break;
            default :     val = iDeviation(close[i],period,Type==st_sam,i);
         }            
      double cprice =  close[i];
      double mprice = (high[ArrayMaximum(high,midPricePeriod,i)]+low[ArrayMinimum(low,midPricePeriod,i)])/2;
              Up[i] = mprice+multiplier*val;
              Dn[i] = mprice-multiplier*val;
         
         //
         //
         //
         //
         //
         
         Direction[i] = (i<rates_total-1) ? (cprice > Up[i+1]) ? 1 : (cprice < Dn[i+1]) ? -1 : Direction[i+1] : 0;
            if (Direction[i] ==  1) { Dn[i] = fmax(Dn[i],Dn[i+1]); Up[i] = fmax(Up[i],Up[i+1]); Trend[i] = Dn[i]; }
            if (Direction[i] == -1) { Up[i] = fmin(Up[i],Up[i+1]); Dn[i] = fmin(Dn[i],Dn[i+1]); Trend[i] = Up[i]; }
            UpH[i] = (Direction[i] == 1) ? 1 : EMPTY_VALUE;
            DnH[i] = (Direction[i] ==-1) ? 1 : EMPTY_VALUE; 
   }
   
   //
   //
   //
   //
   //
      
   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");       
      }         
   }              
   return(rates_total);
}


//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
// 
//
//
//
//

#define _devInstances 1
double workDev[][_devInstances];
double iDeviation(double value, int length, bool isSample, int i, int instanceNo=0)
{
   if (ArrayRange(workDev,0)!=Bars) ArrayResize(workDev,Bars); i=Bars-i-1; workDev[i][instanceNo] = value;
                 
   //
   //
   //
   //
   //
   
      double oldMean   = value;
      double newMean   = value;
      double squares   = 0; int k;
      for (k=1; k<length && (i-k)>=0; k++)
      {
         newMean  = (workDev[i-k][instanceNo]-oldMean)/(k+1)+oldMean;
         squares += (workDev[i-k][instanceNo]-oldMean)*(workDev[i-k][instanceNo]-newMean);
         oldMean  = newMean;
      }
      return(MathSqrt(squares/MathMax(k-isSample,1)));
}

//
//
//
//
//

double workErr[][_devInstances];
double iStdError(double value, int length,int i, int instanceNo=0)
{
   if (ArrayRange(workErr,0)!=Bars) ArrayResize(workErr,Bars); i = Bars-i-1; workErr[i][instanceNo] = value;
                        
      //
      //
      //
      //
      //
                              
      double avgY     = workErr[i][instanceNo]; int j; for (j=1; j<length && (i-j)>=0; j++) avgY += workErr[i-j][instanceNo]; avgY /= j;
      double avgX     = length * (length-1) * 0.5 / length;
      double sumDxSqr = 0.00;
      double sumDySqr = 0.00;
      double sumDxDy  = 0.00;
   
      for (int k=0; k<length && (i-k)>=0; k++)
      {
         double dx = k-avgX;
         double dy = workErr[i-k][instanceNo]-avgY;
            sumDxSqr += (dx*dx);
            sumDySqr += (dy*dy);
            sumDxDy  += (dx*dy);
      }
      double err2 = (sumDySqr-(sumDxDy*sumDxDy)/sumDxSqr)/(length-2); 
      
   //
   //
   //
   //
   //
         
   if (err2 > 0)
         return(MathSqrt(err2));
   else  return(0.00);       
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

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 state changed to "+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(_Symbol+" super trend ",message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}
