//+------------------------------------------------------------------+
//|                                                     insync index |
//+------------------------------------------------------------------+
#property copyright "www,forex-tsd.com"
#property link      "www,forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 7
#property indicator_color1  DimGray
#property indicator_color2  DimGray
#property indicator_color3  DimGray
#property indicator_width4  2
#property indicator_width5  2
#property indicator_width6  2
#property indicator_width7  2
#property indicator_style1  STYLE_DOT
#property indicator_style2  STYLE_DOT
#property indicator_level1  0
#property indicator_levelcolor DimGray

//
//
//
//
//

extern string TimeFrame                = "current time frame";
extern double OverBought               =  45;
extern double OverSold                 = -45;
extern bool   UseVolumeBasedIndicators = true;
extern color  OverSoldColor            = Red; 
extern color  OverBoughtColor          = DeepSkyBlue; 
extern bool   ShowArrows               = true;
extern string arrowsIdentifier         = "insync arrows";
extern int    arrowsWidth              = 1;
extern bool   Interpolate              = true;

//
//
//
//
//

double insync[];
double insyncUp[];
double insyncUpa[];
double insyncUpb[];
double insyncDn[];
double insyncDna[];
double insyncDnb[];
double trend[];
double correction=0;

//
//
//
//
//

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

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   if (!UseVolumeBasedIndicators) correction=-10;
   IndicatorBuffers(8);
      SetIndexBuffer(0,insyncUp);
      SetIndexBuffer(1,insyncDn);
      SetIndexBuffer(2,insync);
      SetIndexBuffer(3,insyncUpa); SetIndexStyle(3,DRAW_LINE,EMPTY,EMPTY,OverSoldColor);
      SetIndexBuffer(4,insyncUpb); SetIndexStyle(4,DRAW_LINE,EMPTY,EMPTY,OverSoldColor);
      SetIndexBuffer(5,insyncDna); SetIndexStyle(5,DRAW_LINE,EMPTY,EMPTY,OverBoughtColor);
      SetIndexBuffer(6,insyncDnb); SetIndexStyle(6,DRAW_LINE,EMPTY,EMPTY,OverBoughtColor);
      SetIndexBuffer(7,trend);

         //
         //
         //
         //
         //
                  
         indicatorFileName = WindowExpertName();
         calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
         returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
         
         //
         //
         //
         //
         //
         
   IndicatorShortName(timeFrameToString(timeFrame)+" insync index");
   return(0);
}
int deinit()
{
   if (!calculateValue && ShowArrows) deleteArrows();
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//

double  work[][5];
#define macdSignal 0
#define rocData    1
#define dpoData    2
#define mfiData    3
#define eomData    4

//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,n,k,r,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { insyncUp[0] = limit+1; return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame==Period())
   {
      if (trend[limit]== 1) CleanPoint(limit,insyncUpa,insyncUpb);
      if (trend[limit]==-1) CleanPoint(limit,insyncDna,insyncDnb);
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      
      //
      //
      //
      //
      //
      
      for (i=limit, r=Bars-i-1; i>=0; i--,r++)
      {
         double insyncScore = 0;
      
         //
         //
         //
         //
         //
      
         double avg = iMA(NULL,0,20,0,MODE_SMA,PRICE_CLOSE,i);
         double std = iStdDev(NULL,0,20,0,MODE_SMA,PRICE_CLOSE,i); if (std==0) continue;
         double bos = (Close[i]-avg+2.0*std)/(4.0*std);
               if (bos < 0.05) insyncScore -=5;
               if (bos > 0.95) insyncScore +=5;
               
         double cci = iCCI(NULL,0,14,PRICE_TYPICAL,i);
               if (cci < -100) insyncScore -=5;
               if (cci >  100) insyncScore +=5;

         double rsi = iRSI(NULL,0,14,PRICE_CLOSE,i);
               if (rsi < 30) insyncScore -=5;
               if (rsi > 70) insyncScore +=5;
               
         double stoFastK = iStochastic(NULL,0,14,3,1,MODE_EMA,0,MODE_MAIN  ,i);
         double stoFastD = iStochastic(NULL,0,14,3,1,MODE_EMA,0,MODE_SIGNAL,i);
               if (stoFastK < 20) insyncScore -=5;
               if (stoFastK > 80) insyncScore +=5;
               if (stoFastD < 20) insyncScore -=5;
               if (stoFastD > 80) insyncScore +=5;
               
         double macd = iMA(NULL,0,12,0,MODE_EMA,PRICE_CLOSE,i)-iMA(NULL,0,25,0,MODE_EMA,PRICE_CLOSE,i);
                work[r][macdSignal] = work[r-1][macdSignal]+0.2*(macd-work[r-1][macdSignal]);
               if (work[r][macdSignal] < 0 && work[r][macdSignal] > macd) insyncScore -=5;
               if (work[r][macdSignal] > 0 && work[r][macdSignal] < macd) insyncScore +=5;
         
         //
         //
         //
         //
         //
         
            work[r][rocData] = Close[i]-Close[i+10];
                  double rocAvg = 0; for (k=0; k<10; k++) rocAvg += work[r-k][rocData]; rocAvg /= 10;
                     if (rocAvg < 0 && rocAvg > work[r][rocData]) insyncScore -=5;
                     if (rocAvg > 0 && rocAvg < work[r][rocData]) insyncScore +=5;

            work[r][dpoData] = Close[i]-iMA(NULL,0,18,0,MODE_SMA,PRICE_CLOSE,i+10);
                  double dpoAvg = 0; for (k=0; k<10; k++) dpoAvg += work[r-k][dpoData]; dpoAvg /= 10;
                     if (dpoAvg < 0 && dpoAvg > work[r][dpoData]) insyncScore -=5;
                     if (dpoAvg > 0 && dpoAvg < work[r][dpoData]) insyncScore +=5;
        
         //
         //
         //
         //    volume based indicators :
         //                   money flow index
         //                   ease of move index
         //
         //
         //
        
         if (UseVolumeBasedIndicators)
         { 
               work[r][mfiData] = iMA(NULL,0,1,0,MODE_SMA,PRICE_TYPICAL,i);
                  double sumMfp = 0;
                  double sumMft = 0;
                  for (k=0; k<14; k++)
                  {
                     sumMft += work[r-k][mfiData]+Volume[i+k];
                        if (work[r-k][mfiData]>work[r-k-1][mfiData]) sumMfp += work[r-k][mfiData]+Volume[i+k];
                  }
                  double mfi = 100.0*sumMfp/sumMft;
                     if (mfi < 20) insyncScore -=5;
                     if (mfi > 80) insyncScore +=5;

               //
               //
               //
               //
               //
            
               double eom = 0; for (k=0; k<13; k++) 
                      eom += 100*100.0*(High[i+k]-Low[i+k])/Volume[i+k]*(High[i+k]+Low[i+k]-High[i+k+1]-Low[i+k+1])*0.5;
               work[r][eomData] = eom/13;
               double eomAvg = 0;
                     for (k=0; k<10; k++) eomAvg += work[r-k][eomData]; eomAvg /= 10;
                     if (eomAvg < 0 && eomAvg > eom) insyncScore -=5;
                     if (eomAvg > 0 && eomAvg < eom) insyncScore +=5;
         }

         //
         //
         //
         //
         //

         insyncUp[i]  = OverBought+correction;
         insyncDn[i]  = OverSold-correction;
         insync[i]    = insyncScore;
         insyncUpa[i] = EMPTY_VALUE;
         insyncUpb[i] = EMPTY_VALUE;
         insyncDna[i] = EMPTY_VALUE;
         insyncDnb[i] = EMPTY_VALUE;
         trend[i]     = trend[i+1];
               if (insync[i]>(OverBought+correction-Point))                                          trend[i] =  1;
               if (insync[i]<(OverSold-correction+Point))                                            trend[i] = -1;
               if (insync[i]>(OverSold-correction+Point) && insync[i]<(OverBought+correction-Point)) trend[i] =  0;
               if (trend[i] ==  1) PlotPoint(i,insyncUpa,insyncUpb,insync);
               if (trend[i] == -1) PlotPoint(i,insyncDna,insyncDnb,insync);
               if (!calculateValue) manageArrow(i);
      }
      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]);
         insync[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",OverBought,OverSold,UseVolumeBasedIndicators,2,y);
         trend[i]     = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",OverBought,OverSold,UseVolumeBasedIndicators,7,y);
         insyncUp[i]  = OverBought+correction;
         insyncDn[i]  = OverSold-correction;
         insyncUpa[i] = EMPTY_VALUE;
         insyncUpb[i] = EMPTY_VALUE;
         insyncDna[i] = EMPTY_VALUE;
         insyncDnb[i] = EMPTY_VALUE;
         manageArrow(i);

         //
         //
         //
         //
         //
      
         if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(k = 1; k < n; k++)
               insync[i+k] = insync[i] + (insync[i+n]-insync[i])*k/n;
   }
   for (i=limit;i>=0;i--)
   {
      if (trend[i]== 1) PlotPoint(i,insyncUpa,insyncUpb,insync);
      if (trend[i]==-1) PlotPoint(i,insyncDna,insyncDnb,insync);
   }

   //
   //
   //
   //
   //
   
   return(0);   
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void manageArrow(int i)
{
   if (ShowArrows)
   {
      deleteArrow(Time[i]);
      if (trend[i]!=trend[i+1])
      {
         if (trend[i] ==-1) drawArrow(i,OverBoughtColor,159,false);
         if (trend[i] == 1) drawArrow(i,OverSoldColor  ,159,true );
      }
   }
}               

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = 3.0*iATR(NULL,0,10,i)/4.0; //20  
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         ObjectSet(name,OBJPROP_WIDTH,arrowsWidth);
         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);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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 char = StringGetChar(s, length);
         if((char > 96 && char < 123) || (char > 223 && char < 256))
                     s = StringSetChar(s, length, char - 32);
         else if(char > -33 && char < 0)
                     s = StringSetChar(s, length, char + 224);
   }
   return(s);
}