//------------------------------------------------------------------
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"
//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2



//
//
//
//
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
};
enum  enMaTypes
      {
         ma_sma,                                        // Simple moving average
         ma_ema,                                        // Exponential moving average
         ma_smma,                                       // Smoothed moving average
         ma_lwma,                                       // Linear weighted moving average
         ma_linr                                        // Least squares moving average
      };

extern enTimeFrames      TimeFrame                = tf_cu;           // Time frame
extern int               BandsPeriod              = 10;              // Bands period
extern enMaTypes         BandsMaType              = ma_sma;          // Bands average type
extern enPrices          Price                    = pr_typical;      // Price
extern bool              alertsOn                 = false;           // Turn alerts on?
extern bool              alertsOnCurrent          = false;           // Alerts on still opened bar?
extern bool              alertsMessage            = true;            // Alerts should display message?
extern bool              alertsSound              = false;           // Alerts should play a sound?
extern bool              alertsNotify             = false;           // Alerts should send a notification?
extern bool              alertsEmail              = false;           // Alerts should send an email?
extern string            soundFile                = "alert2.wav";    // Sound file
extern color             ColorUp                  = clrLimeGreen;    // Color for up
extern color             ColorDn                  = clrOrangeRed;    // Color for down
extern color             ColorNe                  = clrGray;         // Color for bands
bool               verticalLinesVisible     = false;           // Show vertical lines
input bool               linesOnNewest            = true;            // Vertical lines drawn on newest bar of higher time frame bar true/false?
input string             verticalLinesID          = "bb Lines2";     // Vertical lines id
input color              verticalLinesUpColor     = clrBlue;         // Vertical lines up color
input color              verticalLinesDnColor     = clrRed;          // Vertical lines down color
input ENUM_LINE_STYLE    verticalLinesStyle       = STYLE_SOLID;     // Vertical lines color
input int                verticalLinesWidth       = 0;               // Vertical lines width

//Forex-Station button template start41; copy and paste
extern string             button_note1            = "------------------------------";
extern int                btn_Subwindow           = 0;                               // What window to put the button on
extern ENUM_BASE_CORNER   btn_corner              = CORNER_LEFT_UPPER;               // button corner on chart for anchoring
extern string             btn_text                = "KELTNER";                       // a button name
extern string             btn_Font                = "Arial";                         // button font name
extern int                btn_FontSize            = 9;                               // button font size               
extern color              btn_text_ON_color       = clrLime;                         // ON color when the button is turned on
extern color              btn_text_OFF_color      = clrRed;                          // OFF color when the button is turned off
extern color              btn_background_color    = clrDimGray;                      // background color of the button
extern color              btn_border_color        = clrBlack;                        // border color the button
extern int                button_x                = 20;                              // x coordinate of the button     
extern int                button_y                = 25;                              // y coordinate of the button     
extern int                btn_Width               = 80;                              // button width
extern int                btn_Height              = 20;                              // button height
extern string             soundBT                 = "tick.wav";                      // sound file when the button is pressed
extern string             UniqueButtonID          = "KeltnerChannel";                // Unique ID for each button        
extern string             button_note2            = "------------------------------";
//"",btn_Subwindow,btn_corner,btn_text,btn_Font,btn_FontSize,btn_text_ON_color,btn_text_OFF_color,btn_background_color,btn_border_color,button_x,button_y,btn_Width,btn_Height,soundBT,UniqueButtonID,"",
bool show_data = true;
string indicatorFileName, IndicatorName, IndicatorObjPrefix, buttonId;
//Forex-Station button template end41; copy and paste

input bool                Interpolate             = true;             // Interpolate in multi time frame mode on/off?
//
//
//
//
//

double zero[],ma1Ua[],ma1Ub[],amax[],amin[],trend[],count[];
//#define _mtfCall(_buff,_y) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,BandsPeriod,BandsMaType,Price,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ColorUp,ColorDn,ColorNe,verticalLinesVisible,linesOnNewest,verticalLinesID,verticalLinesUpColor,verticalLinesDnColor,verticalLinesStyle,verticalLinesWidth,"",btn_Subwindow,btn_corner,btn_text,btn_Font,btn_FontSize,btn_text_ON_color,btn_text_OFF_color,btn_background_color,btn_border_color,button_x,button_y,btn_Width,btn_Height,soundBT,UniqueButtonID,"",_buff,_y)
#define _mtfCall(_buff,_y) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,BandsPeriod,BandsMaType,Price,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ColorUp,ColorDn,ColorNe,linesOnNewest,verticalLinesID,verticalLinesUpColor,verticalLinesDnColor,verticalLinesStyle,verticalLinesWidth,"",btn_Subwindow,btn_corner,btn_text,btn_Font,btn_FontSize,btn_text_ON_color,btn_text_OFF_color,btn_background_color,btn_border_color,button_x,button_y,btn_Width,btn_Height,soundBT,UniqueButtonID,"",_buff,_y)
//+------------------------------------------------------------------------------------------------------------------+
//Forex-Station button template start42; copy and paste
string GenerateIndicatorName(const string target) 
{
   string name = target;
   int try = 2;
   while (WindowFind(name) != -1)
      name = target + " #" + IntegerToString(try++);
   return name;
}
//+------------------------------------------------------------------------------------------------------------------+
int OnInit()
{
   IndicatorName = GenerateIndicatorName(btn_text);
   IndicatorObjPrefix = "__" + IndicatorName + "__";
   IndicatorDigits(Digits);
   
   ChartSetInteger(ChartID(), CHART_EVENT_MOUSE_MOVE, 1);
   buttonId = IndicatorObjPrefix + UniqueButtonID;
   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);

   double val;
   if (GlobalVariableGet(buttonId + "_visibility", val))
      show_data = val != 0;
   
// put init() here
   OnInit2();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------------------------------------------------------+
void OnDeinit(const int reason) { 
     ObjectsDeleteAll(ChartID(), buttonId);
     OnDeinit2();
}
//+------------------------------------------------------------------+
void createButton(string buttonID,string buttonText,int width2,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_BORDER_TYPE,BORDER_RAISED);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XSIZE,width2);
      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);
}
//+------------------------------------------------------------------+
void handleButtonClicks()
{
   if (ObjectGetInteger(ChartID(), buttonId, OBJPROP_STATE))
   {
      ObjectSetInteger(ChartID(), buttonId, OBJPROP_STATE, false);
      show_data = !show_data;
      GlobalVariableSet(buttonId + "_visibility", show_data ? 1.0 : 0.0);
   }
}
//+------------------------------------------------------------------------------------------------------------------+
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);     

      if (show_data)
         {
          ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_ON_color);
          OnInit2();
         }
      else
      {
       ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_OFF_color);
       for (int ForexStation=0; ForexStation<indicator_buffers; ForexStation++)
           SetIndexStyle(ForexStation,DRAW_NONE);
       OnDeinit2();
      }
}
//Forex-Station button template end42; copy and paste
//+------------------------------------------------------------------------------------------------------------------+
int OnInit2()
{
         IndicatorBuffers(7);
         SetIndexBuffer(0,zero);  SetIndexStyle(0,DRAW_LINE,EMPTY,EMPTY,ColorUp);
         SetIndexBuffer(1,ma1Ua); SetIndexStyle(1,DRAW_LINE,EMPTY,EMPTY,ColorDn);
         SetIndexBuffer(2,ma1Ub); SetIndexStyle(2,DRAW_LINE,EMPTY,EMPTY,ColorDn);
         SetIndexBuffer(3,amax);  SetIndexStyle(3,DRAW_LINE,EMPTY,EMPTY,ColorNe);
         SetIndexBuffer(4,amin);  SetIndexStyle(4,DRAW_LINE,EMPTY,EMPTY,ColorNe);
         SetIndexBuffer(5,trend);
         SetIndexBuffer(6,count);
         
      
      //
      //
      //
      //
      //
     
        indicatorFileName = WindowExpertName();
        TimeFrame         = (enTimeFrames)timeFrameValue(TimeFrame);    
        IndicatorShortName(timeFrameToString(TimeFrame)+"  keltner ch");
return(0);
}
//+------------------------------------------------------------------------------------------------------------------+
 
int OnDeinit2() 
{   
     ObjectsDeleteAll(0,verticalLinesID+":");  
     return(0);
}
//+------------------------------------------------------------------------------------------------------------------+
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=MathMin(rates_total-counted_bars,rates_total-1); count[0]=limit;
           if (TimeFrame!=_Period)
           {
               limit = (int)MathMax(limit,MathMin(rates_total-1,_mtfCall(6,0)*TimeFrame/_Period));
                if (trend[limit]== -1) CleanPoint(limit,ma1Ua,ma1Ub);
               for ( i=limit; i>=0 && !_StopFlag; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,time[i]);
                     zero[i] = _mtfCall(0,y);
                     amax[i] = _mtfCall(3,y);
                     amin[i] = _mtfCall(4,y);
                     trend[i] = _mtfCall(5,y);
                     ma1Ua[i]   = ma1Ub[i]  = EMPTY_VALUE;
                     
                     
                     
                      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(zero);       
                    _interpolate(amax);
                    _interpolate(amin);
                   }  
               }
                for(i=limit;i>=0; i--) 
         {
           
            if (trend[i] == -1)  PlotPoint(i,ma1Ua,ma1Ub,zero);
         }
               
               return(rates_total);
           }

   //
   //
   //
   //
   //
     if (trend[limit]== -1) CleanPoint(limit,ma1Ua,ma1Ub);  
     for( i=limit; i>=0 && !_StopFlag; i--)
     {
         double price = getPrice(Price,open,close,high,low,i);
                zero[i]  = iCustomMa(BandsMaType,price,BandsPeriod,i,rates_total,0);
          double     avg = findAvg(BandsPeriod, i);
               amax[i]  = zero[i]+ avg;
               amin[i]  = zero[i]- avg;
   	        
               trend[i] = (i<rates_total-1) ? (zero[i]>zero[i+1]) ? 1 : (zero[i]<zero[i+1]) ? -1 :  trend[i+1]  : 0; 
                      
                                 
              ma1Ua[i] = ma1Ub[i] = EMPTY_VALUE;
              if (trend[i] == -1)  PlotPoint(i,ma1Ua,ma1Ub,zero);
               //
               //
               //
               
               if (verticalLinesVisible)
               {
                  string tlookFor = verticalLinesID+":"+(string)time[i]; if (ObjectFind(0,tlookFor)==0) ObjectDelete(0,tlookFor);   
                  if (i<(rates_total-1) && trend[i]!=trend[i+1])
                  {
                    if (trend[i] == 1) drawLine(i,verticalLinesUpColor);
                    if (trend[i] ==-1) drawLine(i,verticalLinesDnColor);
                  }               
               }
      }
      if (alertsOn)
      {
         int whichBar = 1; if (alertsOnCurrent) whichBar = 0; 
         if (trend[whichBar] != trend[whichBar+1])
         {
            if (trend[whichBar] == 1) doAlert(" up");
            if (trend[whichBar] ==-1) doAlert(" down");       
         }         
      }              
      return(rates_total);
}


//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
// 
double findAvg(int period, int shift)
{
    double sum = 0;

    for (int i = shift; i < (shift + period); i++)
        sum += High[i] - Low[i];

    sum = sum / period;

    return(sum);
}
//
//
//
//


//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//
#define _maInstances 1
#define _maWorkBufferx1 1*_maInstances

double iCustomMa(int mode, double price, double length, int r, int bars, int instanceNo=0)
{
   r = bars-r-1;
   switch (mode)
   {
      case ma_sma   : return(iSma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_ema   : return(iEma(price,length,r,bars,instanceNo));
      case ma_smma  : return(iSmma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_lwma  : return(iLwma(price,(int)ceil(length),r,bars,instanceNo));
      case ma_linr  : return(iLinr(price,(int)ceil(length),r,bars,instanceNo));
      default       : return(price);
   }
}

//
//
//
//
//

double workSma[][_maWorkBufferx1];
double iSma(double price, int period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= _bars) ArrayResize(workSma,_bars);

   workSma[r][instanceNo+0] = price;
   double avg = price; int k=1;  for(; k<period && (r-k)>=0; k++) avg += workSma[r-k][instanceNo+0];  
   return(avg/(double)k);
}

//
//
//
//
//

double workEma[][_maWorkBufferx1];
double iEma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= _bars) ArrayResize(workEma,_bars);

   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 workSmma[][_maWorkBufferx1];
double iSmma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workSmma,0)!= _bars) ArrayResize(workSmma,_bars);

   workSmma[r][instanceNo] = price;
   if (r>1 && period>1)
          workSmma[r][instanceNo] = workSmma[r-1][instanceNo]+(price-workSmma[r-1][instanceNo])/period;
   return(workSmma[r][instanceNo]);
}

//
//
//
//
//

double workLwma[][_maWorkBufferx1];
double iLwma(double price, double period, int r, int _bars, int instanceNo=0)
{
   if (ArrayRange(workLwma,0)!= _bars) ArrayResize(workLwma,_bars);
   
   workLwma[r][instanceNo] = price; if (period<=1) return(price);
      double sumw = period;
      double sum  = period*price;

      for(int k=1; k<period && (r-k)>=0; k++)
      {
         double weight = period-k;
                sumw  += weight;
                sum   += weight*workLwma[r-k][instanceNo];  
      }             
      return(sum/sumw);
}

//
//
//
//
//

double workLinr[][_maWorkBufferx1];
double iLinr(double price, int period, int r, int bars, int instanceNo=0)
{
   if (ArrayRange(workLinr,0)!= bars) ArrayResize(workLinr,bars);

   //
   //
   //
   //
   //
   
      period = fmax(period,1);
      workLinr[r][instanceNo] = price;
      if (r<period) return(price);
         double lwmw = period; double lwma = lwmw*price;
         double sma  = price;
         for(int k=1; k<period && (r-k)>=0; k++)
         {
            double weight = period-k;
                   lwmw  += weight;
                   lwma  += weight*workLinr[r-k][instanceNo];  
                   sma   +=        workLinr[r-k][instanceNo];
         }             
   
   return(3.0*lwma/lwmw-2.0*sma/period);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

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)+" BB stops state changed to "+doWhat;
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(_Symbol+" BB stops ",message);
             if (alertsSound)   PlaySound(soundFile);
      }
}

//
//
//
//
//

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 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);
}

//
//
//

void drawLine(int i,color theColor)
{
      string name = verticalLinesID+":"+(string)Time[i];
   
      //
      //
      //
      
      datetime ltime = Time[i]; if (linesOnNewest) ltime += PeriodSeconds(_Period)-1;  
      ObjectCreate(name,OBJ_VLINE,0,ltime,0);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         ObjectSet(name,OBJPROP_STYLE,verticalLinesStyle);
         ObjectSet(name,OBJPROP_WIDTH,verticalLinesWidth);
         ObjectSet(name,OBJPROP_BACK,true);
}  

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; }
}
