//+------------------------------------------------------------------
//| original by Metatrader4 Code by jjk2.                            
//| modified by mladen
//+------------------------------------------------------------------
#property copyright "Based on MBA Thesis from Simon Fraser University written by C.E. ALDEA."
#property link      ""
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1  LimeGreen
#property indicator_color2  Red
#property indicator_width1  2
#property indicator_width2  2
#property indicator_maximum 1
#property indicator_minimum 0


extern string TimeFrame       = "Current time frame";
extern int    Kperiod         = 9;
extern int    Dperiod         = 6;
extern int    slowing         = 2;
extern int    method_stoch    = MODE_SMA;
extern int    price_field     = 1;
extern int    mode            = 0;
extern int    period_rsi      = 9;
extern int    period_momentum = 9;

extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = false;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = false;
extern bool   alertsEmail     = false;

double kwan[];
double kwanDa[];
double kwanDb[];
double temp[];
double slope[];

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(5);
   SetIndexBuffer(0,kwanDa);SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1,kwanDb);SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexBuffer(2,kwan);
   SetIndexBuffer(3,temp);
   SetIndexBuffer(4,slope);

      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //
               
   IndicatorShortName(timeFrameToString(timeFrame)+" ZigZag BETA Current value calculated by indicator:");
   return(0);
}
int deinit()
{
   return(0);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int i,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
           int limit=MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { kwan[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
      for (i=limit; i>= 0; i--)
      {
         double Stoch  = iStochastic(NULL,0,Kperiod,Dperiod,slowing,method_stoch,price_field,mode,i);
         double RSI    = iRSI(NULL,0,period_rsi,PRICE_CLOSE,i);
         double moment = iMomentum(NULL,0,period_momentum,PRICE_CLOSE,i);
         if (moment!=0)
               temp[i] = Stoch*RSI/moment;
         else  temp[i] = 0;       
      }
      for (i=limit; i>= 0; i--)
      {
         kwanDa[i] = EMPTY_VALUE;
         kwanDb[i] = EMPTY_VALUE;
         kwan[i]   = iMAOnArray(temp,0,2,0,MODE_SMA,i);
         slope[i]  = slope[i+1];
            if (kwan[i] > kwan[i+1]) slope[i] =  1;
            if (kwan[i] < kwan[i+1]) slope[i] = -1;
            if (slope[i]==-1) kwanDb[i] = 1;
            if (slope[i]== 1) kwanDa[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]);
         kwanDa[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Kperiod,Dperiod,slowing,method_stoch,price_field,mode,period_rsi,period_momentum,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,0,y);
         kwanDb[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Kperiod,Dperiod,slowing,method_stoch,price_field,mode,period_rsi,period_momentum,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,1,y);
         
   }
   return(0);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar=0;
      if (slope[whichBar] != slope[whichBar+1])
      {
         if (slope[whichBar] ==  1) doAlert("up"  );
         if (slope[whichBar] == -1) doAlert("down");
      }
   }
}

//
//
//
//
//

void doAlert(string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[0]) {
       previousAlert  = doWhat;
       previousTime   = Time[0];

       //
       //
       //
       //
       //

       message =  timeFrameToString(Period())+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" Kwan changed to "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(Symbol()+" Kwan",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);
}