//------------------------------------------------------------------
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"
//------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 9
#property indicator_color1  LimeGreen
#property indicator_color2  LimeGreen
#property indicator_color3  Orange
#property indicator_color4  Orange
#property indicator_color5  DarkGray
#property indicator_color6  LimeGreen
#property indicator_color7  LimeGreen
#property indicator_color8  Orange
#property indicator_color9  Orange
#property indicator_width1  2
#property indicator_width3  2
#property indicator_width6  3
#property indicator_width7  3
#property indicator_width8  3
#property indicator_width9  3

//
//
//
//
//

enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased   // Heiken ashi trend biased price
};

extern enPrices TSIPrice      = pr_close;
extern int      TSIPeriod1    = 25;
extern int      TSIPeriod2    = 13;
extern int      TSIPeriod3    =  1;
extern int      TSILookBack   = 10;
extern enPrices EMAPrice      = pr_close;
extern int      EMAPeriod1    =  9;
extern int      EMAPeriod2    =  9;
extern int      EMALookBack   = 10;
extern bool     ShowHistogram = true;

//
//
//
//
//

double histouu[];
double histoud[];
double histodd[];
double histodu[];
double sd[];
double sdda[];
double sddb[];
double sdua[];
double sdub[];
double tsi[];
double ema[];
double prices[];
double state[];
double slope[];

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(14);
   int style = DRAW_NONE; if (ShowHistogram) style = DRAW_HISTOGRAM;      
      SetIndexBuffer(0,histouu); SetIndexStyle(0,style);
      SetIndexBuffer(1,histoud); SetIndexStyle(1,style);
      SetIndexBuffer(2,histodd); SetIndexStyle(2,style);
      SetIndexBuffer(3,histodu); SetIndexStyle(3,style);
      SetIndexBuffer(4,sd);
      SetIndexBuffer(5,sdua);
      SetIndexBuffer(6,sdub);
      SetIndexBuffer(7,sdda);
      SetIndexBuffer(8,sddb);
      SetIndexBuffer(9,tsi);
      SetIndexBuffer(10,ema);
      SetIndexBuffer(11,state);  
      SetIndexBuffer(12,prices);  
      SetIndexBuffer(13,slope);  
   IndicatorShortName(" Slope divergence ("+TSIPeriod1+","+TSIPeriod2+","+TSIPeriod3+","+EMAPeriod1+","+EMAPeriod2+")");
   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 (state[limit]== 1) CleanPoint(limit,sdua,sdub);
      if (state[limit]==-1) CleanPoint(limit,sdda,sddb);
      for(int i=limit; i>=0; i--)
      {
         prices[i] = getPrice(TSIPrice,Open,Close,High,Low,i);
         double priceDiff = prices[i]-prices[i+1];
         double avg       = iEma(iEma(iEma(        priceDiff ,TSIPeriod1,i,0),TSIPeriod2,i,1),TSIPeriod3,i,2);
         double ava       = iEma(iEma(iEma(MathAbs(priceDiff),TSIPeriod1,i,3),TSIPeriod2,i,4),TSIPeriod3,i,5);
            if (ava != 0)
                  tsi[i] = 100.0*avg/ava;
            else  tsi[i] = 0.00;
                  ema[i] = iEma(iEma(getPrice(EMAPrice,Open,Close,High,Low,i),EMAPeriod1,i,6),EMAPeriod2,i,7);
                  
         //
         //
         //
         //
         //
         
         state[i]   = 0;
         sdua[i]    = EMPTY_VALUE;
         sdub[i]    = EMPTY_VALUE;
         sdda[i]    = EMPTY_VALUE;
         sddb[i]    = EMPTY_VALUE;
         histouu[i] = EMPTY_VALUE;
         histoud[i] = EMPTY_VALUE;
         histodd[i] = EMPTY_VALUE;
         histodu[i] = EMPTY_VALUE;
         double slope1 = tsi[i] - tsi[i+TSILookBack];                  
         double slope2 = ema[i] - ema[i+EMALookBack];
         double postsi = 0;
         double negtsi = 0;
         if (slope1 > 0 && slope2 > 0) postsi = tsi[i];
         if (slope1 < 0 && slope2 < 0) negtsi = tsi[i];
               sd[i] = postsi+negtsi;
               if (sd[i]>0) state[i] =  1;
               if (sd[i]<0) state[i] = -1;
               if (state[i] ==  1) { sd[i] = tsi[i]; PlotPoint(i,sdua,sdub,sd); }
               if (state[i] == -1) { sd[i] = tsi[i]; PlotPoint(i,sdda,sddb,sd); }
               slope[i] = slope[i+1];
                  if (tsi[i]>tsi[i+1]) slope[i] =  1;
                  if (tsi[i]<tsi[i+1]) slope[i] = -1;
                  if (state[i]== 1)
                     if (slope[i] == 1)
                           histouu[i] = sd[i];
                     else  histoud[i] = sd[i];       
                  if (state[i]==-1)
                     if (slope[i] == 1)
                           histodu[i] = sd[i];
                     else  histodd[i] = sd[i];       
      }
   return(0);
}  

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workEma[][8];
double iEma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= Bars) ArrayResize(workEma,Bars); r = Bars-r-1;

   //
   //
   //
   //
   //
      
   double alpha = 2.0 / (1.0+period);
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+alpha*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}
  
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//
//

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//
//

double workHa[][4];
double getPrice(int price, const double& open[], const double& close[], const double& high[], const double& low[], int i, int instanceNo=0)
{
  if (price>=pr_haclose)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars);
         int r = Bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen;
         if (r>0)
                haOpen  = (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0;
         else   haOpen  = (open[i]+close[i])/2;
         double haClose = (open[i] + high[i] + low[i] + close[i]) / 4.0;
         double haHigh  = MathMax(high[i], MathMax(haOpen,haClose));
         double haLow   = MathMin(low[i] , MathMin(haOpen,haClose));

         if(haOpen  <haClose) { workHa[r][instanceNo+0] = haLow;  workHa[r][instanceNo+1] = haHigh; } 
         else                 { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow;  } 
                                workHa[r][instanceNo+2] = haOpen;
                                workHa[r][instanceNo+3] = haClose;
         //
         //
         //
         //
         //
         
         switch (price)
         {
            case pr_haclose:     return(haClose);
            case pr_haopen:      return(haOpen);
            case pr_hahigh:      return(haHigh);
            case pr_halow:       return(haLow);
            case pr_hamedian:    return((haHigh+haLow)/2.0);
            case pr_hamedianb:   return((haOpen+haClose)/2.0);
            case pr_hatypical:   return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:  return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:   return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (price)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
   }
   return(0);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if (i>Bars-2) return;
   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 (i>Bars-3) 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; }
}