//------------------------------------------------------------------
//
//------------------------------------------------------------------
// See: https://www.mql5.com/en/forum/181241/page55

#property copyright "mladen"
#property link      "www.forex-tsd.com"

#property indicator_chart_window
#property indicator_buffers 5
#property indicator_color1 LimeGreen
#property indicator_color2 Red
#property indicator_color3 Orange
#property indicator_color4 Orange
#property indicator_color5 Orange
#property indicator_width1 2
#property indicator_width2 2
#property indicator_width3 2
#property indicator_style4 STYLE_DOT
#property indicator_style5 STYLE_DOT

//
//
//
//
//

extern string TimeFrame                 = "Current time frame";
extern int    HalfLength                = 20;
extern int    Price                     = PRICE_CLOSE;
extern double ATRMultiplier             = 2.0;
extern int    ATRPeriod                 = 100;
extern bool   Extrapolate               = true;
extern bool   Interpolate               = true;

extern string _                         = "Alerts Settings";
extern bool   alertsOn                  = false;
extern bool   alertsOnSlope             = false;
extern bool   alertsOnHighLowPriceCross = false;
extern bool   alertsOnClosePriceCross   = false;
extern bool   alertsOnCurrent           = false;
extern bool   alertsMessage             = true;
extern bool   alertsSound               = false;
extern bool   alertsNotify              = true;
extern bool   alertsEmail               = true;
extern string soundFile                 = "alert2.wav"; 

double buffer1[];
double buffer2a[];
double buffer2b[];
double bandUp[];
double bandDn[];
double slope[];
double trend1[];
double trend2[];

string indicatorFileName;
int    timeFrame;
bool   returnBars;
bool   calculateValue;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//

int init()
{
   HalfLength=MathMax(HalfLength,1);
   IndicatorBuffers(8);
   SetIndexBuffer(0,buffer1);  SetIndexDrawBegin(0,HalfLength);
   SetIndexBuffer(1,buffer2a); SetIndexDrawBegin(1,HalfLength);
   SetIndexBuffer(2,buffer2b); SetIndexDrawBegin(2,HalfLength);
   SetIndexBuffer(3,bandUp);   SetIndexDrawBegin(3,HalfLength);
   SetIndexBuffer(4,bandDn);   SetIndexDrawBegin(4,HalfLength);
   SetIndexBuffer(5,slope);
   SetIndexBuffer(6,trend1);
   SetIndexBuffer(7,trend2);
        indicatorFileName = WindowExpertName();
        calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
        returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
        timeFrame         = stringToTimeFrame(TimeFrame);
   return(0);
}
int deinit() { return(0); }




//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,j,k,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-counted_bars+HalfLength,Bars-1);
            if (returnBars) { buffer1[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame==Period())
   {
      if (slope[limit]==-1) CleanPoint(limit,buffer2a,buffer2b);
      int iArraySize_slope = ArraySize(slope);
      for (i=limit;i>=0;i--)
      {
         if ((i+1) > (iArraySize_slope-1))
            continue;
         if (Extrapolate || (!Extrapolate && i>HalfLength))
         {
            double sum  = (HalfLength+1)*iMA(NULL,0,1,0,MODE_SMA,Price,i);
            double sumw = (HalfLength+1);
            for(j=1, k=HalfLength; j<=HalfLength; j++, k--)
            {
               sum  += k*iMA(NULL,0,1,0,MODE_SMA,Price,i+j);
               sumw += k;
               if (j<=i)
               {
                  sum  += k*iMA(NULL,0,1,0,MODE_SMA,Price,i-j);
                  sumw += k;
               }
            }
            double range = iATR(NULL,0,ATRPeriod,i+10)*ATRMultiplier;
            buffer1[i] = sum/sumw;  
            bandUp[i]  = buffer1[i]+range;
            bandDn[i]  = buffer1[i]-range;
         }
         else
         {
            buffer1[i] = buffer1[i+1];  
            bandUp[i]  = bandUp[i+1];  
            bandDn[i]  = bandDn[i+1];  
         }         
         buffer2a[i] = EMPTY_VALUE;
         buffer2b[i] = EMPTY_VALUE;
         slope[i]    = slope[i+1];
         trend1[i]   = trend1[i+1];
         trend2[i]   = trend2[i+1];
            if (buffer1[i]> buffer1[i+1]) slope[i]  = 1;
            if (buffer1[i]< buffer1[i+1]) slope[i]  =-1;
            if (High[i]   > bandUp[i])    trend1[i] = 1;
            if (Low[i]    < bandDn[i])    trend1[i] =-1;
            if (Close[i]  > bandUp[i])    trend2[i] = 1;
            if (Close[i]  < bandDn[i])    trend2[i] =-1;
            if (slope[i]==-1) PlotPoint(i,buffer2a,buffer2b,buffer1);
      }
      manageAlerts();
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (slope[limit]==-1) CleanPoint(limit,buffer2a,buffer2b);
   for (i=limit;i>=0; i--)
   {
       int y = iBarShift(NULL,timeFrame,Time[i]);
            buffer1[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",HalfLength,Price,ATRMultiplier,ATRPeriod,Extrapolate,0,y);
            bandUp[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",HalfLength,Price,ATRMultiplier,ATRPeriod,Extrapolate,3,y);
            bandDn[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",HalfLength,Price,ATRMultiplier,ATRPeriod,Extrapolate,4,y);
            slope[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",HalfLength,Price,ATRMultiplier,ATRPeriod,Extrapolate,5,y);
            trend1[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",HalfLength,Price,ATRMultiplier,ATRPeriod,Extrapolate,6,y);
            trend2[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",HalfLength,Price,ATRMultiplier,ATRPeriod,Extrapolate,7,y);
            buffer2a[i] = EMPTY_VALUE;
            buffer2b[i] = EMPTY_VALUE;
         if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(int m = 1; m < n; m++)
            {
               buffer1[i+m] = buffer1[i] + (buffer1[i+n]-buffer1[i])*m/n;
               bandUp[i+m]  = bandUp[i]  + (bandUp[i+n] -bandUp[i] )*m/n;
               bandDn[i+m]  = bandDn[i]  + (bandDn[i+n] -bandDn[i] )*m/n;
            }
   }
   manageAlerts();
   for (i=limit;i>=0; i--) if (slope[i]==-1) PlotPoint(i,buffer2a,buffer2b,buffer1);            
   return(0);   
            
}

//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar)); 

      //
      //
      //
      //
      //
            
      static datetime time1 = 0;
      static string   mess1 = "";
      if (alertsOnSlope && slope[whichBar] != slope[whichBar+1])
      {
         if (slope[whichBar] ==  1) doAlert(time1,mess1,whichBar,"Sloping up");
         if (slope[whichBar] == -1) doAlert(time1,mess1,whichBar,"Sloping down");
      }
      
      static datetime time2 = 0;
      static string   mess2 = "";
      if (alertsOnHighLowPriceCross && trend1[whichBar] != trend1[whichBar+1])
      {
         if (trend1[whichBar] ==  1) doAlert(time2,mess2,whichBar,"High price crossed upper band");
         if (trend1[whichBar] == -1) doAlert(time2,mess2,whichBar,"Low price crossed lower band");
      }
      
      static datetime time3 = 0;
      static string   mess3 = "";
      if (alertsOnClosePriceCross && trend2[whichBar] != trend2[whichBar+1])
      {
         if (trend2[whichBar] ==  1) doAlert(time3,mess3,whichBar,"Close price crossed upper band");
         if (trend2[whichBar] == -1) doAlert(time3,mess3,whichBar,"Close price crossed lower band");
      }
      
   }
}

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, int forBar, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," TMAcentered & bands currently ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsNotify)  SendNotification(StringConcatenate(Symbol(), Period() ," TMAcentered & bands " +" "+message));
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," TMAcentered & bands "),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[])
{
   int iArraySize_first = ArraySize(first);
   if ((i+2) > (iArraySize_first-1))
      return;
      
   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)
{
   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);
}