//------------------------------------------------------------------+
// Stochastic Momentum Index developed by William Blau              |
//                                              mladen              |
// phase accumulation adaption by Krellian and Mladen               |
//+-----------------------------------------------------------------+

#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"

#property indicator_separate_window
#property indicator_buffers 10
#property indicator_color1  clrRed
#property indicator_color2  clrSilver
#property indicator_color3  clrLimeGreen
#property indicator_color4  clrKhaki
#property indicator_style2  STYLE_DOT
#property strict

//
//
//
//
//

#import "dynamicZone.dll"
   double dzBuyP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision );
   double dzSellP(double& sourceArray[],double probabiltyValue, int lookBack, int bars, int i, double precision );
#import

//
//
//
//
//
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 MA
   ma_lwma,   // Linear weighted MA
   ma_tema    // Triple exponential moving average - TEMA
};
enum enColorOn
{
   cc_onSlope,   // Change color on slope change
   cc_onMiddle,  // Change color on middle line cross
   cc_onLevels   // Change color on outer levels cross
};

extern enTimeFrames    TimeFrame          = tf_cu;   // Time frame
input double          PaFilter               = 1.0;              // Phase accumulation filter
input double          PaCycles               = 1.0;              // Phase accumulation cycles 
input enPrices        PaPrice                = pr_hamedian;      // Phase accumulation price to use
input int             Smooth1                = 6;                // Smi first average period
input int             Smooth2                = 8;                // Smi second average period 
input enMaTypes       MaMethod               = ma_smma;          // Smi Average type
input int             DzLookBackBars         = 70;               // Dynamic zone look back period
input double          DzStartBuyProbability  = 0.10;             // Dynamic zone buy probability
input double          DzStartSellProbability = 0.10;             // Dynamic zone sell probability
input enColorOn       ColorOn                = cc_onSlope;       // Color change on :
input color           ColorUp                = clrLimeGreen;     // Color for up
input color           ColorDown              = clrPaleVioletRed; // Color for down
input color           ShadowColor            = clrGray;          // Shadow color
input int             LineWidth              = 3;                // Main line width
input int             ShadowWidth            = 6;                // Shadow width (<=0 main line width+3) 
input bool            alertsOn               = false;            // Turn alerts on?
input bool            alertsOnCurrent        = false;            // Alerts on still opened bar?
input bool            alertsMessage          = true;             // Alerts should display message?
input bool            alertsSound            = false;            // Alerts should play a sound?
input bool            alertsNotify           = false;            // Alerts should send a notification?
input bool            alertsEmail            = false;            // Alerts should send an email?
input string          soundFile              = "alert2.wav";     // Sound file
input bool            arrowsVisible          = false;            // Arrows visible?
input bool            arrowsOnNewest         = false;            // Arrows on newest mtf bar?
input string          arrowsIdentifier       = "pasmi Arrows1";  // Unique ID for arrows
input double          arrowsUpperGap         = 1.0;              // Upper arrow gap
input double          arrowsLowerGap         = 1.0;              // Lower arrow gap
input color           arrowsUpColor          = clrLimeGreen;     // Upper arrow color
input color           arrowsDnColor          = clrOrange;        // Lower arrow color
input int             arrowsUpCode           = 241;              // Upper arrow code
input int             arrowsDnCode           = 242;              // Lower arrow code
input bool            Interpolate            = true;             // Interpolate in multi time frame mode on/off?

double smi[],buffer1da[],buffer1db[],buffer1ua[],buffer1ub[],bli[],zli[],sli[],trend[],shadowa[],shadowb[],count[];
string indicatorFileName;
#define _mtfCall(_buff,_y) iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PaFilter,PaCycles,PaPrice,Smooth1,Smooth2,MaMethod,DzLookBackBars,DzStartBuyProbability,DzStartSellProbability,ColorOn,ColorUp,ColorDown,ShadowColor,LineWidth,ShadowWidth,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,arrowsVisible,arrowsOnNewest,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,_buff,_y)

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int OnInit()
{
   if (!IsDllsAllowed())
   {
      Alert("and then attach it to the chart again");
      Alert("Please enable DLL imports in the indicator properties");
      Alert("This indicator needs dlls to work");
      return(INIT_FAILED);
   }
   int shadowWidth = (ShadowWidth<=0) ? LineWidth+3 : ShadowWidth;
   IndicatorBuffers(12);
   SetIndexBuffer(0, bli,      INDICATOR_DATA); SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(1, zli,      INDICATOR_DATA); SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(2, sli,      INDICATOR_DATA); SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(3, smi,      INDICATOR_DATA); SetIndexStyle(3,DRAW_LINE,EMPTY,LineWidth);
   SetIndexBuffer(4, shadowa,  INDICATOR_DATA); SetIndexStyle(4,DRAW_LINE,EMPTY,shadowWidth,ShadowColor);
   SetIndexBuffer(5, shadowb,  INDICATOR_DATA); SetIndexStyle(5,DRAW_LINE,EMPTY,shadowWidth,ShadowColor);
   SetIndexBuffer(6, buffer1ua,INDICATOR_DATA); SetIndexStyle(6,DRAW_LINE,EMPTY,LineWidth,ColorUp);
   SetIndexBuffer(7, buffer1ub,INDICATOR_DATA); SetIndexStyle(7,DRAW_LINE,EMPTY,LineWidth,ColorUp);
   SetIndexBuffer(8, buffer1da,INDICATOR_DATA); SetIndexStyle(8,DRAW_LINE,EMPTY,LineWidth,ColorDown);
   SetIndexBuffer(9, buffer1db,INDICATOR_DATA); SetIndexStyle(9,DRAW_LINE,EMPTY,LineWidth,ColorDown);
   SetIndexBuffer(10,trend);
   SetIndexBuffer(11,count);
   
   indicatorFileName = WindowExpertName();
  TimeFrame         = (enTimeFrames)timeFrameValue(TimeFrame);
 
   IndicatorSetString(INDICATOR_SHORTNAME,timeFrameToString(TimeFrame)+" Dynamic Zones pa adaptive SMI ("+(string)Smooth1+","+(string)Smooth2+")");
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

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,limit=fmin(rates_total-prev_calculated+1,rates_total-1); count[0] = limit;
            if (TimeFrame!=_Period)
            {
               limit = (int)fmax(limit,fmin(rates_total-1,_mtfCall(11,0)*TimeFrame/_Period));
               if (trend[limit]==-1) { CleanPoint(limit,buffer1da,buffer1db); CleanPoint(limit,shadowa,shadowb); }
               if (trend[limit]== 1) { CleanPoint(limit,buffer1ua,buffer1ub); CleanPoint(limit,shadowa,shadowb); }
               for (i=limit;i>=0 && !_StopFlag; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,time[i]);
                     bli[i]   = _mtfCall(0,y);
                     zli[i]   = _mtfCall(1,y);
                     sli[i]   = _mtfCall(2,y);
                     smi[i]   = _mtfCall(3,y);
                     buffer1da[i] = buffer1db[i] = EMPTY_VALUE;
                     buffer1ua[i] = buffer1ub[i] = EMPTY_VALUE;
                     shadowa[i]   = shadowb[i]   = EMPTY_VALUE;
                     trend[i]  = _mtfCall(10,y);
                     
                     //
                     //
                     //
                     //
                     //
                  
                     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 btime = iTime(NULL,TimeFrame,y);
                         for(n = 1; (i+n)<rates_total && time[i+n] >= btime; n++) continue;	
                         for(k = 1; k<n && (i+n)<rates_total && (i+k)<rates_total; k++) 
                         {
                            _interpolate(bli);
                            _interpolate(zli);
                            _interpolate(sli);
                            _interpolate(smi);
                         }         
              } 
              for (i=limit; i >= 0; i--)
              {
                 if (trend[i] == -1) { PlotPoint(i,buffer1da,buffer1db,smi); PlotPoint(i,shadowa,shadowb,smi); }
                 if (trend[i] ==  1) { PlotPoint(i,buffer1ua,buffer1ub,smi); PlotPoint(i,shadowa,shadowb,smi); }  
	           }               
   return(rates_total);
   } 
   
   //
   //
   //
   //
   // 
      
      double alfa1 = 2.0 / (1.0 + Smooth1);
      double alfa2 = 2.0 / (1.0 + Smooth2);
      int    colorOn = (DzLookBackBars>0) ? ColorOn : cc_onSlope;
      if (trend[limit]==-1) { CleanPoint(limit,buffer1da,buffer1db); CleanPoint(limit,shadowa,shadowb); }
      if (trend[limit]== 1) { CleanPoint(limit,buffer1ua,buffer1ub); CleanPoint(limit,shadowa,shadowb); }
      for (i=limit;i>=0;i--)
      {
         double price   = getPrice(PaPrice,open,close,high,low,i);
         double Length  = iHilbertPhase(price,PaFilter,PaCycles,i,rates_total);
         double highest = high[iHighest(NULL,0,MODE_HIGH,(int)Length,i)];
         double lowest  = low [iLowest (NULL,0,MODE_LOW ,(int)Length,i)];
         double sm      = close[i]-(highest+lowest)*0.5;
         double hl      =           highest-lowest;
         double value1  = iCustomMa(MaMethod,iCustomMa(MaMethod,sm,Smooth1,i,0),Smooth2,i,1);
         double value2  = iCustomMa(MaMethod,iCustomMa(MaMethod,hl,Smooth1,i,2),Smooth2,i,3);
         smi[i] = (value2!=0) ? 100.00 * (value1/(0.5 *value2)) : 0;
            
         bli[i] = dzBuyP (smi, DzStartBuyProbability, DzLookBackBars,rates_total,i,0.001);
         sli[i] = dzSellP(smi, DzStartSellProbability,DzLookBackBars,rates_total,i,0.001);
         zli[i] = dzSellP(smi, 0.5,                   DzLookBackBars,rates_total,i,0.001);
         buffer1da[i] = buffer1db[i] = EMPTY_VALUE;
         buffer1ua[i] = buffer1ub[i] = EMPTY_VALUE;
         shadowa[i]   = shadowb[i]   = EMPTY_VALUE;
            
           switch(colorOn)
           {
               case cc_onLevels:               trend[i] = (smi[i]>bli[i])   ? 1 : (smi[i]<sli[i])   ? -1 : 0; break;
               case cc_onMiddle:               trend[i] = (smi[i]>zli[i])   ? 1 : (smi[i]<zli[i])   ? -1 : 0; break;
               default :  if (i<rates_total-1) trend[i] = (smi[i]>smi[i+1]) ? 1 : (smi[i]<smi[i+1]) ? -1 : trend[i+1];
            }                  
            if (trend[i] == -1) { PlotPoint(i,buffer1da,buffer1db,smi); PlotPoint(i,shadowa,shadowb,smi); }
            if (trend[i] ==  1) { PlotPoint(i,buffer1ua,buffer1ub,smi); PlotPoint(i,shadowa,shadowb,smi); }  
            
            //
            //
            //
            //
            //
            
            if (arrowsVisible)
            {
               string lookFor = arrowsIdentifier+":"+(string)time[i]; ObjectDelete(lookFor);            
               if (i<rates_total-1 && trend[i] != trend[i+1])
               {
                  if (trend[i] == 1) drawArrow(i,arrowsUpColor,arrowsUpCode,false);
                  if (trend[i] ==-1) drawArrow(i,arrowsDnColor,arrowsDnCode, true);
               }
            }
    
      }
   manageAlerts();
return(rates_total);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workHil[][9];
#define _price      0
#define _smooth     1
#define _detrender  2
#define _period     3
#define _instPeriod 4
#define _phase      5
#define _deltaPhase 6
#define _Q1         7
#define _I1         8

double iHilbertPhase(double price, double filter, double cyclesToReach, int i, int bars, int s=0)
{
   if (ArrayRange(workHil,0)!=bars) ArrayResize(workHil,bars);
   int r = bars-i-1; s = s*9;
      
   //
   //
   //
   //
   //
      
      workHil[r][s+_price]      = price; 
      if (r<6) { workHil[r][s+_smooth]=price; return(0); }
      workHil[r][s+_smooth]     = (4.0*workHil[r][s+_price]+3.0*workHil[r-1][s+_price]+2.0*workHil[r-2][s+_price]+workHil[r-3][s+_price])/10.0;
      workHil[r][s+_detrender]  = calcComp(r,_smooth,s);
      workHil[r][s+_Q1]         = 0.15*calcComp(r,_detrender,s)  +0.85*workHil[r-1][s+_Q1];
      workHil[r][s+_I1]         = 0.15*workHil[r-3][s+_detrender]+0.85*workHil[r-1][s+_I1];
      workHil[r][s+_phase]      = workHil[r-1][s+_phase];
      workHil[r][s+_instPeriod] = workHil[r-1][s+_instPeriod];

      //
      //
      //
      //
      //
           
         if (MathAbs(workHil[r][s+_I1])>0)
                     workHil[r][s+_phase] = 180.0/M_PI*MathArctan(fabs(workHil[r][s+_Q1]/workHil[r][s+_I1]));
           
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]>0) workHil[r][s+_phase] = 180.0-workHil[r][s+_phase];
         if (workHil[r][s+_I1]<0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 180.0+workHil[r][s+_phase];
         if (workHil[r][s+_I1]>0 && workHil[r][s+_Q1]<0) workHil[r][s+_phase] = 360.0-workHil[r][s+_phase];

      //
      //
      //
      //
      //
                        
      workHil[r][s+_deltaPhase] = workHil[r-1][s+_phase]-workHil[r][s+_phase];

         if (workHil[r-1][s+_phase]<90.0 && workHil[r][s+_phase]>270.0)
             workHil[r][s+_deltaPhase] = 360.0+workHil[r-1][s+_phase]-workHil[r][s+_phase];
             workHil[r][s+_deltaPhase] = fmax(fmin(workHil[r][s+_deltaPhase],60),7);
      
            //
            //
            //
            //
            //
                  
            double phaseSum = 0; int k=0; for (; phaseSum<cyclesToReach*360.0 && (r-k)>0; k++) phaseSum += workHil[r-k][s+_deltaPhase];
            if (k>0) workHil[r][s+_instPeriod]= k;
                     workHil[r][s+_period] = iEma(workHil[r][s+_instPeriod],filter,i,2);
   return (workHil[r][s+_period]);
}

//
//
//
//
//

double calcComp(int r, int from, int s)
{
   return((0.0962*workHil[r  ][s+from] + 
           0.5769*workHil[r-2][s+from] - 
           0.5769*workHil[r-4][s+from] - 
           0.0962*workHil[r-6][s+from]) * (0.075*workHil[r-1][s+_period] + 0.54));
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

#define _maInstances 4
#define _maWorkBufferx1 1*_maInstances
#define _maWorkBufferx2 2*_maInstances
#define _maWorkBufferx3 3*_maInstances

double iCustomMa(int mode, double price, double length, int i, int instanceNo=0)
{
   int r = Bars-i-1;
   switch (mode)
   {
      case ma_sma   : return(iSma(price,(int)length,r,instanceNo));
      case ma_ema   : return(iEma(price,length,r,instanceNo));
      case ma_smma  : return(iSmma(price,(int)length,r,instanceNo));
      case ma_lwma  : return(iLwma(price,(int)length,r,instanceNo));
      case ma_tema  : return(iTema(price,(int)length,r,instanceNo));
      default       : return(price);
   }
}

//
//
//
//
//

double workSma[][_maWorkBufferx2];
double iSma(double price, int period, int r, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= Bars) ArrayResize(workSma,Bars); instanceNo *= 2; int k;

   workSma[r][instanceNo+0] = price;
   workSma[r][instanceNo+1] = price; for(k=1; k<period && (r-k)>=0; k++) workSma[r][instanceNo+1] += workSma[r-k][instanceNo+0];  
   workSma[r][instanceNo+1] /= 1.0*k;
   return(workSma[r][instanceNo+1]);
}

//
//
//
//
//

double workEma[][_maWorkBufferx1];
double iEma(double price, double period, int r, 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 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 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 workTema[][_maWorkBufferx3];
#define _tema1 0
#define _tema2 1
#define _tema3 2

double iTema(double price, double period, int r,int instanceNo=0)
{
   if (period<=1) return(price);
   if (ArrayRange(workTema,0)!= Bars) ArrayResize(workTema,Bars); instanceNo*=3;

   //
   //
   //
   //
   //
      
   workTema[r][_tema1+instanceNo] = price;
   workTema[r][_tema2+instanceNo] = price;
   workTema[r][_tema3+instanceNo] = price;
   double alpha = 2.0 / (1.0+period);
   if (r>0)
   {
          workTema[r][_tema1+instanceNo] = workTema[r-1][_tema1+instanceNo]+alpha*(price                         -workTema[r-1][_tema1+instanceNo]);
          workTema[r][_tema2+instanceNo] = workTema[r-1][_tema2+instanceNo]+alpha*(workTema[r][_tema1+instanceNo]-workTema[r-1][_tema2+instanceNo]);
          workTema[r][_tema3+instanceNo] = workTema[r-1][_tema3+instanceNo]+alpha*(workTema[r][_tema2+instanceNo]-workTema[r-1][_tema3+instanceNo]); }
   return(workTema[r][_tema3+instanceNo]+3.0*(workTema[r][_tema1+instanceNo]-workTema[r][_tema2+instanceNo]));
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//
//

#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  = 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:     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 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)]);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] == 1) doAlert(whichBar,"up");
         if (trend[whichBar] ==-1) doAlert(whichBar,"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)+" dz pa adaptive smi trend changed to "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsNotify)  SendNotification(message);
          if (alertsEmail)   SendMail(_Symbol+" dz pa adaptive smi ",message);
          if (alertsSound)   PlaySound(soundFile);
       
   }
}

//-------------------------------------------------------------------
//                                                                  
//-------------------------------------------------------------------
//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+(string)Time[i];
   double gap  = iATR(NULL,0,20,i);   
   
      //
      //
      //
      //
      //

      datetime time = Time[i]; if (arrowsOnNewest) time += _Period*60-1;      
      ObjectCreate(name,OBJ_ARROW,0,time,0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i] + arrowsUpperGap * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i]  - arrowsLowerGap * gap);
}




