//+------------------------------------------------------------------+
//|                                             Volatility.Pivot.mq4 |
//+------------------------------------------------------------------+
#property copyright "thanks to S.B.T. (Japan)"
#property link      "http://sufx.core.t3-ism.net/" //<<< convert this from VT, thanks mate !!!
#property link      "www.forex-station.com"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1  clrSlateGray
#property indicator_width1  2

//
//
//
//
//

extern string TimeFrame       = "Current time frame";
extern double atr_range       = 14;
extern double ima_range       = 10;
extern double atr_factor      =  3;
extern int    Mode            =  0;
extern double DeltaPrice      = 30;
extern ENUM_APPLIED_PRICE priceForAlerts  = PRICE_CLOSE;
extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;
extern bool   alertsNotify    = false;
extern bool   Interpolate     = true;

//
//
//
//
//

double TrStop[];
double ATR[];
double trend[];

//
//
//
//
//

int    timeFrame;
string indicatorFileName;
bool   returnBars;
bool   calculateValue;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int init()
{
   IndicatorBuffers(3);
      SetIndexBuffer(0, TrStop); SetIndexStyle(0,DRAW_LINE); SetIndexLabel(0,"range base");
      SetIndexBuffer(1, ATR);
      SetIndexBuffer(2, trend);
   
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
         returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //

   IndicatorShortName(timeFrameToString(timeFrame)+" Risenberg volatility capture");
   return(0);
}
int deinit()
{
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int start()
{
   double DeltaStop,pipMultiplier=1;
   int    i,limit,counted_bars=IndicatorCounted();

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { TrStop[0] = limit+1; return(0); }
         if (Digits==3 || Digits==5) pipMultiplier = 10;

   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
      for(i=limit; i>=0; i--) ATR[i] = iATR(NULL,0,atr_range,i);
      for(i=limit; i>=0; i--)
      {
         if (Mode == 0)
               DeltaStop = iMAOnArray(ATR,0,ima_range,0,MODE_EMA,i) * atr_factor;
         else  DeltaStop = DeltaPrice*pipMultiplier*Point;

         while (true)
         {
            if (Close[i]  == TrStop[i+1]) { TrStop[i] = TrStop[i+1]; break; }
            if (Close[i+1] < TrStop[i+1] && Close[i]<TrStop[i+1]) { TrStop[i] = MathMin(TrStop[i+1], Close[i] + DeltaStop); break; }
            if (Close[i+1] > TrStop[i+1] && Close[i]>TrStop[i+1]) { TrStop[i] = MathMax(TrStop[i+1], Close[i] - DeltaStop); break; }         
            if (Close[i]   > TrStop[i+1]) 
                 TrStop[i] = Close[i] - DeltaStop; 
            else TrStop[i] = Close[i] + DeltaStop;
            break;
         }
      
         //
         //
         //
         //
         //
    
         double price = iMA(NULL,0,1,0,MODE_SMA,priceForAlerts,i);
            trend[i] = trend[i+1];
               if (price>TrStop[i]) trend[i] =  1;
               if (price<TrStop[i]) trend[i] = -1;
      }
      manageAlerts();
      return(0);
   }      

   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         TrStop[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",atr_range,ima_range,atr_factor,Mode,DeltaPrice,priceForAlerts,0,y);
         trend[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",atr_range,ima_range,atr_factor,Mode,DeltaPrice,priceForAlerts,2,y);
            
         //
         //
         //
         //
         //
      
         if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(int k = 1; k < n; k++)
               TrStop[i+k] = TrStop[i] + (TrStop[i+n]-TrStop[i])*k/n;
   }
   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 (trend[whichBar]   ==  1) doAlert(whichBar," broken up");
         if (trend[whichBar]   == -1) doAlert(whichBar," 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()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," volatility pivot line ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"volatility pivot"),message);
          if (alertsNotify)  SendNotification(message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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);
}