//------------------------------------------------------------------
#property link      "www.forex-station.com"
#property copyright "www.forex-station.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_color1  clrDarkGoldenrod
#property indicator_color2  clrDarkGoldenrod
#property indicator_color3  clrDarkGoldenrod
#property strict

//
//
//
//
//

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_tbiased2,   // Trend biased (extreme) 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
   pr_hatbiased2, // Heiken ashi trend biased (extreme) price
   pr_habclose,   // Heiken ashi (better formula) close
   pr_habopen ,   // Heiken ashi (better formula) open
   pr_habhigh,    // Heiken ashi (better formula) high
   pr_hablow,     // Heiken ashi (better formula) low
   pr_habmedian,  // Heiken ashi (better formula) median
   pr_habtypical, // Heiken ashi (better formula) typical
   pr_habweighted,// Heiken ashi (better formula) weighted
   pr_habaverage, // Heiken ashi (better formula) average
   pr_habmedianb, // Heiken ashi (better formula) median body
   pr_habtbiased, // Heiken ashi (better formula) trend biased price
   pr_habtbiased2 // Heiken ashi (better formula) trend biased (extreme) price
};

extern ENUM_TIMEFRAMES TimeFrame         = PERIOD_CURRENT;   // Time frame
input int              JmaLength         = 13;               // Jma Length 26
input double           JmaPhase          = 0;                // Jma phase 0
input bool             JmaDouble         = false;            // Jma double smooth false
input enPrices         JmaPrice          = pr_haweighted;    // Jma price to use pr_close    
input int              AtrPeriod         = 10;               // Atr period 30
input double           AtrMultiplier     = 1.2;              // Atr multiplier 1.5
input bool             alertsOn          = false;     // Turn alerts on?
input bool             alertsOnCurrent   = true;      // Alerts on current (still opened) bar?
input bool             alertsMessage     = true;      // Alerts should show pop-up message?
input bool             alertsSound       = false;     // Alerts should play alert sound?
input bool             alertsNotify      = false;     // Alerts should send push notification?
input bool             alertsEmail       = false;     // Alerts should send email?
input string           soundFile         = "alert2.wav";
input bool             ShowArrows        = false;
input int              ArrowsWidth       = 2;
input color            ArrowUpColor      = clrSkyBlue; //Green;
input color            ArrowDnColor      = clrMagenta; 
input int              ArrowCodeUp       = 159;       // Arrow code up
input int              ArrowCodeDn       = 159;       // Arrow code down
input double           ArrowGapUp        = 0.5;       // Gap for arrow up        
input double           ArrowGapDn        = 0.5;       // Gap for arrow down
input bool             ArrowOnFirst      = true;      // Arrow on first bars
input bool             Interpolate       = true;             // Interpolate in mtf mode


double bup[],bdn[],ma[],count[],arrowu[],arrowd[],trend[];
string indicatorFileName;
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,JmaLength,JmaPhase,JmaDouble,JmaPrice,AtrPeriod,AtrMultiplier,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,ArrowsWidth,ArrowUpColor,ArrowDnColor,ArrowCodeUp,ArrowCodeDn,ArrowGapUp,ArrowGapDn,ArrowOnFirst,_buff,_ind)

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int OnInit()
{
   IndicatorBuffers(7);
   SetIndexBuffer(0,bup,   INDICATOR_DATA); SetIndexStyle(0,DRAW_LINE);SetIndexLabel(0,"Jkc-b0-bup");
   SetIndexBuffer(1,bdn,   INDICATOR_DATA); SetIndexStyle(1,DRAW_LINE);SetIndexLabel(1,"Jkc-b1-bdn");
   SetIndexBuffer(2,ma,    INDICATOR_DATA); SetIndexStyle(2,DRAW_LINE);SetIndexLabel(2,"Jkc-b2-ma");
   SetIndexBuffer(3,arrowu,INDICATOR_DATA); SetIndexStyle(3,ShowArrows ? DRAW_ARROW : DRAW_NONE,EMPTY,ArrowsWidth,ArrowUpColor); SetIndexArrow(3,ArrowCodeUp);  
   SetIndexBuffer(4,arrowd,INDICATOR_DATA); SetIndexStyle(4,ShowArrows ? DRAW_ARROW : DRAW_NONE,EMPTY,ArrowsWidth,ArrowDnColor); SetIndexArrow(4,ArrowCodeDn);
   SetIndexBuffer(5,trend, INDICATOR_CALCULATIONS);SetIndexLabel(5,"Jkc-b4-trend");
   SetIndexBuffer(6,count, INDICATOR_CALCULATIONS);SetIndexLabel(6,"Jkc-b3-count");   
  
   
   indicatorFileName = WindowExpertName();
   TimeFrame         = fmax(TimeFrame,_Period);
  
   IndicatorShortName(timeFrameToString(TimeFrame)+" Jurik KC 1.01 MTF-rk");
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason){}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int OnCalculate (const int       rates_total,
                 const int       prev_calculated,
                 const datetime& time[],
                 const double&   open[],
                 const double&   high[],
                 const double&   low[],
                 const double&   close[],
                 const long&     tick_volume[],
                 const long&     volume[],
                 const int&      spread[] )

{
   int i,counted_bars=prev_calculated;
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = fmin(rates_total-counted_bars,rates_total-1); count[0] = limit;
         if (TimeFrame != _Period)
         {
            limit = (int)fmax(limit,fmin(rates_total-1,_mtfCall(5,0)*TimeFrame/_Period));
            for (i=limit;i>=0 && !_StopFlag; i--)
            {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                  int x = y;
                  if (ArrowOnFirst)
                        {  if (i<rates_total-1) x = iBarShift(NULL,TimeFrame,Time[i+1]);               }
                  else  {  if (i>0)             x = iBarShift(NULL,TimeFrame,Time[i-1]); else x = -1;  }
                     bup[i]    = _mtfCall(0,y);
   	               bdn[i]    = _mtfCall(1,y);
   	               ma[i]     = _mtfCall(2,y);
                     arrowu[i] = EMPTY_VALUE;
                     arrowd[i] = EMPTY_VALUE;
                     if (x!=y)
                     {
                       arrowu[i] = _mtfCall(3,y);
                       arrowd[i] = _mtfCall(4,y);
                     }
     
                     //
                     //
                     //
                     //
                     //
                     
                      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 dtime = iTime(NULL,TimeFrame,y);
                         for(n = 1; (i+n)<rates_total && Time[i+n] >= dtime; n++) continue;	
                         for(k = 1; k<n && (i+n)<rates_total && (i+k)<rates_total; k++)
                         { 
                           _interpolate(bup);   
                           _interpolate(bdn);  
                           _interpolate(ma);  
                         }           
            }
    return(rates_total);
    }
    
    //
    //
    //
    //
    //

    for(i = limit; i >= 0; i--)
    {
         double atr = iATR(NULL,0,AtrPeriod,i);
            ma[i]  = iDSmooth(getPrice(JmaPrice,open,close,high,low,i,rates_total),JmaLength,JmaPhase,JmaDouble,i);
            bup[i] = ma[i]+AtrMultiplier*atr;
            bdn[i] = ma[i]-AtrMultiplier*atr; 
            arrowu[i] = EMPTY_VALUE;
            arrowd[i] = EMPTY_VALUE;
            trend[i]  = (close[i]>=bup[i]) ? 1 : (close[i]<=bdn[i]) ? -1 : 0;  
            if (i<rates_total-1 && trend[i]!=trend[i+1])
            {
               if (trend[i] ==  1) arrowu[i] = fmin(bup[i],high[i])+iATR(NULL,0,15,i)*ArrowGapUp;
               if (trend[i] == -1) arrowd[i] = fmax(bdn[i], low[i])-iATR(NULL,0,15,i)*ArrowGapDn;
            } 
   }
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0; 
      if (trend[whichBar] != trend[whichBar+1])
      if (trend[whichBar] == 1)
            doAlert(" crossed upper band");
      else  doAlert(" crossed lower band");       
   }
return(rates_total);           
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

double wrk[][20];

#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,sqrt(length),phase,i,s),sqrt(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; for(k=0; 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 = 0;
            if (wrk[r][avolty+s] > 0)
                  dVolty = wrk[r][volty+s]/wrk[r][avolty+s];   
	               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]);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     1
#define _priceInstancesSize 4
double workHa[][_priceInstances*_priceInstancesSize];
double getPrice(int tprice, const double& open[], const double& close[], const double& high[], const double& low[], int i, int bars, int instanceNo=0)
{
  if (tprice>=pr_haclose)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars); instanceNo*=_priceInstancesSize; int r = bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen  = (r>0) ? (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0 : (open[i]+close[i])/2;;
         double haClose = (open[i]+high[i]+low[i]+close[i]) / 4.0;
         if (_prHABF(tprice))
               if (high[i]!=low[i])
                     haClose = (open[i]+close[i])/2.0+(((close[i]-open[i])/(high[i]-low[i]))*MathAbs((close[i]-open[i])/2.0));
               else  haClose = (open[i]+close[i])/2.0; 
         double haHigh  = fmax(high[i], fmax(haOpen,haClose));
         double haLow   = fmin(low[i] , fmin(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 (tprice)
         {
            case pr_haclose:
            case pr_habclose:    return(haClose);
            case pr_haopen:   
            case pr_habopen:     return(haOpen);
            case pr_hahigh: 
            case pr_habhigh:     return(haHigh);
            case pr_halow:    
            case pr_hablow:      return(haLow);
            case pr_hamedian:
            case pr_habmedian:   return((haHigh+haLow)/2.0);
            case pr_hamedianb:
            case pr_habmedianb:  return((haOpen+haClose)/2.0);
            case pr_hatypical:
            case pr_habtypical:  return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:
            case pr_habweighted: return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:  
            case pr_habaverage:  return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
            case pr_habtbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
            case pr_hatbiased2:
            case pr_habtbiased2:
               if (haClose>haOpen)  return(haHigh);
               if (haClose<haOpen)  return(haLow);
                                    return(haClose);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (tprice)
   {
      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);        
      case pr_tbiased2:   
               if (close[i]>open[i]) return(high[i]);
               if (close[i]<open[i]) return(low[i]);
                                     return(close[i]);        
   }
   return(0);
}

//
//
//
//
//

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("");
}

//+------------------------------------------------------------------+
//
//
//
//

void doAlert(string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
      if (previousAlert != doWhat || previousTime != Time[0]) {
          previousAlert  = doWhat;
          previousTime   = Time[0];

          //
          //
          //
          //
          //

          message = timeFrameToString(_Period)+" "+_Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" jurik keltner channel "+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(_Symbol+" jurik keltner channel ",message);
             if (alertsSound)   PlaySound(soundFile);
      }
}






