//------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-station.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 4
#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
};
enum enDisplay
{
   dis_all, // Display lines and values
   dis_val, // Display linear regression value only
   dis_lin  // Display linear regression lines only
};
enum enFilterWhat
{
   flt_prc, // Filter price
   flt_val, // Filter linear regression value
   flt_all, // Filter price and linear regression value
   flt_no   // No filtering
};

extern int                LrcPeriod    = 50;             // Period for linear regression 
extern enPrices           LrcPrice     = pr_habtbiased2; // Linear regression price
extern int                LrcNo        = 150;            // Number of linear regressions drawn
extern enFilterWhat       FilterWhat   = flt_prc;        // Filter :
extern double             Filter       = 0;              // Filter to use on price (<= 0, no filter)
extern int                FilterPeriod = 0;              // Filter period to use (0 to use lrc period)
extern enDisplay          Display      = dis_lin;        // Display :
extern color              ColorUp      = clrLimeGreen;   // Color when regression sloping up
extern color              ColorDown    = clrOrangeRed;   // Color when regression sloping down
extern color              ColorShadow  = clrDimGray;     // Color for the shadow line
extern int                LinesWidth   = 3;              // Line graph width
extern int                LinesWidthWhenTrendChange = 5; // Lines width when trend change
extern ENUM_LINE_STYLE    ChannelStyle = STYLE_DOT;      // Channel lines style
extern string             UniqueID     = "Lrs1";         // Indicator unique ID

double lr[],lrda[],lrdb[],shadow[],slope[],trend[];
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(6); 
   int lstyle = DRAW_LINE; if (Display==dis_lin) lstyle=DRAW_NONE;
   SetIndexBuffer(0,shadow); SetIndexStyle(0,lstyle,EMPTY,LinesWidth+4,ColorShadow);
   SetIndexBuffer(1,lr);     SetIndexStyle(1,lstyle,EMPTY,LinesWidth  ,ColorUp);
   SetIndexBuffer(2,lrda);   SetIndexStyle(2,lstyle,EMPTY,LinesWidth  ,ColorDown);
   SetIndexBuffer(3,lrdb);   SetIndexStyle(3,lstyle,EMPTY,LinesWidth  ,ColorDown);
   SetIndexBuffer(4,slope); 
   SetIndexBuffer(5,trend); 
   return(0); 
}
int deinit() { ObjectsDeleteAll(0,UniqueID+":"); return(0); }

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
            int limit=MathMin(MathMax(Bars-counted_bars,LrcNo),Bars-1);

   //
   //
   //
   //
   //
   
   int tperiod = FilterPeriod; if (tperiod<=0) tperiod = LrcPeriod;
   int pperiod = (FilterWhat==flt_prc || FilterWhat==flt_all) ? tperiod : 0;
   int vperiod = (FilterWhat==flt_val || FilterWhat==flt_all) ? tperiod : 0;
   if (slope[limit]==-1) CleanPoint(limit,lrda,lrdb);            
   for (int i=limit; i>=0; i--)
   {
     double tslope,error;
         lr[i]    = shadow[i] = iFilter(iLrValue(iFilter(getPrice(LrcPrice,Open,Close,High,Low,i),Filter,pperiod,i,0),LrcPeriod,tslope,error,i),Filter,vperiod,i,1);
         lrda[i]  = EMPTY_VALUE;
         lrdb[i]  = EMPTY_VALUE;
         trend[i] = (tslope>0) ? 1 : (tslope<0)? -1 : (i<Bars-1) ? trend[i+1] : 0;
         slope[i] = (i<Bars-1) ? (lr[i]>lr[i+1]) ? 1 : (lr[i]<lr[i+1]) ? -1 : slope[i+1] : 0;
               if (i<Bars-1 && Display!=dis_val && i<=LrcNo)
               if (trend[i]!=trend[i+1])
                     createLine("",lr[i],lr[i]-tslope*(LrcPeriod-1),i,LinesWidthWhenTrendChange);
               else  createLine("",lr[i],lr[i]-tslope*(LrcPeriod-1),i);
         if (slope[i]==-1) PlotPoint(i,lrda,lrdb,lr);
	}
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//


#define filterInstances 2
#define filterInstancesSize 3
double workFil[][filterInstances*filterInstancesSize];

#define _fchange 0
#define _fachang 1
#define _fprice  2

double iFilter(double tprice, double filter, int period, int i, int instanceNo=0)
{
   if (filter<=0 || period<=0) return(tprice);
   if (ArrayRange(workFil,0)!= Bars) ArrayResize(workFil,Bars); i = Bars-i-1; instanceNo*=filterInstancesSize;
   
   //
   //
   //
   //
   //
   
   workFil[i][instanceNo+_fprice]  = tprice; if (i<1) return(tprice);
   workFil[i][instanceNo+_fchange] = MathAbs(workFil[i][instanceNo+_fprice]-workFil[i-1][instanceNo+_fprice]);
   workFil[i][instanceNo+_fachang] = workFil[i][instanceNo+_fchange];

   for (int k=1; k<period && (i-k)>=0; k++) workFil[i][instanceNo+_fachang] += workFil[i-k][instanceNo+_fchange];
                                            workFil[i][instanceNo+_fachang] /= period;
    
   double stddev = 0; for (int k=0;  k<period && (i-k)>=0; k++) stddev += MathPow(workFil[i-k][instanceNo+_fchange]-workFil[i-k][instanceNo+_fachang],2);
          stddev = MathSqrt(stddev/(double)period); 
   double filtev = filter * stddev;
   if( MathAbs(workFil[i][instanceNo+_fprice]-workFil[i-1][instanceNo+_fprice]) < filtev ) workFil[i][instanceNo+_fprice]=workFil[i-1][instanceNo+_fprice];
   return(workFil[i][instanceNo+_fprice]);
}

//
//
//
//
//

void createLine(string add, double lrs, double lre, int i, int lineWidth=0)
{
   string name = UniqueID+":"+add+(string)i;
   ObjectCreate(0,name,OBJ_TREND,0,0,0);
      ObjectSet(name,OBJPROP_TIME1,Time[i]);
      ObjectSet(name,OBJPROP_TIME2,Time[i+LrcPeriod-1]);
      ObjectSet(name,OBJPROP_PRICE1,lrs);
      ObjectSet(name,OBJPROP_PRICE2,lre);
      ObjectSet(name,OBJPROP_SELECTABLE,false);
      ObjectSet(name,OBJPROP_RAY,false);
      ObjectSet(name,OBJPROP_BACK,true);
      ObjectSet(name,OBJPROP_HIDDEN,true);
      ObjectSet(name,OBJPROP_WIDTH,lineWidth);
      ObjectSet(name,OBJPROP_STYLE,ChannelStyle);
            color  theColor = ColorDown;
               if (lrs>lre) theColor = ColorUp;
               ObjectSet(name,OBJPROP_COLOR,theColor);
}

//
//
//
//
//

double workLr[];
double iLrValue(double value, int period, double& tslope, double& error, int r)
{
   if (ArraySize(workLr)!=Bars) ArrayResize(workLr,Bars); r = Bars-r-1; workLr[r] = value;
   if (r<period || period<2) return(value);

   //
   //
   //
   //
   //

      double sumx=0, sumxx=0, sumxy=0, sumy=0, sumyy=0;
         for (int k=0; k<period; k++)
         {
            double price = workLr[r-k];
                   sumx  += k;
                   sumxx += k*k;
                   sumxy += k*price;
                   sumy  +=   price;
                   sumyy +=   price*price;
         }
         tslope = (period*sumxy-sumx*sumy)/(sumx*sumx-period*sumxx);
         error  = MathSqrt((period*sumyy-sumy*sumy-tslope*tslope*(period*sumxx-sumx*sumx))/(period*(period-2)));
   return((sumy + tslope*sumx)/period);
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if (i>=Bars-3) 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-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; }
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

#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 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);
}