//+------------------------------------------------------------------+
//|                                           Chandes Trendscore.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers    1
#property indicator_color1     Red
#property indicator_maximum    1.05
#property indicator_minimum    -1.05
#property indicator_levelcolor MediumOrchid

//
//
//
//
//

extern string  TimeFrame        = "Current time frame";
extern int     LookBack         = 20;
extern int     LookBackLength   = 20;
extern int     T3Period         = 10;
extern double  T3Hot            = 0.618;
extern bool    T3Original       = false;
extern bool    T3Adaptive       = true;
extern double  levelOs          = -0.90;
extern double  levelOb          = 0.90; 
extern bool    Interpolate      = true;

extern string  _                = "alerts settings";
extern bool    alertsOn         = true;
extern bool    alertsOnCurrent  = true;
extern bool    alertsMessage    = true;
extern bool    alertsSound      = false;
extern bool    alertsEmail      = false;

extern string  __               = "arrows settings";
extern bool    ShowArrows       = true;
extern string  arrowsIdentifier = "adaptive ct arrows";
extern color   arrowsUpColor    = Lime;
extern color   arrowsDnColor    = Orange;


//
//
//
//
//

double TrendBuffer[];
double trend[];

//
//
//
//
//

string indicatorFileName;
bool   calculateValue;
bool   returnBars;
int    timeFrame;

//
//
//
//
//
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

int init()
{
    for (int i=0; i<indicator_buffers; i++) SetIndexStyle(i,DRAW_LINE);
    IndicatorBuffers(2);
    SetIndexBuffer(0,TrendBuffer); SetIndexLabel(0,"Trend score");
    SetIndexBuffer(1,trend);
    
    SetLevelValue(0,levelOs);
    SetLevelValue(1,levelOb);

   
     //
     //
     //
     //
     //
     
        indicatorFileName = WindowExpertName();
        calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
        returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
        timeFrame         = stringToTimeFrame(TimeFrame);   
     
     //
     //
     //
     //
     //
     
    IndicatorShortName(timeFrameToString(timeFrame)+"   adaptive T3 Chande Trendscore ("+LookBack+","+LookBackLength+")");
   
return(0);
}

//
//
//
//
//

int deinit(){  if (!calculateValue && ShowArrows) deleteArrows();  return(0); }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int    counted_bars=IndicatorCounted();
   int    limit,i,n,j,k;


   if(counted_bars < 0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1); 
         if (returnBars) { TrendBuffer[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
   for (i=limit;i>=0;i--)
       {
         double score = 0;
         
         for (k=0; k<LookBackLength; k++)
         {
                  if (Close[i] >= Close[i+k+LookBack])
                        score++;
                  else  score--;
         }
                                          
         TrendBuffer[i] = iT3a(score/LookBackLength,T3Period,T3Hot,T3Original,T3Adaptive,i);
               trend[i] = trend[i+1];
         if (TrendBuffer[i] > TrendBuffer[i+1] && TrendBuffer[i] > levelOs && TrendBuffer[i+1]  <= levelOs) trend[i] =  1;  
         if (TrendBuffer[i] < TrendBuffer[i+1] && TrendBuffer[i] < levelOb && TrendBuffer[i+1]  >= levelOb) trend[i] = -1;
         
         if (!calculateValue) manageArrow(i);
         
         }
                 
    manageAlerts();
    return(0);      
    }
    
    //
    //
    //
    //
    //
   
    limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
       
    for(i=limit; i>=0; i--)
    {
       
       int y = iBarShift(NULL,timeFrame,Time[i]);
           TrendBuffer[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",LookBack,LookBackLength,T3Period,T3Hot,T3Original,T3Adaptive,levelOs,levelOb,0,y);
           trend[i]       = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",LookBack,LookBackLength,T3Period,T3Hot,T3Original,T3Adaptive,levelOs,levelOb,1,y);
              
           manageArrow(i); 
               
           //
           //
           //
           //
           //
      
           if (timeFrame <= Period() || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
           if (!Interpolate) continue;

           //
           //
           //
           //
           //

           datetime time = iTime(NULL,timeFrame,y);
              for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
              for(j = 1; j < n; j++)
              {
                
                 TrendBuffer[i+j] = TrendBuffer[i] + (TrendBuffer[i+n] - TrendBuffer[i]) * j/n;
                    
             }               
    }               

    //
    //
    //
    //
    //
       
    manageAlerts();
             
return(0);
}
         
//
//
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void manageAlerts()
{
   if (!calculateValue && 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)," adaptive T3 Chande Trendscore changed direction to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," adaptive T3 Chande Trendscore "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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);
} 

//+------------------------------------------------------------------
//|
//+------------------------------------------------------------------
//
//
//
//
//

double workT3[][14];
double workT3Coeffs[][6];
#define _period 0
#define _c1     1
#define _c2     2
#define _c3     3
#define _c4     4
#define _alpha  5
#define _atr    6

//
//
//
//
//

double iT3a(double price, double period, double hot, bool original, bool adaptive, int i, int forInstance=0)
{
   int r      = Bars-i-1;
   int buffer = forInstance*7;

   //
   //
   //
   //
   //
   
      if (ArrayRange(workT3,0) !=Bars)                  ArrayResize(workT3,Bars);
      if (ArrayRange(workT3Coeffs,0) < (forInstance+1)) ArrayResize(workT3Coeffs,forInstance+1);
      if (adaptive)
      {
         workT3[r][_atr+buffer] = iATR(NULL,0,period,i);
            double max = workT3[r][_atr+buffer];
            double min = workT3[r][_atr+buffer];
            for (int k=1; k<period && (r-k>=0); k++)
               {
                  max = MathMax(max,workT3[r-k][_atr+buffer]);
                  min = MathMin(min,workT3[r-k][_atr+buffer]);
               }
            if (min!=max)
                  double atn = 1.0-(workT3[r][_atr+buffer]-min)/(max-min);
            else         atn = 0.5;
            period = period*(atn+1.0)/2.0;
      }
   
   //
   //
   //
   //
   //
   
      if (workT3Coeffs[forInstance][_period] != period)
      {
        workT3Coeffs[forInstance][_period] = period;
           double a = hot;
               workT3Coeffs[forInstance][_c1] = -a*a*a;
               workT3Coeffs[forInstance][_c2] = 3*a*a+3*a*a*a;
               workT3Coeffs[forInstance][_c3] = -6*a*a-3*a-3*a*a*a;
               workT3Coeffs[forInstance][_c4] = 1+3*a+a*a*a+3*a*a;
               if (original)
                    workT3Coeffs[forInstance][_alpha] = 2.0/(1.0 + period);
               else workT3Coeffs[forInstance][_alpha] = 2.0/(2.0 + (period-1.0)/2.0);
      }
   
   //
   //
   //
   //
   //
   
   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[forInstance][_alpha]*(price              -workT3[r-1][0+buffer]);
         workT3[r][1+buffer] = workT3[r-1][1+buffer]+workT3Coeffs[forInstance][_alpha]*(workT3[r][0+buffer]-workT3[r-1][1+buffer]);
         workT3[r][2+buffer] = workT3[r-1][2+buffer]+workT3Coeffs[forInstance][_alpha]*(workT3[r][1+buffer]-workT3[r-1][2+buffer]);
         workT3[r][3+buffer] = workT3[r-1][3+buffer]+workT3Coeffs[forInstance][_alpha]*(workT3[r][2+buffer]-workT3[r-1][3+buffer]);
         workT3[r][4+buffer] = workT3[r-1][4+buffer]+workT3Coeffs[forInstance][_alpha]*(workT3[r][3+buffer]-workT3[r-1][4+buffer]);
         workT3[r][5+buffer] = workT3[r-1][5+buffer]+workT3Coeffs[forInstance][_alpha]*(workT3[r][4+buffer]-workT3[r-1][5+buffer]);
      }

   //
   //
   //
   //
   //
   
   return(workT3Coeffs[forInstance][_c1]*workT3[r][5+buffer] + 
          workT3Coeffs[forInstance][_c2]*workT3[r][4+buffer] + 
          workT3Coeffs[forInstance][_c3]*workT3[r][3+buffer] + 
          workT3Coeffs[forInstance][_c4]*workT3[r][2+buffer]);
}

//
//
//
//
//

void manageArrow(int i)
{
   if (ShowArrows)
   {
      deleteArrow(Time[i]);
      if (trend[i]!=trend[i+1])
      {
         if (trend[i] == 1) drawArrow(i,arrowsUpColor,241,false);
         if (trend[i] ==-1) drawArrow(i,arrowsDnColor,242,true);
      }
   }
}               

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = 3.0*iATR(NULL,0,20,i)/4.0;   
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
  
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i]+gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i] -gap);
}

//
//
//
//
//

void deleteArrows()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}

void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}

//
//
//
//
//

