//+------------------------------------------------------------------+
//|                                                              rsi |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"

#property indicator_chart_window
#property indicator_buffers 8


//
//
//
//
//

extern string TimeFrame              = "Current time frame";
extern int    Length                 = 20;
extern ENUM_APPLIED_PRICE Price      = PRICE_CLOSE;
extern double RSIModifier            = 0.9;
extern double LevelUp                =  1;
extern double LevelDown              = -1;
extern double SmoothLength           =   5;
extern double SmoothPhase            =   0;
input bool    signalOnEveryBreak     = false;              // Alerts on every OB/OS break
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           color_UP                = clrForestGreen;      // Bullish  wick color
extern color           color_DOWN              = clrKhaki;      // Bearish  wick color
extern color           color_NEUTRAL           = clrSnow;      // Neutral body color
extern bool   alertsOn               = false;
extern bool   alertsOnZoneEnter      = true;
extern bool   alertsOnZoneExit       = true;
extern bool   alertsOnCurrent        = true;
extern bool   alertsMessage          = true;
extern bool   alertsSound            = false;
extern bool   alertsEmail            = false;
extern bool   verticalLinesVisible   = true;
extern string verticalLinesID        = "RsiSmoothLines";
extern bool   verticalLinesShowBreak   = true;
extern bool   verticalLinesShowRetrace = false;
extern color  verticalLinesUpColor   = DeepSkyBlue;
extern color  verticalLinesDownColor = PaleVioletRed;
extern ENUM_LINE_STYLE verticalLinesStyle = STYLE_DASHDOT;
extern int    verticalLinesWidth     = 0;
extern bool               ShowZones_OnTheMainChart        = true;                 // Display the background zones on the main chart
extern bool               ShowZones_InTheSeparatedWindow1 = false;                 // Display the background zones in the first separated window
extern int                WhatSeparatedWindow1            = 1;
extern bool               ShowZones_InTheSeparatedWindow2 = false;                 // Display the background zones in the second separated window
extern int                WhatSeparatedWindow2            = 2;
extern bool               ShowZones_InTheSeparatedWindow3 = false;                 // Display the background zones in the third separated window
extern int                WhatSeparatedWindow3            = 3;
extern color              ZoneColorUp                     = clrPowderBlue;          // Uptrend Zone color
extern color              ZoneColorDown                   = clrTan;     // Downtrend Zone color
extern string             UniqueZoneID                    = "MACDzones1";  // Unique ID for the zones

//
//
//
//
//

double rsi[];
double UpH[],UpH_bot[],DnH[],DnH_bot[],NuH_top[],NuH_bot[],NuH_topU[],NuH_botD[];
double trend[];
double Dummy = -1;
int candlewidth=0;
//
//
//
//
//

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

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(10);
   SetIndexBuffer(0,UpH,INDICATOR_DATA); 
   SetIndexBuffer(1,DnH,INDICATOR_DATA); 
   SetIndexBuffer(2,NuH_top,INDICATOR_DATA); 
   SetIndexBuffer(3,NuH_bot,INDICATOR_DATA); 
   SetIndexBuffer(4,UpH_bot,INDICATOR_DATA);
   SetIndexBuffer(5,DnH_bot,INDICATOR_DATA);
   SetIndexBuffer(6,NuH_topU,INDICATOR_DATA);
   SetIndexBuffer(7,NuH_botD,INDICATOR_DATA);
   
      SetIndexBuffer(8,rsi);
      
      SetIndexBuffer(9,trend);
      
      
     SetIndexStyle(0,DRAW_HISTOGRAM, 0, WickWidth, color_UP);
        SetIndexStyle(1,DRAW_HISTOGRAM, 0, WickWidth, color_DOWN);
        SetIndexStyle(2,DRAW_HISTOGRAM, 0, candlewidth, color_NEUTRAL);
        SetIndexStyle(3,DRAW_HISTOGRAM, 0, candlewidth, color_NEUTRAL);
        SetIndexStyle(4,DRAW_HISTOGRAM, 0, candlewidth, color_UP);
        SetIndexStyle(5,DRAW_HISTOGRAM, 0, candlewidth, color_DOWN);
       SetIndexStyle(6,DRAW_HISTOGRAM, 0, WickWidth, color_NEUTRAL);
        SetIndexStyle(7,DRAW_HISTOGRAM, 0, WickWidth, color_NEUTRAL);
        
         
         Length = fmax(Length ,1);

   //
   //
   //
   //
   //

         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);

         //
         //
         //
         //
         //
         
         string PriceType;
         switch(Price)
         {
            case PRICE_CLOSE:    PriceType = "Close";    break;  // 0
            case PRICE_OPEN:     PriceType = "Open";     break;  // 1
            case PRICE_HIGH:     PriceType = "High";     break;  // 2
            case PRICE_LOW:      PriceType = "Low";      break;  // 3
            case PRICE_MEDIAN:   PriceType = "Median";   break;  // 4
            case PRICE_TYPICAL:  PriceType = "Typical";  break;  // 5
            case PRICE_WEIGHTED: PriceType = "Weighted"; break;  // 6
         }      

   //
   //
   //
   //
   //

   SetLevelValue(0,LevelUp);
   SetLevelValue(1,LevelDown);
   IndicatorShortName(timeFrameToString(timeFrame)+" RSI ("+Length+","+PriceType+")");
   return(0);
}

//
//
//
//
//

int deinit()
{
   string lookFor       = verticalLinesID+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
   
    lookFor       = UniqueZoneID+":";
       lookForLength = StringLen(lookFor);
   for ( i=ObjectsTotal()-1; i>=0; i--)
   {
       objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
   GlobalVariableDel(ChartID()+":"+UniqueZoneID);  
   
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
if(ChartGetInteger(0,CHART_SCALE) != candlewidth) init();

   int counted_bars=IndicatorCounted();
   int i,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { UpH[0] = MathMin(limit+1,Bars-1); return(0); }
 datetime tDummy = GlobalVariableGet(ChartID()+":"+UniqueZoneID); if (tDummy==0) tDummy = Time[0];
   //
   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == _Period)
   {
     
      for(i=limit; i >= 0; i--)
      {
         rsi[i] = iSmooth(RSIModifier*(iRSI(NULL,0,Length,Price,i)-50.0),SmoothLength,SmoothPhase,i);
           
         trend[i] = trend[i+1];
            if (rsi[i]>LevelUp)                                           trend[i]= 1;
            if (rsi[i]<LevelDown)                                         trend[i]=-1;
            if (signalOnEveryBreak && rsi[i]<LevelUp && rsi[i]>LevelDown) trend[i]= 0;
          
      UpH[i]  =  EMPTY_VALUE;
      DnH[i]  = EMPTY_VALUE;   
      NuH_top[i]  =  EMPTY_VALUE; 
      NuH_bot[i]  =  EMPTY_VALUE;
      UpH_bot[i]  =  EMPTY_VALUE;
      DnH_bot[i]  =  EMPTY_VALUE;  
      NuH_topU[i]  =  EMPTY_VALUE; 
      NuH_botD[i]  =  EMPTY_VALUE;    
            
        if (trend[i]== 1)
         {UpH[i]  = High[i]; DnH[i]  = Low[i];UpH_bot[i] = MathMax(Open[i],Close[i]);DnH_bot[i] = MathMin(Open[i],Close[i]);
         }               
         if (trend[i]==-1)
         { UpH[i]  = Low[i]; DnH[i]  = High[i];  UpH_bot[i] = MathMin(Open[i],Close[i]); DnH_bot[i] = MathMax(Open[i],Close[i]);
         } 
        if (trend[i]== 0)
        { NuH_topU[i]  = High[i]; NuH_botD[i]  = Low[i]; NuH_top[i] = MathMax(Open[i],Close[i]); NuH_bot[i] = MathMin(Open[i],Close[i]);
        }                 
            
            
         manageLines(i);
         
         for (int index=i; index<Bars; index++) if (trend[index]!= trend[index+1]) break;
               if (ShowZones_OnTheMainChart)
                  {
                    string name = UniqueZoneID+":MainChart"+Time[index+1]; ObjectDelete(name); ObjectDelete(UniqueZoneID+":"+Time[1]);
                    datetime lastTime = Time[i-1]; if (i==0) { lastTime = tDummy; if (Time[index]==lastTime) lastTime = Time[0]+Period()*60;}
                    ObjectCreate(name,OBJ_RECTANGLE,0,Time[index],0,lastTime,WindowPriceMax()*3.0);
                    ObjectSet(name,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                          ObjectSet(name,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name,OBJPROP_COLOR,ZoneColorUp);
                  }
               if (ShowZones_InTheSeparatedWindow1)
                  {
                    string name2 = UniqueZoneID+":aboveZero1"+Time[index+1]; ObjectDelete(name2); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime2 = Time[i-1]; if (i==0) { lastTime2 = tDummy; if (Time[index]==lastTime2) lastTime2 = Time[0]+Period()*60;}
                    ObjectCreate(name2,OBJ_RECTANGLE,WhatSeparatedWindow1,Time[index],0,lastTime2,1000);
                    ObjectSet(name2,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name2,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name2,OBJPROP_COLOR,ZoneColorUp);

                    string name3 = UniqueZoneID+":belowZero1"+Time[index+1]; ObjectDelete(name3); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime3 = Time[i-1]; if (i==0) { lastTime3 = tDummy; if (Time[index]==lastTime3) lastTime3 = Time[0]+Period()*60;}
                    ObjectCreate(name3,OBJ_RECTANGLE,WhatSeparatedWindow1,Time[index],0,lastTime3,-1000);
                    ObjectSet(name3,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name3,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name3,OBJPROP_COLOR,ZoneColorUp);
                  }
               if (ShowZones_InTheSeparatedWindow2)
                  {
                    string name4 = UniqueZoneID+":aboveZero2"+Time[index+1]; ObjectDelete(name4); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime4 = Time[i-1]; if (i==0) { lastTime4 = tDummy; if (Time[index]==lastTime4) lastTime4 = Time[0]+Period()*60;}
                    ObjectCreate(name4,OBJ_RECTANGLE,WhatSeparatedWindow2,Time[index],0,lastTime4,1000);
                    ObjectSet(name4,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name4,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name4,OBJPROP_COLOR,ZoneColorUp);

                    string name5 = UniqueZoneID+":belowZero2"+Time[index+1]; ObjectDelete(name5); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime5 = Time[i-1]; if (i==0) { lastTime5 = tDummy; if (Time[index]==lastTime5) lastTime5 = Time[0]+Period()*60;}
                    ObjectCreate(name5,OBJ_RECTANGLE,WhatSeparatedWindow2,Time[index],0,lastTime5,-1000);
                    ObjectSet(name5,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name5,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name5,OBJPROP_COLOR,ZoneColorUp);
                  }
               if (ShowZones_InTheSeparatedWindow3)
                  {
                    string name6 = UniqueZoneID+":aboveZero3"+Time[index+1]; ObjectDelete(name6); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime6 = Time[i-1]; if (i==0) { lastTime6 = tDummy; if (Time[index]==lastTime6) lastTime6 = Time[0]+Period()*60;}
                    ObjectCreate(name6,OBJ_RECTANGLE,WhatSeparatedWindow3,Time[index],0,lastTime6,1000);
                    ObjectSet(name6,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name6,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name6,OBJPROP_COLOR,ZoneColorUp);

                    string name7 = UniqueZoneID+":belowZero3"+Time[index+1]; ObjectDelete(name7); ObjectDelete(UniqueZoneID+":"+Time[1]);             
                    datetime lastTime7 = Time[i-1]; if (i==0) { lastTime7 = tDummy; if (Time[index]==lastTime7) lastTime7 = Time[0]+Period()*60;}
                    ObjectCreate(name7,OBJ_RECTANGLE,WhatSeparatedWindow3,Time[index],0,lastTime7,-1000);
                    ObjectSet(name7,OBJPROP_BACK,true);
                    if (trend[i]==-1)
                        ObjectSet(name7,OBJPROP_COLOR,ZoneColorDown);
                    else  ObjectSet(name7,OBJPROP_COLOR,ZoneColorUp);
                  }
                  
                  
      }
      manageAlerts();
      return(0);
   }   
   
   //
   //
   //
   //
   //
   
   limit = fmax(limit,fmin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/_Period));
   for (i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         rsi[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Length,Price,RSIModifier,LevelUp,LevelDown,SmoothLength,SmoothPhase,8,y);
         trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Length,Price,RSIModifier,LevelUp,LevelDown,SmoothLength,SmoothPhase,9,y);
        
         manageLines(i);
     //    GlobalVariableSet(ChartID()+":"+UniqueZoneID,Time[0]+_Period*60-1);
         //
         //
         //
         UpH[i]  =  EMPTY_VALUE;
      DnH[i]  = EMPTY_VALUE;   
      NuH_top[i]  =  EMPTY_VALUE; 
      NuH_bot[i]  =  EMPTY_VALUE;
      UpH_bot[i]  =  EMPTY_VALUE;
      DnH_bot[i]  =  EMPTY_VALUE;  
      NuH_topU[i]  =  EMPTY_VALUE; 
      NuH_botD[i]  =  EMPTY_VALUE; 
         //
         //
       if (trend[i]== 1)
         {UpH[i]  = High[i]; DnH[i]  = Low[i];UpH_bot[i] = MathMax(Open[i],Close[i]);DnH_bot[i] = MathMin(Open[i],Close[i]);
         }               
         if (trend[i]==-1)
         { UpH[i]  = Low[i]; DnH[i]  = High[i];  UpH_bot[i] = MathMin(Open[i],Close[i]); DnH_bot[i] = MathMax(Open[i],Close[i]);
         } 
        if (trend[i]== 0)
        { NuH_topU[i]  = High[i]; NuH_botD[i]  = Low[i]; NuH_top[i] = MathMax(Open[i],Close[i]); NuH_bot[i] = MathMin(Open[i],Close[i]);
        }                 
       
  }
   //
   
   manageAlerts();
   return(0);   
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (alertsOnZoneEnter && trend[whichBar]   ==  1) doAlert(whichBar,DoubleToStr(LevelUp,2)  +" broken up");
         if (alertsOnZoneEnter && trend[whichBar]   == -1) doAlert(whichBar,DoubleToStr(LevelDown,2)+" broken down");
         if (alertsOnZoneExit  && trend[whichBar+1] == -1) doAlert(whichBar,DoubleToStr(LevelDown,2)+" broken up");
         if (alertsOnZoneExit  && trend[whichBar+1] ==  1) doAlert(whichBar,DoubleToStr(LevelUp,2)  +" broken 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 =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS),"rsi level ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"rsi"),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void manageLines(int i)
{
   if (!calculateValue && verticalLinesVisible)
   {
         deleteLine(Time[i]);
         if (trend[i]!=trend[i+1])
         {
            if (verticalLinesShowBreak)
            {
               if (trend[i] == 1) drawLine(i,verticalLinesUpColor);
               if (trend[i] ==-1) drawLine(i,verticalLinesDownColor);
            }               
            if (verticalLinesShowRetrace)
            {
               if (trend[i] == 0 && trend[i+1]==-1) drawLine(i,verticalLinesUpColor);
               if (trend[i] == 0 && trend[i+1]== 1) drawLine(i,verticalLinesDownColor);
            }
         }
   }
}               

//
//
//
//
//

void drawLine(int i,color theColor)
{
   string name = verticalLinesID+":"+Time[i];
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_VLINE,0,Time[i],0);
         ObjectSet(name,OBJPROP_COLOR,theColor);
         ObjectSet(name,OBJPROP_STYLE,verticalLinesStyle);
         ObjectSet(name,OBJPROP_WIDTH,verticalLinesWidth);
         ObjectSet(name,OBJPROP_BACK,true);
}

//
//
//
//
//

void deleteLine(datetime time)
{
   string lookFor = verticalLinesID+":"+time; ObjectDelete(lookFor);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   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 (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};

//
//
//
//
//

int stringToTimeFrame(string tfs)
{
   tfs = stringUpperCase(tfs);
   for (int i=ArraySize(iTfTable)-1; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[i],Period()));
                                                      return(Period());
}
string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//
//
//
//
//

string stringUpperCase(string str)
{
   string   s = str;

   for (int length=StringLen(str)-1; length>=0; length--)
   {
      int tchar = StringGetChar(s, length);
         if((tchar > 96 && tchar < 123) || (tchar > 223 && tchar < 256))
                     s = StringSetChar(s, length, tchar - 32);
         else if(tchar > -33 && tchar < 0)
                     s = StringSetChar(s, length, tchar + 224);
   }
   return(s);
}
//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//

double wrk[][10];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

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) { for(int 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]);
            if (wrk[r][avolty+s] > 0)
               double dVolty = wrk[r][volty+s]/wrk[r][avolty+s]; else dVolty = 0;   
	               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]);
}