//+------------------------------------------------------------------+
//|                                    Spearman Rank Correlation.mq4 |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers  8
#property indicator_color1   clrDimGray
#property indicator_color2   clrDodgerBlue
#property indicator_color3   clrDodgerBlue
#property indicator_color4   clrSandyBrown
#property indicator_color5   clrSandyBrown
#property indicator_color6   clrSandyBrown
#property indicator_color7   clrDodgerBlue
#property indicator_color8   clrDimGray
#property indicator_style8   STYLE_DOT
#property indicator_width2   3
#property indicator_width3   3
#property indicator_width4   3
#property indicator_width5   3
#property indicator_minimum -1
#property indicator_maximum  1
#property strict

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuyP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision);
   double dzSellP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision);
#import "spearman.dll"
   double rankSpearman(double& sourceArray[],bool isSeries, int rank, int bars, int i);
#import
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 ENUM_TIMEFRAMES    TimeFrame              = PERIOD_CURRENT; // Time frame to use
extern int                Rank                   = 50;             // Spearman rank period
extern enPrices           Price                  = pr_close;       // Price to use
extern int                PriceSmoothing         = 1;              // Price pre-smoothing
extern ENUM_MA_METHOD     PriceSmoothingMethod   = MODE_EMA;       // Price pre smoothing method
extern int                DzLookBackBars         = 20;             // Dynamic zones lookback period
extern double             DzStartBuyProbability  = 0.20;           // Dynamic zones buy probability
extern double             DzStartSellProbability = 0.20;           // Dynamic zones sell probability
extern bool               alertsOn               = false;          // Turn alerts on?
extern bool               alertsOnCurrent        = false;          // Alerts on current (stil opened) bar?
extern bool               alertsMessage          = false;          // Alerts should display pop-up message?
extern bool               alertsSound            = false;          // Alerts should play a sound?
extern bool               alertsEmail            = false;          // Alerts should send email?
extern bool               alertsNotification     = false;          // Alerts should send push notification?
extern bool               Interpolate            = true;           // Interpolate data in multi time frame mode?

//
//
//
//
//

double rank[];
double rankUa[];
double rankUb[];
double rankDa[];
double rankDb[];
double bli[];
double sli[];
double zli[];
double prices[];
double rawprice[];
double trend[];

//
//
//
//
//

string indicatorFileName;
bool   returnBars;


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

int init()
{
   IndicatorBuffers(10);
   SetIndexBuffer(0, rank);
   SetIndexBuffer(1, rankUa);
   SetIndexBuffer(2, rankUb);
   SetIndexBuffer(3, rankDa);
   SetIndexBuffer(4, rankDb);
   SetIndexBuffer(5, bli);
   SetIndexBuffer(6, sli);
   SetIndexBuffer(7, zli);
   SetIndexBuffer(8, trend);
   SetIndexBuffer(9, rawprice);
   
   
      //
      //
      //
      //
      //
      
         Rank = MathMax(Rank,8);
         indicatorFileName = WindowExpertName();
         returnBars        = TimeFrame==-99;
         TimeFrame         = MathMax(TimeFrame,_Period);
   IndicatorShortName(timeFrameToString(TimeFrame)+" Spearman (" + (string)Rank + ")");
   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) { rank[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //

   if (ArraySize(prices)!= Bars) { ArrayResize(prices,Bars); ArrayResize(trend,Bars); }
   if (TimeFrame == Period())
   {
      if (trend[limit]== 1) CleanPoint(limit,rankUa,rankUb);
      if (trend[limit]==-1) CleanPoint(limit,rankDa,rankDb);
      for(int i = limit, r=Bars-i-1; i >= 0; i--,r++) rawprice[i] = getPrice(Price,Open,Close,High,Low,i);
      for(int i = limit, r=Bars-i-1; i >= 0; i--,r++)
      {
         prices[r] = iMAOnArray(rawprice,0,PriceSmoothing,0,PriceSmoothingMethod,i);
         rankUa[i] = EMPTY_VALUE;
         rankUb[i] = EMPTY_VALUE;
         rankDa[i] = EMPTY_VALUE;
         rankDb[i] = EMPTY_VALUE;
         rank[i]   = rankSpearman(prices,false,Rank,Bars,i);
         bli[i]    = dzBuyP (rank, DzStartBuyProbability,  DzLookBackBars, Bars, i, 0.0001);
         sli[i]    = dzSellP(rank, DzStartSellProbability, DzLookBackBars, Bars, i, 0.0001);
         zli[i]    = dzSellP(rank, 0.5,                    DzLookBackBars, Bars, i, 0.0001);
         trend[i]  = 0;
         
            //
            //
            //
            //
            //
            
            if (rank[i]>sli[i])                    trend[i]= 1;
            if (rank[i]<bli[i])                    trend[i]=-1;
            if (rank[i]>bli[i]  && rank[i]<sli[i]) trend[i]= 0;
            if (trend[i] ==  1) PlotPoint(i,rankUa,rankUb,rank);
            if (trend[i] == -1) PlotPoint(i,rankDa,rankDb,rank);
      }      
      manageAlerts();
      return(0);
   }      
   
   //
   //
   //
   //
   //
   
   limit = (int)MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   for (int i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,TimeFrame,Time[i]);
         rank[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Rank,Price,PriceSmoothing,PriceSmoothingMethod,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotification,0,y);
         trend[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Rank,Price,PriceSmoothing,PriceSmoothingMethod,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotification,8,y);
         bli[i]    = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Rank,Price,PriceSmoothing,PriceSmoothingMethod,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotification,5,y);
         sli[i]    = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Rank,Price,PriceSmoothing,PriceSmoothingMethod,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotification,6,y);
         zli[i]    = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,Rank,Price,PriceSmoothing,PriceSmoothingMethod,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotification,7,y);
         rankUa[i] = EMPTY_VALUE;
         rankUb[i] = EMPTY_VALUE;
         rankDa[i] = EMPTY_VALUE;
         rankDb[i] = EMPTY_VALUE;

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

         //
         //
         //
         //
         //

         int n,k; datetime time = iTime(NULL,TimeFrame,y);
            for(n = 1; i+n<Bars && Time[i+n] >= time; n++) continue;	
            for(k = 1; i+n<Bars && i+k<Bars && k<n; k++)
            {
               rank[i+k] = rank[i] + (rank[i+n]-rank[i])*k/n;
               bli[i+k]  = bli[i]  + (bli[i+n] -bli[i] )*k/n;
               sli[i+k]  = sli[i]  + (sli[i+n] -sli[i] )*k/n;
               zli[i+k]  = zli[i]  + (zli[i+n] -zli[i] )*k/n;
            }
   }
   for (int i=limit;i>=0;i--)
   {
      if (trend[i]== 1) PlotPoint(i,rankUa,rankUb,rank);
      if (trend[i]==-1) PlotPoint(i,rankDa,rankDb,rank);
   }
   return(0);
}


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

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (trend[Bars-whichBar-1] != trend[Bars-whichBar-2])
      {
         if (trend[Bars-whichBar-1] ==  1) doAlert(whichBar,DoubleToStr(sli[whichBar]  ,4)+" broken up");
         if (trend[Bars-whichBar-1] == -1) doAlert(whichBar,DoubleToStr(bli[whichBar]  ,4)+" broken down");
         if (trend[Bars-whichBar-2] == -1) doAlert(whichBar,DoubleToStr(bli[whichBar+1],4)+" broken up");
         if (trend[Bars-whichBar-2] ==  1) doAlert(whichBar,DoubleToStr(sli[whichBar+1],4)+" broken 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(_Period)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," spearman level ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"Spearman rank"),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

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

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 (i>=Bars-2) 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; }
}

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

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

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

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 && price<=pr_hatbiased)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars);
         int r = Bars-i-1; instanceNo *= 4;
         
         //
         //
         //
         //
         //
         
         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);
}