//+------------------------------------------------------------------+
//|                                                  STO_CCI_RSI.mq4 |                                   
//| not for sale, rent, auction, nor lease                           |
//+------------------------------------------------------------------+

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1 clrGreen
#property indicator_color2 clrRed
#property indicator_color3 clrDarkGreen //up arrow
#property indicator_width3 0
#property indicator_color4 clrCrimson       //down arrow
#property indicator_width4 0
#property indicator_level1 0
#property indicator_level2 100
#property indicator_level3 -100

#property indicator_levelstyle STYLE_DOT
#property indicator_levelcolor clrDimGray

//33 enPrices
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 string   TimeFrame        = "Current time frame";
extern string   ForSymbol        = "NULL";
extern int      RSIperiod        = 9;
extern int      StochasticPeriod = 14;
extern int      CCIperiod        = 20;

extern double   Hot              = 0.4;
extern int      Smoothing        = 4;
extern bool     Interpolate      = true;
extern int      UpArrowCode      = 233;
extern int      DownArrowCode    = 234;

extern bool     alertsOn         = false;
extern bool     alertsOnCurrent  = false;
extern bool     alertsMessage    = false;
extern bool     alertsSound      = false;
extern bool     alertsEmail      = false;

extern string   TimeFrameNote1="TimeFrame =0 for Current Timeframe, =1 for 1MIN, =5 for 5MIN, =15 for 15MIN, =30 for 30MIN, =60 for 1H, =240 for 4H, =1440 for D1, =10080 for W1, =43200 for MN1";



double Signal1[],Signal2[],upX[],downX[],trend[], prices[];

string indicatorFileName;
bool   returnBars, calculateValue;
int    timeFrame;
//+------------------------------------------------------------------
int OnInit()
{
   for (int i=0; i<indicator_buffers; i++) SetIndexStyle(i,DRAW_LINE);
	string FileName;
	IndicatorBuffers(5);
      SetIndexBuffer(0,Signal1);
      SetIndexBuffer(1,Signal2);
      SetIndexBuffer(2,upX);   SetIndexStyle(2,DRAW_ARROW); SetIndexArrow(2,UpArrowCode);
      SetIndexBuffer(3,downX); SetIndexStyle(3,DRAW_ARROW);	SetIndexArrow(3,DownArrowCode);
      SetIndexBuffer(4,trend);

      for (i=0; i < 4; i++) SetIndexDrawBegin(i,RSIperiod+StochasticPeriod+CCIperiod+Hot+Smoothing);
      
         indicatorFileName = WindowExpertName();
         returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
         calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
         ForSymbol         = (ForSymbol=="NULL") ? _Symbol : ForSymbol; 
      
   IndicatorShortName(timeFrameToString(timeFrame)+" STO ("+StochasticPeriod+") CCI (" +CCIperiod+") RSI (" +RSIperiod+"); Hot[" +DoubleToStr(Hot,2)+"]; Smooth["+Smoothing+"]"); 
	return(0);
}
//+------------------------------------------------------------------
int start()
{
   int i,n,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) { Signal1[0] = limit+1; return(0); }
	
      	double Sm = Smoothing;
         	if (Sm<2) Sm=2;
               double sk  = 2.0 / (Sm + 1.0);
               double sk2 = 2.0 / (Sm * 0.8 + 1.0);
   
   if (calculateValue || (ForSymbol == Symbol() && timeFrame == Period()))
   {
      for(i=limit; i>=0; i--)
      {
         double rsi   =  iRSI(ForSymbol,0,RSIperiod,PRICE_CLOSE,i);
         double maxrsi = rsi;
         double minrsi = rsi;

                  for (int k=1; k<=StochasticPeriod; k++)
                  {
                     double trsi   = iRSI(ForSymbol,0,RSIperiod,PRICE_CLOSE,i+k);
                            maxrsi = MathMax(maxrsi,trsi);
                            minrsi = MathMin(minrsi,trsi);
                  }
                  if (maxrsi==minrsi)
         		       double storsi = 0;
                  else  	  storsi = ((rsi-minrsi)/(maxrsi-minrsi)*200-100);
         
         double SCR = Hot*iCCI(ForSymbol,0,CCIperiod,PRICE_TYPICAL,i)+(1-Hot)*storsi;
      
   		Signal1[i] = sk *SCR         +(1-sk )*Signal1[i+1];
         Signal2[i] = sk2*Signal1[i+1]+(1-sk2)*Signal2[i+1];
         upX[i]     = EMPTY_VALUE;
         downX[i]   = EMPTY_VALUE;
         trend[i]   = trend[i+1];
		
         if (Signal1[i]>Signal2[i]) trend[i] =  1;
         if (Signal1[i]<Signal2[i]) trend[i] = -1;
         if (trend[i] != trend[i+1])
               if (trend[i]==1) 
                     upX[i]   = Signal2[i]-15;
               else  downX[i] = Signal2[i]+15;
      }
      manageAlerts();
      return(0);
   }
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(ForSymbol,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for (i=limit; i>=0; i--)
   {
      int y = iBarShift(ForSymbol,timeFrame,Time[i]);
         Signal1[i] = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",RSIperiod,StochasticPeriod,CCIperiod,Hot,Smoothing,0,y);
         Signal2[i] = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",RSIperiod,StochasticPeriod,CCIperiod,Hot,Smoothing,1,y);
         trend[i]   = iCustom(ForSymbol,timeFrame,indicatorFileName,"calculateValue","",RSIperiod,StochasticPeriod,CCIperiod,Hot,Smoothing,4,y);
         upX[i]     = EMPTY_VALUE;
         downX[i]   = EMPTY_VALUE;
            
            if (trend[i]!=trend[i+1])
                  if (trend[i]==1) 
                        upX[i]   = Signal2[i]-15;
                  else  downX[i] = Signal2[i]+15;
            if (!Interpolate || y==iBarShift(ForSymbol,timeFrame,Time[i-1])) continue;

            datetime time = iTime(ForSymbol,timeFrame,y);
               for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
               for(k = 1; k < n; k++)
               {
                  Signal1[i+k] = Signal1[i] + (Signal1[i+n] - Signal1[i])*k/n;
                  Signal2[i+k] = Signal2[i] + (Signal2[i+n] - Signal2[i])*k/n;
               }                  
   }    
   manageAlerts();
   return(0);
}
//+-------------------------------------------------------------------
void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(ForSymbol,0,iTime(NULL,timeFrame,whichBar));
      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 =  StringConcatenate(Symbol()," STO CCI Rsi - at ",TimeToStr(TimeLocal(),TIME_SECONDS)," trend changed to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"Sto CCI Rsi"),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);
}
//+-------------------------------------------------------------------
//------------------------------------------------------------------
#define _prHABF(_prtype) (_prtype>=pr_habclose && _prtype<=pr_habtbiased2)
#define _priceInstances     1
#define _priceInstancesSize 4
double workHa[][_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(workHa,0)!= Bars) ArrayResize(workHa,Bars); instanceNo*=_priceInstancesSize; int r = bars-i-1;
         
         double haOpen  = (r>0) ? (workHa[r-1][instanceNo+2] + workHa[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]))*MathAbs((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) { 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:
            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);
}
//-------------------------------------------------------------------
