//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1  LimeGreen
#property indicator_width1  2

//
//
//
//
//

extern string TimeFrame       = "Current time frame";
extern string T3Periods       = "14;17;20;23;26;29;32;35";
extern string T3Hots          = "0.7;0.7;0.7;0.7;0.7;0.7;0.7;0.7";
extern string T3AdaptPeriods  = "25;25;25;25;25;25;25;25";
extern string T3Originals     = "T;T;T;T;T;T;T;T";
extern int    T3Price         = PRICE_CLOSE;
extern bool   Interpolate     = true;

//
//
//
//
//

double Buffer0[];

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

int    size;
bool   originals[];
double aperiods[];
double periods[];
double hots[];

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

int init()
{
   SetIndexBuffer(0,Buffer0);

      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);


      //
      //
      //
      //
      //
         
         if (StringSubstr(T3Periods,StringLen(T3Periods)-1,1) != ";")
                          T3Periods = StringConcatenate(T3Periods,";");
            int s = 0;
            int i = StringFind(T3Periods,";",s);
            int current;
               while (i > 0)
               {
                  current = StrToDouble(StringSubstr(T3Periods,s,i-s));
                  if (current > 0) {
                        ArrayResize(periods,ArraySize(periods)+1);
                                    periods[ArraySize(periods)-1] = current; }
                                    s = i + 1;
                                        i = StringFind(T3Periods,";",s);
               }
               size = MathMin(ArraySize(periods),8);

         //
         //
         //
         //
         //
      
         if (StringSubstr(T3AdaptPeriods,StringLen(T3AdaptPeriods)-1,1) != ";")
                          T3AdaptPeriods = StringConcatenate(T3AdaptPeriods,";");
            s = 0;
            i = StringFind(T3AdaptPeriods,";",s);
               while (i > 0)
               {
                  current = StrToDouble(StringSubstr(T3AdaptPeriods,s,i-s));
                  if (current > 0) {
                        ArrayResize(aperiods,ArraySize(aperiods)+1);
                                    aperiods[ArraySize(aperiods)-1] = current; }
                                    s = i + 1;
                                        i = StringFind(T3AdaptPeriods,";",s);
               }
      
         //
         //
         //
         //
         //
      
         if (StringSubstr(T3Hots,StringLen(T3Hots)-1,1) != ";")
                          T3Hots = StringConcatenate(T3Hots,";");
            s = 0;
            i = StringFind(T3Hots,";",s);
               while (i > 0)
               {
                  double currend = StrToDouble(StringSubstr(T3Hots,s,i-s));
                  if (currend > 0) {
                        ArrayResize(hots,ArraySize(hots)+1);
                                    hots[ArraySize(hots)-1] = currend; }
                                    s = i + 1;
                                        i = StringFind(T3Hots,";",s);
               }

         //
         //
         //
         //
         //
      
         if (StringSubstr(T3Originals,StringLen(T3Originals)-1,1) != ";")
                          T3Originals = stringUpperCase(StringConcatenate(T3Originals,";"));
            s = 0;
            i = StringFind(T3Originals,";",s);
               while (i > 0)
               {
                  string currens = StringSubstr(T3Originals,s,i-s);
                  if (currens == "F" || currens == "T") {
                        ArrayResize(originals,ArraySize(originals)+1);
                                    originals[ArraySize(originals)-1] = (currens=="T"); }
                                    s = i + 1;
                                        i = StringFind(T3Originals,";",s);
               }
   
      //
      //
      //
      //
      //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" "+"adaptive T3 rainbow");
   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) { Buffer0[0] = MathMin(limit+1,Bars-1); return(0); }

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

   if (calculateValue || timeFrame == Period())
   {
      for(int i=limit; i >= 0; i--)
      {
         double sum = 0;
         for (int k=0; k<size; k++)
         {
            double dev = iStdDev(NULL,0,aperiods[k],0,MODE_SMA,T3Price,i);
            double avg = iSma(dev,aperiods[k],i,k);
            if (dev!=0) 
                   double period = periods[k]*avg/dev;
            else          period = periods[k];
            if (period<3) period = 3;
            
            //
            //
            //
            //
            //

            sum += iT3(iMA(NULL,0,1,0,MODE_SMA,T3Price,i),period,hots[k],originals[k],i,k);
         }      
         if (k>0) Buffer0[i] =  sum/k;       
      }         
      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]);               
          Buffer0[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",T3Periods,T3Hots,T3AdaptPeriods,T3Originals,T3Price,0,y);
            
          //
          //
          //
          //
          //
       
          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++)
                {
                   if (Buffer0[i]!=EMPTY_VALUE) Buffer0[i+x] = Buffer0[i] + (Buffer0[i+n] - Buffer0[i]) * x/n;
                }                   
   }
   return(0);
}



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

double workSma[][16];
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[][48];
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]);
}

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

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