#property copyright "TRENDPOWER"

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1  clrMediumBlue
#property indicator_color2  clrMaroon
#property indicator_color3  clrMaroon
#property indicator_width1  12
#property indicator_width2  12
#property indicator_width3  12
#property indicator_buffers 9
#property strict

#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
};
enum enColorOn
{
   col_colorOnSlope,  // Change color on slope change
   col_colorOnLevelm, // Change color on middle level cross
   col_colorOnLevelo  // Change color on outer level cross
};

extern int       Length          = 75;             // Ema period
extern enPrices  Price           = pr_median;       // Price to use
extern int       flLookBack      = 0;             // Floating levels lookback period
extern double    flLevelUp       = 90;             // Floating levels up level %
extern double    flLevelDown     = 10;             // Floating levels down level %
extern enColorOn colorOn         = col_colorOnSlope; // Color change
extern color     colorUp         = clrMediumBlue; // Color for up
extern color     colorDown       = clrMaroon;  // Color for down
extern color     colorNeutral    = clrDimGray;   // Color for neutral
extern color     colorShadow     = clrLightGray;     // Color for "shadow"
extern int       linesWidth      = 12;              // Lines width
extern bool      AlertsOn        = false;          // Turn alerts on
extern bool      AlertsOnCurrent = false;           // Alerts on current
extern bool      AlertsMessage   = false;           // Alerts message
extern bool      AlertsSound     = false;          // Alerts sound
extern bool      AlertsEmail     = false;          // Alerts email

double avg[],avgda[],avgdb[],avgua[],avgub[],shadow[],slope[],flu[],flm[],fld[];

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(10);
   SetIndexBuffer(0,flu);    SetIndexStyle(0,EMPTY,STYLE_DOT,0,colorUp);
   SetIndexBuffer(1,flm);    SetIndexStyle(1,EMPTY,STYLE_DOT,0,colorNeutral);
   SetIndexBuffer(2,fld);    SetIndexStyle(2,EMPTY,STYLE_DOT,0,colorDown);
   SetIndexBuffer(3,shadow); SetIndexStyle(3,EMPTY,EMPTY,linesWidth+6,colorShadow);
   SetIndexBuffer(4,avg);    SetIndexStyle(4,EMPTY,EMPTY,linesWidth  ,colorNeutral);
   SetIndexBuffer(5,avgda);  SetIndexStyle(5,EMPTY,EMPTY,linesWidth  ,colorDown);
   SetIndexBuffer(6,avgdb);  SetIndexStyle(6,EMPTY,EMPTY,linesWidth  ,colorDown);
   SetIndexBuffer(7,avgua);  SetIndexStyle(7,EMPTY,EMPTY,linesWidth  ,colorUp);
   SetIndexBuffer(8,avgub);  SetIndexStyle(8,EMPTY,EMPTY,linesWidth  ,colorUp);
   SetIndexBuffer(9,slope);
   IndicatorShortName("EMA Adaptive  ("+(string)Length+")");    
   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 (slope[limit]==-1) CleanPoint(limit,avgda,avgdb);
   if (slope[limit]== 1) CleanPoint(limit,avgua,avgub);
   for(int i=limit; i>=0; i--)
   {
      double price = getPrice(Price,Open,Close,High,Low,i);
            avg[i]    = iEma(price,Length+Length*(iRsq(price,Length,i)-0.25),i);
            shadow[i] = avg[i];
            avgda[i]  = EMPTY_VALUE;
            avgdb[i]  = EMPTY_VALUE;
            avgua[i]  = EMPTY_VALUE;
            avgub[i]  = EMPTY_VALUE;
               double min   = avg[ArrayMinimum(avg,flLookBack,i)];
               double max   = avg[ArrayMaximum(avg,flLookBack,i)];
               double range = max-min;
                  flu[i]    = min+flLevelUp*range/100.0;
                  fld[i]    = min+flLevelDown*range/100.0;
                  flm[i]    = min+0.5*range;
      
            //
            //
            //
            //
            //
      
            if (i<Bars-1)
            {
               slope[i] = slope[i+1];
               switch (colorOn)
               {
                  case col_colorOnSlope :
                        if (avg[i]>avg[i+1]) slope[i]= 1;
                        if (avg[i]<avg[i+1]) slope[i]=-1;
                        break;
                  case col_colorOnLevelm :
                        if (avg[i]>flm[i]) slope[i]= 1;
                        if (avg[i]<flm[i]) slope[i]=-1;
                        break;
                  default :
                        slope[i] = 0;
                        if (avg[i]>flu[i]) slope[i]= 1;
                        if (avg[i]<fld[i]) slope[i]=-1;
               }                                             
            }
            if (slope[i]==-1) PlotPoint(i,avgda,avgdb,avg);
            if (slope[i]== 1) PlotPoint(i,avgua,avgub,avg);
   }   
   if (AlertsOn)
   {
      int whichBar = 1; if (AlertsOnCurrent) whichBar = 0;
      if (slope[whichBar] != slope[whichBar+1])
      {
         if (slope[whichBar] == 1) doAlert(" ema (r-squared) adaptive state changed to up");
         if (slope[whichBar] ==-1) doAlert(" ema (r-squared) adaptive state changed to down");
      }         
   }
   return(0);           
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//



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 = _Symbol+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+doWhat;
             if (AlertsMessage) Alert(message);
             if (AlertsEmail)   SendMail(_Symbol+" ema (r-squared) adaptive",message);
             if (AlertsSound)   PlaySound("alert2.wav");
      }
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

double workEma[][1];
double iEma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= Bars) ArrayResize(workEma,Bars); r=Bars-r-1;

   //
   //
   //
   //
   //
      
   workEma[r][instanceNo] = price;
   if (r>0 && period>=1)
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+(2.0/(1.0+period))*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//
//
//
//
//

double workRsq[][1];
double iRsq(double price, double period, int i, int instanceNo=0)
{
   if (ArrayRange(workRsq,0) != Bars) ArrayResize(workRsq,Bars); i = Bars-i-1;
  
   //
   //
   //
   //
   //

      workRsq[i][instanceNo] = price;

         double SumX  = 0;
         double SumXX = 0;
         double SumXY = 0;
         double SumYY = 0;
         double SumY  = 0;
 
                  for(int k=0; k<period && (i-k)>=0; k++)
                  {
                     double tprice = workRsq[i-k][instanceNo];
                        SumX  += (k+1); 
                        SumXX += (k+1)*(k+1);
                        SumXY += (k+1)*tprice;
                        SumYY +=       tprice*tprice;
                        SumY  +=       tprice;
                  }
   
         double Q1  = SumXY - SumX*SumY/period;
         double Q2  = SumXX - SumX*SumX/period;
         double Q3  = SumYY - SumY*SumY/period;
         return((Q1*Q1)/(Q2*Q3));
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

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 priceInstances 1
double workHa[][priceInstances*4];
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*=4;
         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 (tprice)
         {
            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);        
            case pr_hatbiased2:
               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);
}   