//+------------------------------------------------------------------+
//|                                                        frama.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"
#property description "Thanks to Mladen for frama ribbon   "
#property description "Replaced frama with jma-dpwma @2021   "
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_width3  3
#property indicator_width4  3


//
//
enum enTimeFrames
{
   tf_cu  = PERIOD_CURRENT, // 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_mn1 = PERIOD_MN1,     // Monthly
   tf_n1  = -1,             // First higher time frame
   tf_n2  = -2,             // Second higher time frame
   tf_n3  = -3              // Third higher time frame
};

//
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 enTimeFrames    TimeFrame          = tf_cu;      // Timeframe to use
extern int             DpwmaLength = 12;              // Dpwma length
extern enPrices        DpwmaPrice  = pr_close;        // Dpwma price to use
extern double          DpwmaPower  = 2.0;             // Dpwma power
extern int             JmaLength   = 26;              // Jma length
extern double          JmaPhase    = 0;               // Jma phase
extern bool            JmaDouble   = false;           // Jma double 
extern enPrices        JmaPrice    = pr_close;        // Jma Price to use
input int             WickWidth        = 1;                 // Candle wick width
input int             BodyWidth        = 2;                 // If auto width = false then use this
input bool            UseAutoWidth     = true;              // Auto adjust candle body width
extern color           color1                = clrMediumSeaGreen;      // Bearish candle wick color
extern color           color2                = clrCrimson;      // Bullish candle wick color
extern color           color3                = clrMediumSeaGreen;      // Bearish candle body color
extern color           color4                = clrCrimson;      // Bullish candle body color


extern bool               alertsOn         = false;          // Turn alerts on
extern bool               alertsOnCurrent  = false;          // Alerts on current (still opened) bar?
extern bool               alertsMessage    = true;           // Alerts should display a pop-up message?
extern bool               alertsSound      = true;           // Alerts should play an alert sound?
extern bool               alertsEmail      = false;          // Alerts should send an email?
extern bool               alertsNotify     = false;          // Alerts should send push notification?
//extern bool               Interpolate      = true;           // Interpolate in multi time frame
//template code 
extern string             button_note1          = "------------------------------";
extern int                btn_Subwindow = 0;
extern ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER; 
extern string             btn_text              = "DJCANDLE";
extern string             btn_Font              = "Arial";
extern int                btn_FontSize          = 10;                            
extern color              btn_text_ON_color     = clrLime;
extern color              btn_text_OFF_color    = clrRed;
extern string             btn_pressed           = "DJCANDLE";            
extern string             btn_unpressed         = "DJCANDLE";
extern color              btn_background_color  = clrDimGray;
extern color              btn_border_color      = clrBlack;
extern int                button_x              = 200;                                 
extern int                button_y              = 0;                                   
extern int                btn_Width             = 75;                                 
extern int                btn_Height            = 20;                                
extern string             soundBT               = "tick.wav";  
extern string             button_note2          = "------------------------------";

bool                      show_data             = true;
string IndicatorName, IndicatorObjPrefix ,buttonId ;

double jBuffer[],jBuffer1[],state[];
double t3wu[];
double t3wd[];
double t3bu[];
double t3bd[];
int candlewidth=0;
string indicatorFileName;
bool   returnBars;


//template code 
string GenerateIndicatorName(const string target)
{
   string name = target;
   int try = 2;
   while (WindowFind(name) != -1)
   {
      name = target + " #" + IntegerToString(try++);
   }
   return name;
}
//template code 

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
if (UseAutoWidth)
   {
      int scale = int(ChartGetInteger(0,CHART_SCALE));
      switch(scale) 
	   {
	      case 0: candlewidth =  1; break;
	      case 1: candlewidth =  1; break;
		   case 2: candlewidth =  2; break;
		   case 3: candlewidth =  3; break;
		   case 4: candlewidth =  6; break;
		   case 5: candlewidth = 14; break;
	   }
	}
	else { candlewidth = BodyWidth; }
   IndicatorBuffers(7);
   SetIndexBuffer(0,t3wu);  SetIndexStyle(0,DRAW_HISTOGRAM,0, WickWidth, color1);
   SetIndexBuffer(1,t3wd);  SetIndexStyle(1,DRAW_HISTOGRAM,0,WickWidth, color2);
   SetIndexBuffer(2,t3bu);  SetIndexStyle(2,DRAW_HISTOGRAM,0,candlewidth, color3);
   SetIndexBuffer(3,t3bd);  SetIndexStyle(3,DRAW_HISTOGRAM,0,candlewidth, color4);
   SetIndexBuffer(4,jBuffer);
   SetIndexBuffer(5,jBuffer1);
   //  SetIndexBuffer(6,jBufferua);
   //  SetIndexBuffer(7,jBufferub);
   //  SetIndexBuffer(8,jBufferda);
   //  SetIndexBuffer(9,jBufferdb);
   SetIndexBuffer(6,state);
   
   
   //template code 
   IndicatorName = GenerateIndicatorName(btn_text);
   IndicatorObjPrefix = "__" + IndicatorName + "__";
   IndicatorShortName(WindowExpertName());
   IndicatorDigits(Digits);
   
     
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame==-99;
   //   TimeFrame         = MathMax(TimeFrame,_Period);
       TimeFrame         = (enTimeFrames)timeFrameValue(TimeFrame);
   IndicatorShortName("Jurik ribbon candles ("+(string)JmaLength+")");
   
       double val;
   if (GlobalVariableGet(IndicatorName + "_visibility", val))
   show_data = val != 0;

   ChartSetInteger(ChartID(), CHART_EVENT_MOUSE_MOVE, 1);
   buttonId = IndicatorObjPrefix+btn_text;
   createButton(buttonId, btn_text, btn_Width, btn_Height, btn_Font, btn_FontSize, btn_background_color, btn_border_color, btn_text_ON_color);
   ObjectSetInteger(ChartID(), buttonId, OBJPROP_YDISTANCE, button_y);
   ObjectSetInteger(ChartID(), buttonId, OBJPROP_XDISTANCE, button_x);
//template code  
            
   return(0);
}

//template code 
void createButton(string buttonID,string buttonText,int width,int height,string font,int fontSize,color bgColor,color borderColor,color txtColor)
{
      ObjectDelete    (ChartID(),buttonID);
      ObjectCreate (ChartID(),buttonID,OBJ_BUTTON,btn_Subwindow,0,0);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_COLOR,txtColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_BGCOLOR,bgColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_BORDER_COLOR,borderColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XSIZE,width);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_YSIZE,height);
      ObjectSetString (ChartID(),buttonID,OBJPROP_FONT,font);
      ObjectSetString (ChartID(),buttonID,OBJPROP_TEXT,buttonText);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_FONTSIZE,fontSize);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_SELECTABLE,0);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_CORNER,btn_corner);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_HIDDEN,1);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XDISTANCE,9999);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_YDISTANCE,9999);
}
//template code     


int deinit()
{
ObjectsDeleteAll(0,"DJCANDLE");
   ObjectsDeleteAll(ChartID(), IndicatorObjPrefix);

   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
 bool recalc = true;

void handleButtonClicks()
{
   if (ObjectGetInteger(ChartID(), buttonId, OBJPROP_STATE))
   {
      ObjectSetInteger(ChartID(), buttonId, OBJPROP_STATE, false);
      show_data = !show_data;
      GlobalVariableSet(IndicatorName + "_visibility", show_data ? 1.0 : 0.0);
      recalc = true;
      start();
   }
}
void OnChartEvent(const int id, 
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
   handleButtonClicks();
   if (id==CHARTEVENT_OBJECT_CLICK && ObjectGet(sparam,OBJPROP_TYPE)==OBJ_BUTTON)
   {
   if (soundBT!="") PlaySound(soundBT);     
   }
}
//template code 
// 
//
//
//
//

int start()
{
//template code 
   handleButtonClicks();
   recalc = false;
   
   start2();
   
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexStyle(2,DRAW_HISTOGRAM);
   SetIndexStyle(3,DRAW_HISTOGRAM);
   
   if (show_data)
      {
      ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_ON_color);
      ObjectSetString(ChartID(),buttonId,OBJPROP_TEXT,btn_unpressed);
      }
      else
      {
      ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_OFF_color);
      ObjectSetString(ChartID(),buttonId,OBJPROP_TEXT,btn_pressed);
      SetIndexStyle (0,DRAW_NONE);
   SetIndexStyle (1,DRAW_NONE);
   SetIndexStyle (2,DRAW_NONE);
   SetIndexStyle(3,DRAW_NONE);
      //template code     
      }
       return(0);
      }
      
       int start2()
  {
if(ChartGetInteger(0,CHART_SCALE) != candlewidth) init(); 
   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 (returnBars) { t3wu[0] = limit+1; return(0); }
            if (TimeFrame != Period())
            {
               limit = (int)MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
              
               for(int i = limit; i >= 0; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                 //  jBuffer[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,DpwmaLength,DpwmaPrice,DpwmaPower,JmaLength,JmaPhase,JmaDouble,JmaPrice,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotify,0,y); 
                //   jBuffer1[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,DpwmaLength,DpwmaPrice,DpwmaPower,JmaLength,JmaPhase,JmaDouble,JmaPrice,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotify,1,y); 
                  state[i]     = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,DpwmaLength,DpwmaPrice,DpwmaPower,JmaLength,JmaPhase,JmaDouble,JmaPrice,WickWidth,BodyWidth,UseAutoWidth,color1,color2,color3,color4,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,alertsNotify,button_note1,btn_Subwindow,btn_corner,btn_text,btn_Font,btn_FontSize,btn_text_ON_color,btn_text_OFF_color,btn_pressed,btn_unpressed,btn_background_color,btn_border_color,button_x,button_y,btn_Width,btn_Height,soundBT,button_note2,6,y); 
                  
         
                  //
                  //
                  //
                  //
                  //
      
                 
                  
                  //
                  //
                  //
                  //
                  //
                  t3wu[i]  =  EMPTY_VALUE; 
          t3wd[i]  =  EMPTY_VALUE;
          t3bu[i]  =  EMPTY_VALUE;
          t3bd[i]  =  EMPTY_VALUE;  
                  
              
                       if (state[i]== 1)
            {
               t3wu[i] = High[i]; 
               t3wd[i] = Low[i];
               t3bu[i] = MathMax(Open[i],Close[i]);
               t3bd[i] = MathMin(Open[i],Close[i]);
            }               
            if (state[i]== -1)
            {
               t3wu[i]  = Low[i];
               t3wd[i]  = High[i];
               t3bu[i] = MathMin(Open[i],Close[i]);
               t3bd[i] = MathMax(Open[i],Close[i]);
            }  
             }             
               return(0); 
            }

   //
   //
   //
   //
   //

      
      for( i = limit; i >= 0; i--)
      {
       
         jBuffer[i]     = iDSmooth(getPrice(JmaPrice,Open,Close,High,Low,i,Bars,0),JmaLength,JmaPhase,JmaDouble,i);
         jBuffer1[i]     = iDpwma(getPrice(DpwmaPrice,Open,Close,High,Low,i,Bars,0)  ,DpwmaLength,DpwmaPower,i);
          t3wu[i]  =  EMPTY_VALUE; 
          t3wd[i]  =  EMPTY_VALUE;
          t3bu[i]  =  EMPTY_VALUE;
          t3bd[i]  =  EMPTY_VALUE;  
           state[i] = state[i+1];
            if (jBuffer[i]>jBuffer1[i]) state[i] =  1;
            if (jBuffer[i]<jBuffer1[i]) state[i] = -1;
            if (state[i]== 1)
            {
               t3wu[i] = High[i]; 
               t3wd[i] = Low[i];
               t3bu[i] = MathMax(Open[i],Close[i]);
               t3bd[i] = MathMin(Open[i],Close[i]);
            }      
            if (state[i]== -1)
            {
               t3wu[i]  = Low[i];
               t3wd[i]  = High[i];
               t3bu[i] = MathMin(Open[i],Close[i]);
               t3bd[i] = MathMax(Open[i],Close[i]);
            }       
           
      }  
             
   manageAlerts();
   return(0);      
}


//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (state[whichBar] != state[whichBar+1])
      {
         if (state[whichBar]== 1) doAlert(whichBar,"trend changed to up");
         if (state[whichBar]==-1) doAlert(whichBar,"trend changed to 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 ribbon "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(Symbol()+" Jurik ribbon ",message);
          if (alertsNotify)  SendNotification(message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
double workDpwma[][2];
double iDpwma(double price, double period, double power, int r, int instanceNo=0)
{
   if (ArraySize(workDpwma)!= Bars) ArrayResize(workDpwma,Bars); r = Bars-r-1; instanceNo*=2;
   
   //
   //
   //
   //
   //

   for (int i=0; i<2; i++)
   {
      workDpwma[r][instanceNo+i] = price;
         double sumw = period;
         double sum  = period*price;

         for(int k=1; k<period && (r-k)>=0; k++)
         {
            double weight = MathPow(period-k,power);
                  sumw  += weight;
                  sum   += weight*workDpwma[r-k][instanceNo+i];  
         }             
         price = sum/sumw;
   }              
return(price);
}
//
//

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,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; 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]);
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

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; }
}

//
//
//
//
//

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("");
}
int timeFrameValue(int _tf)
{
   int add  = (_tf>=0) ? 0 : MathAbs(_tf);
   if (add != 0) _tf = _Period;
   int size = ArraySize(iTfTable); 
      int i =0; for (;i<size; i++) if (iTfTable[i]==_tf) break;
                                   if (i==size) return(_Period);
                                                return(iTfTable[(int)MathMin(i+add,size-1)]);
}
 
 

#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     2
#define _priceInstancesSize 4
double  _priceWorkHa[][_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(_priceWorkHa,0)!= bars) ArrayResize(_priceWorkHa,bars); instanceNo*=_priceInstancesSize; int r = #ifdef __MQL4__ bars-i-1 #else i #endif;
         
         //
         //
         //
         //
         //
         
         double haOpen  = (r>0) ? (_priceWorkHa[r-1][instanceNo+2] + _priceWorkHa[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]))*fabs((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) { _priceWorkHa[r][instanceNo+0] = haLow;  _priceWorkHa[r][instanceNo+1] = haHigh; } 
         else               { _priceWorkHa[r][instanceNo+0] = haHigh; _priceWorkHa[r][instanceNo+1] = haLow;  } 
                              _priceWorkHa[r][instanceNo+2] = haOpen;
                              _priceWorkHa[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);
}