//+------------------------------------------------------------------+ 
// #Chaos Oscillator v2 nrp       \¦/
// Knowledge of the ancients (ò ó)
//______________________o0o___(_)___o0o_____
//___¦Xard777¦_____¦_____¦_____¦_____¦_2009_¦
//http://www.forex-tsd.com/suggestions-trading-systems/21030-trading-system-xard777-59.html
// modified a bit by Boxter, Dec 2011
//+------------------------------------------------------------------+

#property  indicator_separate_window
//#property  indicator_minimum 0.0
//#property  indicator_maximum 1.0
#property  indicator_buffers 3
#property  indicator_color2  Blue
#property  indicator_color3  Red
#property indicator_style2 STYLE_SOLID
#property indicator_style3 STYLE_SOLID
#property indicator_width2 2
#property indicator_width3 2

extern int candles=14;
double ExtBuffer0[];
double ExtBuffer1[];
double ExtBuffer2[];

int init(){
   SetIndexStyle(0,DRAW_NONE);
   SetIndexStyle(1,DRAW_HISTOGRAM, STYLE_SOLID, 2); //color blue, buy
   SetIndexStyle(2,DRAW_HISTOGRAM, STYLE_SOLID, 2); //color red, sell
   IndicatorDigits(Digits+1);

   SetIndexBuffer(0,ExtBuffer0);
   SetIndexBuffer(1,ExtBuffer1);
   SetIndexBuffer(2,ExtBuffer2);

   IndicatorShortName("#Chaos Oscillator");
   SetIndexLabel(0,NULL);
   SetIndexLabel(1,NULL);
   SetIndexLabel(2,NULL);
   return(0);
}

int start(){
   double prev,current,old;
   double Value=0,Value1=0,Value2=0,Fish=0,Fish1=0,Fish2=0;
   double price;
   double MinL=0;
   double MaxH=0;  
   int counted_bars=IndicatorCounted(); //The function returns the amount of bars not changed after the indicator had been launched last.
   if (counted_bars>0) counted_bars--;
   int limit=Bars-counted_bars; //taking in consideration only bars changed after indi had been launched last

//   for(int i=Bars; i>=0; i--){
   for(int i=limit; i>=0; i--){
      MaxH = High[Highest(NULL,0,MODE_HIGH,candles,i)];
      MinL = Low[Lowest(NULL,0,MODE_LOW,candles,i)];
      price = (High[i]+Low[i])/2;
      if(MaxH-MinL == 0) Value = 0.33*2*(0-0.5) + 0.67*Value1; 
      else Value = 0.66*((price-MinL)/(MaxH-MinL)-0.5) + 0.67*Value1;         
      Value=MathMin(MathMax(Value,-0.999),0.999);     
      if(1-Value == 0) ExtBuffer0[i]=0.5+0.5*Fish1;
      else ExtBuffer0[i]=0.5*MathLog((1+Value)/(1-Value))+0.5*Fish1;   
      Value1=Value;
      Fish1=ExtBuffer0[i];
   }
   bool up=true;
//   for(i=Bars; i>=0; i--){
   for(i=limit; i>=0; i--){
      current=ExtBuffer0[i];
      prev=ExtBuffer0[i+1];    
      if (((current<0)&&(prev>0))||(current<0))   up= false;    
      if (((current>0)&&(prev<0))||(current>0))   up= true;  
      if(!up){
         ExtBuffer2[i]=-1.0;
         ExtBuffer1[i]=0.0;
      }
        
      else{
         ExtBuffer1[i]=1.0;
         ExtBuffer2[i]=0.0;
      }
   }
   return(0);
}