//------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1  clrLimeGreen
#property indicator_color2  clrOrange
#property indicator_color3  clrOrange
#property indicator_width1  3
#property indicator_width2  3
#property indicator_width3  3
#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_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
};
enum enTimeFrames
{
   tf_cu  = 0,              // current time frame
   tf_m1  = PERIOD_M1,      // 1 minute
   tf_m5  = PERIOD_M5,      // 5 minutes
   tf_m15 = PERIOD_M15,     // 15 minutes
   tf_m30 = PERIOD_M30,     // 30 minutes
   tf_h1  = PERIOD_H1,      // 1 hour
   tf_h4  = PERIOD_H4,      // 4 hours
   tf_d1  = PERIOD_D1,      // daily
   tf_w1  = PERIOD_W1,      // weekly
   tf_mb1 = PERIOD_MN1      // monthly
};

extern enTimeFrames timeFrame   = 0;        // Time frame to use
extern int          period      = 14;       // Calculating period
extern enPrices     Price       = pr_close; // Price
extern double       Divisor     = 3;        // Divisor to use for "ema" calculation
extern double       Filter      = 1;        // Filter 
extern int          Precision   = 5;        // Precision
extern bool         Interpolate = true;     // Interpolate multi time frame data?

double buffer[];
double bufferda[];
double bufferdb[];
double trend[];

string indicatorFileName;
bool   returnBars;

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

int init()
{
   IndicatorBuffers(4);
   SetIndexBuffer(0,buffer,  INDICATOR_DATA);
   SetIndexBuffer(1,bufferda,INDICATOR_DATA);
   SetIndexBuffer(2,bufferdb,INDICATOR_DATA);
   SetIndexBuffer(3,trend   ,INDICATOR_CALCULATIONS);
         indicatorFileName = WindowExpertName();
         returnBars        = timeFrame==-999; 
         timeFrame         = MathMax(timeFrame,_Period);
   return(0);
}

//
//
//
//
//

double work[][2];
#define _change 0
#define _achang 1
int start()
{
   int i,r,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
           int limit=MathMin(Bars-counted_bars,Bars-2);
           if (returnBars) { buffer[0] = MathMin(limit+1,Bars-1); return(0); }
           if (timeFrame!=Period())
           {
               limit = (int)MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,-999,0,0)*timeFrame/Period()));
               if (trend[limit]==-1) CleanPoint(limit,bufferda,bufferdb);
               for (i=limit; i>=0; i--)
               {
                  int y = iBarShift(NULL,timeFrame,Time[i]);
                     trend[i]    = iCustom(NULL,timeFrame,indicatorFileName,tf_cu,period,Price,Divisor,Filter,Precision,3,y);
                     buffer[i]   = iCustom(NULL,timeFrame,indicatorFileName,tf_cu,period,Price,Divisor,Filter,Precision,0,y);
                     bufferda[i] = EMPTY_VALUE;
                     bufferdb[i] = EMPTY_VALUE;
                     if (!Interpolate || ((i>0) && y==iBarShift(NULL,timeFrame,Time[(int)MathMax(i-1,0)]))) continue;
                         datetime time = iTime(NULL,timeFrame,y);
                         int n,x;
                           for(n = 1; (i+n)<(Bars-1) && Time[i+n] >= time; n++) continue;	
                           for(x = 1; x < n && (i+x)<Bars; x++)
                              buffer[i+x] = buffer[i] + (buffer[i+n] - buffer[i]) * x/n;
               }                   
               for (i=limit; i>=0; i--) if (trend[i] == -1) PlotPoint(i,bufferda,bufferdb,buffer);
               return(0);
           }
           if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);

   //
   //
   //
   //
   //

   if (trend[limit]==-1) CleanPoint(limit,bufferda,bufferdb);
   for(i=limit, r=Bars-i-1; i>=0; i--,r++)
   {
      buffer[i]   = iEma(iEma(getPrice(Price,Open,Close,High,Low,i),(double)period/Divisor,Bars,i,0),(double)period/Divisor,Bars,i,1);
      bufferda[i] = EMPTY_VALUE;
      bufferdb[i] = EMPTY_VALUE;
      trend[i]    = trend[i+1];
      
         //
         //
         //
         //
         //
         
         if (Filter>0)
         {
            work[r][_change] = MathAbs(buffer[i]-buffer[i+1]);
            work[r][_achang] = work[r][_change];
            for (int k=1; k<period && (r-k)>=0; k++) work[r][_achang] += work[r-k][_change];
                                                     work[r][_achang] /= 1.0*period;
    
            double stddev = 0; for (int k=0;  k<period && (r-k)>=0; k++) stddev += MathPow(work[r-k][_change]-work[r-k][_achang],2);
                   stddev = MathSqrt(stddev/period); 
            double filter = Filter * stddev;
            if( MathAbs(buffer[i]-buffer[i+1]) < filter ) buffer[i]=buffer[i+1];
         }
         if (NormalizeDouble(buffer[i],Precision)>NormalizeDouble(buffer[i+1],Precision)) trend[i] =  1;
         if (NormalizeDouble(buffer[i],Precision)<NormalizeDouble(buffer[i+1],Precision)) trend[i] = -1;
         if (trend[i] == -1) PlotPoint(i,bufferda,bufferdb,buffer);
   }      
   return(0);
}

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

double workEma[][2];
double iEma(double price, double eperiod, int bars, int r, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= bars) ArrayResize(workEma,bars); r = bars-r-1;

   //
   //
   //
   //
   //
      
   double alpha = 2.0 / (1.0+eperiod);
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+alpha*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

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

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; }
}

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

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;
         
         //
         //
         //
         //
         //
         
         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);
}