//+------------------------------------------------------------------+
//|                                               SuperTrend nrp.mq4 |
//|                                                                  |
//| original Super trend for metatrader made by Jason Robinson       |
//| calculation correction, repainting solving and mtf by mladen     |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_chart_window
#property indicator_buffers 5
#property indicator_color1 DeepSkyBlue
#property indicator_color2 PaleVioletRed
#property indicator_color3 DeepSkyBlue
#property indicator_color4 PaleVioletRed
#property indicator_color5 PaleVioletRed
#property indicator_width3 2
#property indicator_width4 2
#property indicator_width5 2

//
//
//
//
//

extern string TimeFrame        = "Current time frame";
extern int    CciPeriod        = 50;
extern bool   OldCalculation   = false;
extern bool   Interpolate      = true;
extern bool   DrawColorLines   = true;
extern bool   DrawColorBars    = true;

extern string _                = "alerts settings";
extern bool   alertsOn         = false;
extern bool   alertsOnCurrent  = false;
extern bool   alertsMessage    = true;
extern bool   alertsSound      = false;
extern bool   alertsEmail      = false;

extern string LabelID          = "SuperTrendBars1";
extern string LabelText        = "Super trend bars";
extern color  LabelColor       = DarkGray;
extern string LabelFontName    = "Arial";
extern int    LabelFontSize    = 10;
extern int    LabelShift       = 15;

//
//
//
//
//

double STrend[];
double STrendHu[];
double STrendHd[];
double STrendDoA[];
double STrendDoB[];
double Trend[];

//
//
//
//
//

int    timeFrame;
string IndicatorFileName;
bool   ReturningBars;
bool   CalculatingStr;
double UpDownShift;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   int style = DRAW_NONE; if (DrawColorBars) style = DRAW_HISTOGRAM;
   IndicatorBuffers(6);
      SetIndexBuffer(0, STrendHu);  SetIndexStyle(0,style); SetIndexLabel(0,"SuperTrend");
      SetIndexBuffer(1, STrendHd);  SetIndexStyle(1,style); SetIndexLabel(1,"SuperTrend");
      
      style = DRAW_NONE; if (DrawColorLines) style = DRAW_LINE;
      
      SetIndexBuffer(2, STrend);    SetIndexStyle(2,style); SetIndexLabel(2,"SuperTrend");
      SetIndexBuffer(3, STrendDoA); SetIndexStyle(3,style); SetIndexLabel(3,"SuperTrend");
      SetIndexBuffer(4, STrendDoB); SetIndexStyle(4,style); SetIndexLabel(4,"SuperTrend");
      SetIndexBuffer(5, Trend);

      //
      //
      //
      //
      //
         
         IndicatorFileName = WindowExpertName();
         CalculatingStr    = (TimeFrame=="CalculateStr"); if (CalculatingStr) return(0);
         ReturningBars     = (TimeFrame=="returnBars");   if (ReturningBars)  return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
         
         //
         //
         //
         //
         //
         
         if (OldCalculation)
         {
            switch(Period())
            {
               case 1:     UpDownShift = 3;   break;
               case 5:     UpDownShift = 5;   break;
               case 15:    UpDownShift = 7;   break;
               case 30:    UpDownShift = 9;   break;
               case 60:    UpDownShift = 20;  break;
               case 240:   UpDownShift = 35;  break;
               case 1440:  UpDownShift = 40;  break;
               case 10080: UpDownShift = 100; break;
               case 43200: UpDownShift = 120; break;
            }
            UpDownShift *= Point;
            if (Digits==3 || Digits==5)
               UpDownShift *= 10.0;
         }            
         
   
      //
      //
      //
      //
      //
   
   IndicatorShortName("SuperTrend "+timeFrameToString(timeFrame));    
   return(0);
}
int deinit()
{
   ObjectDelete(LabelID);
   return(0);
}




//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars = IndicatorCounted();
   int limit,i;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         if (ReturningBars) { STrend[0] = limit+1; return(0); }
   //
   //
   //
   //
   //

   if (CalculatingStr || timeFrame==Period())
   {      
      if (!CalculatingStr && Trend[limit]==-1) CleanPoint(limit,STrendDoA,STrendDoB);
      for(i=limit; i>=0; i--)
      {
         double cciTrend = iCCI(NULL, 0, CciPeriod, PRICE_TYPICAL, i);
         
         //
         //
         //
         //
         //
         
         STrendDoA[i] = EMPTY_VALUE;
         STrendDoB[i] = EMPTY_VALUE;
         Trend[i]     = Trend[i+1];
            if (cciTrend > 0)    Trend[i]    =  1;
            if (cciTrend < 0)    Trend[i]    = -1;
            if (!OldCalculation) UpDownShift =  iATR(NULL,0,5,i);
            if (Trend[i] ==  1) { STrend[i] = MathMax(Low[i]  - UpDownShift,STrend[i+1]); STrendHu[i] = High[i];  STrendHd[i] = Low[i]; }
            if (Trend[i] == -1) { STrend[i] = MathMin(High[i] + UpDownShift,STrend[i+1]); STrendHd[i] = High[i];  STrendHu[i] = Low[i]; }
            
            //
            //
            //
            //
            //
            
            if (!CalculatingStr && Trend[i] == -1) PlotPoint(i,STrendDoA,STrendDoB,STrend);
            manageAlerts();
      }
      setLabel();
      return(0);
   }

   //
   //
   //
   //
   //
   
   if (timeFrame > Period()) limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,IndicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (Trend[limit] == -1) CleanPoint(limit,STrendDoA,STrendDoB);

   for (i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         Trend[i]     = iCustom(NULL,timeFrame,IndicatorFileName,"CalculateStr",CciPeriod,OldCalculation,5,y);
         STrend[i]    = iCustom(NULL,timeFrame,IndicatorFileName,"CalculateStr",CciPeriod,OldCalculation,2,y);
         STrendDoA[i] = EMPTY_VALUE;
         STrendDoB[i] = EMPTY_VALUE;
            if (Trend[i] ==  1) { STrendHu[i] = High[i];  STrendHd[i] = Low[i]; }
            if (Trend[i] == -1) { STrendHd[i] = High[i];  STrendHu[i] = Low[i]; }

         //
         //
         //
         //
         //
      
         if (timeFrame <= Period() || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
         if (!Interpolate) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            double factor = 1.0 / n;
            for(int k = 1; k < n; k++) STrend[i+k] = k*factor*STrend[i+n] + (1.0-k*factor)*STrend[i];
   }
   for (i=limit;i>=0;i--) if (Trend[i] == -1) PlotPoint(i,STrendDoA,STrendDoB,STrend);
   manageAlerts(); setLabel();
   
   //
   //
   //
   //
   //
   return(0);
}



void setLabel()
{
   if (!CalculatingStr)
   {
      if (ObjectFind(LabelID)<0) 
          ObjectCreate(LabelID,OBJ_TEXT,0,0,0,0);
             ObjectSet(LabelID,OBJPROP_COLOR,LabelColor);
             ObjectSet(LabelID,OBJPROP_PRICE1,STrend[0]);
             ObjectSet(LabelID,OBJPROP_TIME1,Time[0]+Period()*LabelShift*60);
             ObjectSetText(LabelID,LabelText,LabelFontSize,LabelFontName,LabelColor);
   }
}

void manageAlerts()
{
   if (!CalculatingStr && 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,"up");
         if (Trend[whichBar] == -1) doAlert(whichBar,"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 =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," SuperTrend changed direction to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," SuperTrend "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

//
//
//
//
//

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (first[i+1] == EMPTY_VALUE)
      {
      if (first[i+2] == EMPTY_VALUE) {
          first[i]    = from[i];
          first[i+1]  = from[i+1];
          second[i]   = EMPTY_VALUE;
         }
      else {
          second[i]   = from[i];
          second[i+1] = from[i+1];
          first[i]    = EMPTY_VALUE;
         }
      }
   else
      {
         first[i]   = from[i];
         second[i]  = EMPTY_VALUE;
      }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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)
{
   StringToUpper(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("");
}
