//+------------------------------------------------------------------+
//|                                                jurik crosses.mq4 |
//|                                                           mladen |
//|                                                                  |
//|                                                                  |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+

#property copyright "copyleft mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 6
#property indicator_color1 Red
#property indicator_color2 Maroon
#property indicator_color3 LimeGreen
#property indicator_color4 Green
#property indicator_color5 Gold
#property indicator_color6 Green
#property indicator_width1 2
#property indicator_width2 1
#property indicator_width3 2
#property indicator_width4 1
#property indicator_width5 2
#property indicator_width6 2
#property strict

//
//
//
//
//

extern ENUM_TIMEFRAMES    TimeFrame           = PERIOD_CURRENT;  // Time frame
extern ENUM_APPLIED_PRICE FastJmaPrice        = 0;               // Fast price
extern double             FastJmaLength       = 20;              // Fast jma length
extern double             FastJmaPhase        = 0;               // Fast jma phase
extern bool               FastJmaSmoothDouble = false;           // Fast jma should be double?
extern ENUM_APPLIED_PRICE SlowJmaPrice        = 0;               // Slow price
extern double             SlowJmaLength       = 50;              // Slow jma length
extern double             SlowJmaPhase        = 0;               // Slow jma phase
extern bool               SlowJmaSmoothDouble = false;           // Slow jma should be double?
extern int                SignalLength        =  9;              // Signal period
extern bool               AlertsOn            = false;           // Turn alerts on?
extern bool               AlertsOnCurrent     = true;            // Alerts on current (still opened) bar?
extern bool               AlertsMessage       = true;            // Alerts should show pop-up message?
extern bool               AlertsSound         = false;           // Alerts should play alert sound?
extern bool               AlertsPushNotif     = false;           // Alerts should send push notification?
extern bool               AlertsEmail         = false;           // Alerts should send email?
extern bool               Interpolate         = true;            // Interpolate in multi time frame mode?

//
//
//
//
//

double jurgCross[],jurrCross[],upBuffer1[],upBuffer2[],dnBuffer1[],dnBuffer2[],jurdiff[],trend[],slope[],count[];
string indicatorFileName;
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,0,FastJmaPrice,FastJmaLength,FastJmaPhase,FastJmaSmoothDouble,SlowJmaPrice,SlowJmaLength,SlowJmaPhase,SlowJmaSmoothDouble,SignalLength,AlertsOn,AlertsOnCurrent,AlertsMessage,AlertsSound,AlertsPushNotif,AlertsEmail,_buff,_ind)

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(10);
      SetIndexBuffer(0,dnBuffer1); SetIndexStyle(0,DRAW_HISTOGRAM);
      SetIndexBuffer(1,dnBuffer2); SetIndexStyle(1,DRAW_HISTOGRAM);
      SetIndexBuffer(2,upBuffer1); SetIndexStyle(2,DRAW_HISTOGRAM);
      SetIndexBuffer(3,upBuffer2); SetIndexStyle(3,DRAW_HISTOGRAM);
      SetIndexBuffer(4,jurrCross); SetIndexLabel(4,"Jurik trix "+ (string)SlowJmaLength);
      SetIndexBuffer(5,jurgCross); SetIndexLabel(5,"Jurik trix "+ (string)FastJmaLength);   
      SetIndexBuffer(6,jurdiff);  
      SetIndexBuffer(7,trend);
      SetIndexBuffer(8,slope);
      SetIndexBuffer(9,count);
      
      //
      //
      //
      //
      //
   
         indicatorFileName = WindowExpertName();
         TimeFrame         = MathMax(TimeFrame,_Period);
   
   IndicatorShortName(timeFrameToString(TimeFrame)+" Jurik trix  ("+(string)FastJmaLength+","+(string)SlowJmaLength+")");
   return(0);
}
int deinit(){ return(0); }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double work[][2];

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); count[0] = limit;
           if (TimeFrame!=_Period)
           {
               limit = (int)MathMax(limit,MathMin(Bars-1,_mtfCall(9,0)*TimeFrame/Period()));
               for (int i=limit; i>=0; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                  jurgCross[i] = _mtfCall(5,y);
                  jurrCross[i] = _mtfCall(4,y);
                  jurdiff[i]   = _mtfCall(6,y);
                  trend[i]     = _mtfCall(7,y);
                  slope[i]     = _mtfCall(8,y);
                  upBuffer1[i] = EMPTY_VALUE;
                  upBuffer2[i] = EMPTY_VALUE;
                  dnBuffer1[i] = EMPTY_VALUE;
                  dnBuffer2[i] = EMPTY_VALUE;
                     if (trend[i]==1)
                        if (slope[i] == 1)
                              upBuffer1[i] = jurdiff[i];
                        else  upBuffer2[i] = jurdiff[i];
                     else               
                        if (slope[i] == 1)
                              dnBuffer2[i] = jurdiff[i];
                        else  dnBuffer1[i] = jurdiff[i];

                  //
                  //
                  //
                  //
                  //

                  if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,Time[i-1]))) continue;
                   #define _interpolate(buff) buff[i+k] = buff[i]+(buff[i+n]-buff[i])*k/n
                   int n,k; datetime time = iTime(NULL,TimeFrame,y);
                      for(n = 1; (i+n)<Bars && Time[i+n] >= time; n++) continue;	
                      for(k = 1; k<n && (i+n)<Bars && (i+k)<Bars; k++)
                      {
                        _interpolate(jurgCross);
                        _interpolate(jurrCross);
                        _interpolate(jurdiff);
                           if (upBuffer1[i+k]!=EMPTY_VALUE) upBuffer1[i+k] = jurdiff[i+k];
                           if (upBuffer2[i+k]!=EMPTY_VALUE) upBuffer2[i+k] = jurdiff[i+k];
                           if (dnBuffer1[i+k]!=EMPTY_VALUE) dnBuffer1[i+k] = jurdiff[i+k];
                           if (dnBuffer2[i+k]!=EMPTY_VALUE) dnBuffer2[i+k] = jurdiff[i+k];
                     }                           
               }
               return(0);
            }

   //
   //
   //
   //
   //

      if (ArrayRange(work,0) != Bars) { ArrayResize(work,Bars); }
      for(int i=limit, r=Bars-i-1; i>=0; i--,r++)
      {
         double Fma = iMA(NULL,0,1,0,MODE_SMA,FastJmaPrice,i);
         double Sma = iMA(NULL,0,1,0,MODE_SMA,SlowJmaPrice,i);
      
         work[r][0]   = iDSmooth(Fma,FastJmaLength,FastJmaPhase,FastJmaSmoothDouble,i, 0);  
         work[r][1]   = iDSmooth(Sma,SlowJmaLength,SlowJmaPhase,SlowJmaSmoothDouble,i,20);
         jurgCross[i] = (r>0) ? work[r][0]-work[r-1][0] : 0;
         jurrCross[i] = (r>0) ? work[r][1]-work[r-1][1] : 0;
         jurdiff[i]   = jurgCross[i]-jurrCross[i];
         upBuffer1[i] = EMPTY_VALUE;
         upBuffer2[i] = EMPTY_VALUE;
         dnBuffer1[i] = EMPTY_VALUE;
         dnBuffer2[i] = EMPTY_VALUE;
         slope[i]     = (i<Bars-1) ? (jurdiff[i]>jurdiff[i+1]) ? 1 : (jurdiff[i]<jurdiff[i+1]) ? -1 : trend[i+1] : 0;
         trend[i]     =              (jurdiff[i]>0) ? 1 : (jurdiff[i]<0) ? -1 : 0;
            if (trend[i]==1)
               if (slope[i] == 1)
                     upBuffer1[i] = jurdiff[i];
               else  upBuffer2[i] = jurdiff[i];
            else               
               if (slope[i] == 1)
                     dnBuffer2[i] = jurdiff[i];
               else  dnBuffer1[i] = jurdiff[i];
      }
      manageAlerts(trend);
      return(0);
}


//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts(double& _trend[])
{
   if (AlertsOn)
   {
      int whichBar = 1; if (AlertsOnCurrent) whichBar = 0;
      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 = timeFrameToString(_Period)+" "+_Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" Jurik TRIX state changed to "+doWhat;
          if (AlertsMessage)   Alert(message);
          if (AlertsEmail)     SendMail(_Symbol+" Jurik TRIX",message);
          if (AlertsPushNotif) SendNotification(message);
          if (AlertsSound)     PlaySound("alert2.wav");
   }
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

double wrk[][40];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iDSmooth(double price, double length, double phase, bool isDouble, int i, int s=0)
{
   if (isDouble)
         return (iSmooth(iSmooth(price,MathSqrt(length),phase,i,s),MathSqrt(length),phase,i,s+10));
   else  return (iSmooth(price,length,phase,i,s));
}

//
//
//
//
//

double iSmooth(double price, double length, double phase, int i, int s=0)
{
   if (length <=1) return(price);
   
   if (ArrayRange(wrk,0) != Bars) ArrayResize(wrk,Bars);
   
   int r = Bars-i-1; 
      if (r==0) { int k=0; for(; k<7; k++) wrk[r][k+s]=price; for(; k<10; k++) wrk[r][k+s]=0; return(price); }

   //
   //
   //
   //
   //
   
      double len1   = MathMax(MathLog(MathSqrt(0.5*(length-1)))/MathLog(2.0)+2.0,0);
      double pow1   = MathMax(len1-2.0,0.5);
      double del1   = price - wrk[r-1][bsmax+s];
      double del2   = price - wrk[r-1][bsmin+s];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = MathMin(r,10);
	
         wrk[r][volty+s] = 0;
               if(MathAbs(del1) > MathAbs(del2)) wrk[r][volty+s] = MathAbs(del1); 
               if(MathAbs(del1) < MathAbs(del2)) wrk[r][volty+s] = MathAbs(del2); 
         wrk[r][vsum+s] =	wrk[r-1][vsum+s] + (wrk[r][volty+s]-wrk[r-forBar][volty+s])*div;
         
         //
         //
         //
         //
         //
   
         wrk[r][avolty+s] = wrk[r-1][avolty+s]+(2.0/(MathMax(4.0*length,30)+1.0))*(wrk[r][vsum+s]-wrk[r-1][avolty+s]);
               double dVolty = (wrk[r][avolty+s] > 0) ? wrk[r][volty+s]/wrk[r][avolty+s] : 0;   
	               if (dVolty > MathPow(len1,1.0/pow1)) dVolty = MathPow(len1,1.0/pow1);
                  if (dVolty < 1)                      dVolty = 1.0;

      //
      //
      //
      //
      //
	        
   	double pow2 = MathPow(dVolty, pow1);
      double len2 = MathSqrt(0.5*(length-1))*len1;
      double Kv   = MathPow(len2/(len2+1), MathSqrt(pow2));

         if (del1 > 0) wrk[r][bsmax+s] = price; else wrk[r][bsmax+s] = price - Kv*del1;
         if (del2 < 0) wrk[r][bsmin+s] = price; else wrk[r][bsmin+s] = price - Kv*del2;
	
   //
   //
   //
   //
   //
      
      double R     = MathMax(MathMin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = MathPow(beta,pow2);

         wrk[r][0+s] = price + alpha*(wrk[r-1][0+s]-price);
         wrk[r][1+s] = (price - wrk[r][0+s])*(1-beta) + beta*wrk[r-1][1+s];
         wrk[r][2+s] = (wrk[r][0+s] + R*wrk[r][1+s]);
         wrk[r][3+s] = (wrk[r][2+s] - wrk[r-1][4+s])*MathPow((1-alpha),2) + MathPow(alpha,2)*wrk[r-1][3+s];
         wrk[r][4+s] = (wrk[r-1][4+s] + wrk[r][3+s]); 

   //
   //
   //
   //
   //

   return(wrk[r][4+s]);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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("");
}