//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 6
#property indicator_color1  Lime
#property indicator_color2  Orange
#property indicator_color3  Orange
#property indicator_color4  LimeGreen
#property indicator_color5  Tomato
#property indicator_color6  Tomato
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_width4  2
#property indicator_width5  2
#property indicator_width6  2

//
//
//
//
//

extern string TimeFrame       = "Current time frame";
extern double T3Period        =  14;
extern int    T3Price         =  PRICE_CLOSE;
extern double T3Hot           =  0.7;
extern bool   T3Original      = true;
extern int    AdaptPeriod     =  25;
extern double T3Period2       =  21;
extern int    T3Price2        =  PRICE_CLOSE;
extern double T3Hot2          =  0.7;
extern bool   T3Original2     = true;
extern int    AdaptPeriod2    =  25;
extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = false;
extern bool   alertsMessage   = true;
extern bool   alertsPushNotif = false;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;
extern bool   Interpolate     = true;

//
//
//
//
//

double Buffer[];
double Bufferda[];
double Bufferdb[];
double Buffet[];
double Buffetda[];
double Buffetdb[];
double slope[];
double slopt[];

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,Buffer);
   SetIndexBuffer(1,Bufferda);
   SetIndexBuffer(2,Bufferdb);
   SetIndexBuffer(3,Buffet);
   SetIndexBuffer(4,Buffetda);
   SetIndexBuffer(5,Buffetdb);
   SetIndexBuffer(6,slope);
   SetIndexBuffer(7,slopt);
   
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" "+"adaptive T3 ("+T3Period+","+AdaptPeriod+")");
   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 = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { Buffer[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
      if (slope[limit]==-1) CleanPoint(limit,Bufferda,Bufferdb);
      if (slopt[limit]==-1) CleanPoint(limit,Buffetda,Buffetdb);
      for(int i=limit; i >= 0; i--)
      {
         double dev = iStdDev(NULL,0,AdaptPeriod,0,MODE_SMA,T3Price,i);
         double avg = iSma(dev,AdaptPeriod,i,0);
         if (dev!=0) 
                double period = T3Period*avg/dev;
         else          period = T3Period; 
         if (period<3) period = 3;
         Buffer[i] = iT3(iMA(NULL,0,1,0,MODE_SMA,T3Price,i),period,T3Hot,T3Original,i,0);           
         
         //
         //
         //
         //
         //
         
         dev = iStdDev(NULL,0,AdaptPeriod2,0,MODE_SMA,T3Price,i);
         avg = iSma(dev,AdaptPeriod2,i,0);
         if (dev!=0) 
                period = T3Period2*avg/dev;
         else   period = T3Period2; 
         if (period<3) period = 3;
         Buffet[i] = iT3(iMA(NULL,0,1,0,MODE_SMA,T3Price2,i),period,T3Hot2,T3Original2,i,1);           
           
         //
         //
         //
         //
         //
                 
         Bufferda[i] = EMPTY_VALUE;
         Bufferdb[i] = EMPTY_VALUE;
         Buffetda[i] = EMPTY_VALUE;
         Buffetdb[i] = EMPTY_VALUE;
         slope[i] = slope[i+1];
         slopt[i] = slopt[i+1];
            if (Buffer[i]>Buffer[i+1]) slope[i] =  1;
            if (Buffer[i]<Buffer[i+1]) slope[i] = -1;
            if (Buffet[i]>Buffet[i+1]) slopt[i] =  1;
            if (Buffet[i]<Buffet[i+1]) slopt[i] = -1;
            if (slope[i] == -1) PlotPoint(i,Bufferda,Bufferdb,Buffer);
            if (slopt[i] == -1) PlotPoint(i,Buffetda,Buffetdb,Buffet);
      }         
      manageAlerts();
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (slope[limit]==-1) CleanPoint(limit,Bufferda,Bufferdb);
   if (slopt[limit]==-1) CleanPoint(limit,Buffetda,Buffetdb);
   for (i=limit; i>=0; i--)
   {
       int y = iBarShift(NULL,timeFrame,Time[i]);               
          slope[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",T3Period,T3Price,T3Hot,T3Original,AdaptPeriod,T3Period2,T3Price2,T3Hot2,T3Original2,AdaptPeriod2,alertsOn,alertsOnCurrent,alertsMessage,alertsPushNotif,alertsSound,alertsEmail,6,y);
          slopt[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",T3Period,T3Price,T3Hot,T3Original,AdaptPeriod,T3Period2,T3Price2,T3Hot2,T3Original2,AdaptPeriod2,alertsOn,alertsOnCurrent,alertsMessage,alertsPushNotif,alertsSound,alertsEmail,7,y);
          Buffer[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",T3Period,T3Price,T3Hot,T3Original,AdaptPeriod,T3Period2,T3Price2,T3Hot2,T3Original2,AdaptPeriod2,alertsOn,alertsOnCurrent,alertsMessage,alertsPushNotif,alertsSound,alertsEmail,0,y);
          Buffet[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",T3Period,T3Price,T3Hot,T3Original,AdaptPeriod,T3Period2,T3Price2,T3Hot2,T3Original2,AdaptPeriod2,alertsOn,alertsOnCurrent,alertsMessage,alertsPushNotif,alertsSound,alertsEmail,3,y);
          Bufferda[i] = EMPTY_VALUE;
          Bufferdb[i] = EMPTY_VALUE;
          Buffetda[i] = EMPTY_VALUE;
          Buffetdb[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 x = 1; x < n; x++)
                {
                   Buffer[i+x] = Buffer[i] + (Buffer[i+n] - Buffer[i]) * x/n;
                   Buffet[i+x] = Buffet[i] + (Buffet[i+n] - Buffet[i]) * x/n;
                }                   
   }
   for (i=limit; i>=0; i--)
   {
      if (slope[i] == -1) PlotPoint(i,Bufferda,Bufferdb,Buffer);
      if (slopt[i] == -1) PlotPoint(i,Buffetda,Buffetdb,Buffet);
   }      
   return(0);
}


//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; 
      static datetime time1 = 0;
      static string   mess1 = "";
      if (slope[whichBar] != slope[whichBar+1])
      {
         if (slope[whichBar] ==  1) doAlert(time1,mess1,"slope of first adaptive T3 changed to up");
         if (slope[whichBar] == -1) doAlert(time1,mess1,"slope of first adaptive T3 changed to down");
      }
      static datetime time2 = 0;
      static string   mess2 = "";
      if (slopt[whichBar] != slopt[whichBar+1])
      {
         if (slopt[whichBar] ==  1) doAlert(time2,mess2,"slope of second adaptive T3 changed to up");
         if (slopt[whichBar] == -1) doAlert(time2,mess2,"slope of second adaptive T3 changed to down");
      }
   }
}

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[0]) {
       previousAlert  = doWhat;
       previousTime   = Time[0];

       //
       //
       //
       //
       //

       message = timeFrameToString(Period())+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+doWhat;
          if (alertsMessage)   Alert(message);
          if (alertsEmail)     SendMail(StringConcatenate(Symbol()," Adaptive T3"),message);
          if (alertsPushNotif) SendNotification(message);
          if (alertsSound)     PlaySound("alert2.wav");
   }
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//
//

double workSma[][2];
double iSma(double price, int period, int r, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= Bars) ArrayResize(workSma,Bars); instanceNo *= 2; r = Bars-r-1;

   //
   //
   //
   //
   //
      
   workSma[r][instanceNo] = price;
   if (r>=period)
          workSma[r][instanceNo+1] = workSma[r-1][instanceNo+1]+(workSma[r][instanceNo]-workSma[r-period][instanceNo])/period;
   else { workSma[r][instanceNo+1] = 0; for(int k=0; k<period && (r-k)>=0; k++) workSma[r][instanceNo+1] += workSma[r-k][instanceNo];  
          workSma[r][instanceNo+1] /= k; }
   return(workSma[r][instanceNo+1]);
}

//
//
//
//
//

double workT3[][12];
double workT3Coeffs[][6];
#define _period 0
#define _c1     1
#define _c2     2
#define _c3     3
#define _c4     4
#define _alpha  5

//
//
//
//
//

double iT3(double price, double period, double hot, bool original, int i, int instanceNo=0)
{
   if (ArrayRange(workT3,0) !=Bars)                 ArrayResize(workT3,Bars);
   if (ArrayRange(workT3Coeffs,0) < (instanceNo+1)) ArrayResize(workT3Coeffs,instanceNo+1);

   if (workT3Coeffs[instanceNo][_period] != period)
   {
     workT3Coeffs[instanceNo][_period] = period;
        double a = hot;
            workT3Coeffs[instanceNo][_c1] = -a*a*a;
            workT3Coeffs[instanceNo][_c2] = 3*a*a+3*a*a*a;
            workT3Coeffs[instanceNo][_c3] = -6*a*a-3*a-3*a*a*a;
            workT3Coeffs[instanceNo][_c4] = 1+3*a+a*a*a+3*a*a;
            if (original)
                 workT3Coeffs[instanceNo][_alpha] = 2.0/(1.0 + period);
            else workT3Coeffs[instanceNo][_alpha] = 2.0/(2.0 + (period-1.0)/2.0);
   }
   
   //
   //
   //
   //
   //
   
   int buffer = instanceNo*6;
   int r = Bars-i-1;
   if (r == 0)
      {
         workT3[r][0+buffer] = price;
         workT3[r][1+buffer] = price;
         workT3[r][2+buffer] = price;
         workT3[r][3+buffer] = price;
         workT3[r][4+buffer] = price;
         workT3[r][5+buffer] = price;
      }
   else
      {
         workT3[r][0+buffer] = workT3[r-1][0+buffer]+workT3Coeffs[instanceNo][_alpha]*(price              -workT3[r-1][0+buffer]);
         workT3[r][1+buffer] = workT3[r-1][1+buffer]+workT3Coeffs[instanceNo][_alpha]*(workT3[r][0+buffer]-workT3[r-1][1+buffer]);
         workT3[r][2+buffer] = workT3[r-1][2+buffer]+workT3Coeffs[instanceNo][_alpha]*(workT3[r][1+buffer]-workT3[r-1][2+buffer]);
         workT3[r][3+buffer] = workT3[r-1][3+buffer]+workT3Coeffs[instanceNo][_alpha]*(workT3[r][2+buffer]-workT3[r-1][3+buffer]);
         workT3[r][4+buffer] = workT3[r-1][4+buffer]+workT3Coeffs[instanceNo][_alpha]*(workT3[r][3+buffer]-workT3[r-1][4+buffer]);
         workT3[r][5+buffer] = workT3[r-1][5+buffer]+workT3Coeffs[instanceNo][_alpha]*(workT3[r][4+buffer]-workT3[r-1][5+buffer]);
      }

   //
   //
   //
   //
   //
   
   return(workT3Coeffs[instanceNo][_c1]*workT3[r][5+buffer] + 
          workT3Coeffs[instanceNo][_c2]*workT3[r][4+buffer] + 
          workT3Coeffs[instanceNo][_c3]*workT3[r][3+buffer] + 
          workT3Coeffs[instanceNo][_c4]*workT3[r][2+buffer]);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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)
{
   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);
}