
#property copyright "Copyleft © 2007, GamaRat Forex"
#property link      "http://www.GammaRat.com/Forex"
//Please note that this is built from the Metaquotes Stochastic Oscillator source code
// and that source code rights defer to them for anything in here which
// is directly attributable to their work.
//

#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_buffers 1
#property indicator_color1 Red

//---- input parameters
extern int KPeriod=5;
extern int DPeriod=3;
extern int Slowing=3;
//---- buffers
double MainBuffer[];
//----
int draw_begin1=0;
int draw_begin2=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
   string short_name;   
//---- indicator lines
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0, MainBuffer);
   short_name="Sto("+KPeriod+","+DPeriod+","+Slowing+")";
   IndicatorShortName(short_name);
   SetIndexLabel(0,short_name);
   draw_begin1=KPeriod+Slowing;
   draw_begin2=draw_begin1+DPeriod;
   SetIndexDrawBegin(0,draw_begin1);
   return(0);
  }
//+------------------------------------------------------------------+
//| Stochastic oscillator                                            |
//+------------------------------------------------------------------+
int start()
  {
   int    i,k;
   int    counted_bars=IndicatorCounted();
   static bool   waiting_for_upper = false, waiting_for_lower=false;
   double M,S;
//----
   if(Bars<=draw_begin2) return(0);
//---- initial zero
   if(counted_bars<1){
      for(i=1;i<=draw_begin1;i++) MainBuffer[Bars-i]=0;
   }

   if(counted_bars>0) counted_bars--;
   int limit=Bars-counted_bars;
//---- signal line is simple movimg average
   for(i=0; i<limit; i++){
      M = iStochastic(NULL,NULL,KPeriod,DPeriod,Slowing,MODE_SMA,0,MODE_MAIN,i);
      S = iStochastic(NULL,NULL,KPeriod,DPeriod,Slowing,MODE_SMA,0,MODE_SIGNAL,i);
      MainBuffer[i]=50;
      if(waiting_for_upper){
         if(M<=80){
            waiting_for_upper = false;
            continue;
         }
         if( S<= M){
            waiting_for_upper = false;
            MainBuffer[i] = 100;
            continue;
          }
      } 
      if(waiting_for_lower){
         if(M >=20){
            waiting_for_lower = false;
            continue;
         }
         if( S >= M){
            waiting_for_lower = false;
            MainBuffer[i] = 0;
            continue;
          }
      }   
      if((M > 80) && (S > M)){
         waiting_for_upper = true;
      } else if((M < 20) && (S < M)){
         waiting_for_lower = true;
      }
   }  

   return(0);
}
//+------------------------------------------------------------------+