//------------------------------------------------------------------
//
//    original idea and tradestation code by John Ehlers
//    this version by mladen
//
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 7
#property indicator_color1 DarkGray
#property indicator_color2 DarkGray
#property indicator_color3 Silver
#property indicator_color4 LimeGreen
#property indicator_color5 LimeGreen
#property indicator_color6 PaleVioletRed
#property indicator_color7 PaleVioletRed
#property indicator_width3 2
#property indicator_width4 3
#property indicator_width6 3

//
//
//
//
//

extern string TimeFrame              = "Current time frame";
extern int    MMPeriod               = 20;
extern double Delta                  = 0.5;
extern double Fraction               = 0.8;
extern double LevelUpAveragePeriod   = 10;
extern double LevelDownAveragePeriod = 10;
extern int    Price                  = PRICE_MEDIAN;
extern bool   AlertsOn               = false;
extern bool   AlertsOnCurrent        = true;
extern bool   AlertsMessage          = true;
extern bool   AlertsSound            = false;
extern bool   AlertsEmail            = false;
extern bool   Interpolate            = true;

double mode[];
double modeUl[];
double modeUa[];
double modeDl[];
double modeDa[];
double fractionUp[];
double fractionDn[];
double trend[];

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorDigits(5);
   IndicatorBuffers(8);
   SetIndexBuffer(0,fractionUp);
   SetIndexBuffer(1,fractionDn);
   SetIndexBuffer(2,mode);
   SetIndexBuffer(3,modeUl);
   SetIndexBuffer(4,modeUa); SetIndexStyle(4,DRAW_ARROW); SetIndexArrow(4,159);
   SetIndexBuffer(5,modeDl);
   SetIndexBuffer(6,modeDa); SetIndexStyle(6,DRAW_ARROW); SetIndexArrow(6,159);
   SetIndexBuffer(7,trend);
   
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //

      IndicatorShortName(timeFrameToString(timeFrame)+" Market mode "+MMPeriod+","+DoubleToStr(Delta,2)+","+DoubleToStr(Fraction,2)+")");
   return(0);
}
int deinit()
{
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double work[][4];
#define _price  0
#define _bp     1
#define _apeak  2
#define _avaley 3
#define Pi 3.141592653589793238462643383279

//
//
//
//
//

int start()
{
   int i,k,n,r,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) { fractionUp[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
      double beta    = MathCos(2.0*Pi/MMPeriod);
      double gamma   = 1.0 / MathCos(4.0*Pi*Delta/MMPeriod);
      double alpha   = gamma -MathSqrt(gamma*gamma-1.0);
      double alphaUp = 2.0 /(1.0+LevelUpAveragePeriod);
      double alphaDn = 2.0 /(1.0+LevelDownAveragePeriod);
      int    dPeriod = 2*MMPeriod;
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
   
      //
      //
      //
      //
      //
      
      for(i=limit, r=Bars-i-1; i>=0; i--,r++)
      {
         work[r][_price] = iMA(NULL,0,1,0,MODE_SMA,Price,i);
         work[r][_bp]    = 0.5*(1.0-alpha)*(work[r][_price]-work[r-2][_price])+beta*(1.0+alpha)*work[r-1][_bp]-alpha*work[r-2][_bp];
         
            //
            //
            //
            //
            //
            
            double mean = work[r][_bp]; for (k=1; k<(dPeriod) && (r-k)>=0; k++) mean += work[r-k][_bp];
                                                                                mean /= k;
            work[r][_apeak]  = work[r-1][_apeak];  if (mean>0) work[r][_apeak]  = work[r-1][_apeak] +alphaUp*(mean-work[r-1][_apeak]);
            work[r][_avaley] = work[r-1][_avaley]; if (mean<0) work[r][_avaley] = work[r-1][_avaley]+alphaDn*(mean-work[r-1][_avaley]);
  
            //
            //
            //
            //
            //
            
            modeUl[i]     = EMPTY_VALUE;
            modeUa[i]     = EMPTY_VALUE;
            modeDl[i]     = EMPTY_VALUE;
            modeDa[i]     = EMPTY_VALUE;
            mode[i]       = mean;
            fractionUp[i] = Fraction*work[r][_apeak];
            fractionDn[i] = Fraction*work[r][_avaley];
                 trend[i] = trend[i+1];
                 if (mode[i]>fractionUp[i])                          trend[i] =  1;
                 if (mode[i]<fractionDn[i])                          trend[i] = -1;
                 if (mode[i]<fractionUp[i] && mode[i]>fractionDn[i]) trend[i] =  0;
                 if (trend[i] == -1)
                 {
                     modeDl[i] = mode[i]; if (trend[i+1]!=-1) modeDa[i] = mode[i];
                 }
                 if (trend[i] == 1)
                 {
                     modeUl[i] = mode[i]; if (trend[i+1]!= 1) modeUa[i] = mode[i];
                 }
         }               
         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]);
         fractionUp[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",MMPeriod,Delta,Fraction,LevelUpAveragePeriod,LevelDownAveragePeriod,Price,AlertsOn,AlertsOnCurrent,AlertsMessage,AlertsSound,AlertsEmail,0,y);
         fractionDn[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",MMPeriod,Delta,Fraction,LevelUpAveragePeriod,LevelDownAveragePeriod,Price,AlertsOn,AlertsOnCurrent,AlertsMessage,AlertsSound,AlertsEmail,1,y);
         trend[i]      = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",MMPeriod,Delta,Fraction,LevelUpAveragePeriod,LevelDownAveragePeriod,Price,AlertsOn,AlertsOnCurrent,AlertsMessage,AlertsSound,AlertsEmail,7,y);
         mode[i]       = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",MMPeriod,Delta,Fraction,LevelUpAveragePeriod,LevelDownAveragePeriod,Price,AlertsOn,AlertsOnCurrent,AlertsMessage,AlertsSound,AlertsEmail,2,y);
         modeUl[i]     = EMPTY_VALUE;
         modeUa[i]     = EMPTY_VALUE;
         modeDl[i]     = EMPTY_VALUE;
         modeDa[i]     = EMPTY_VALUE;
                 if (trend[i] == -1) { modeDl[i] = mode[i]; if (trend[i+1]!=-1) modeDa[i] = mode[i]; }
                 if (trend[i] ==  1) { modeUl[i] = mode[i]; if (trend[i+1]!= 1) modeUa[i] = mode[i]; }

         //
         //
         //
         //
         //
      
         if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(k = 1; k < n; k++)
            {
               mode[i+k]       = mode[i]       + (mode[i+n]       - mode[i]      )*k/n;
               fractionUp[i+k] = fractionUp[i] + (fractionUp[i+n] - fractionUp[i])*k/n;
               fractionDn[i+k] = fractionDn[i] + (fractionDn[i+n] - fractionDn[i])*k/n;
                  if (modeUl[i+k]!=EMPTY_VALUE) modeUl[i+k]=mode[i+k];
                  if (modeDl[i+k]!=EMPTY_VALUE) modeDl[i+k]=mode[i+k];
                  if (modeUa[i+k]!=EMPTY_VALUE) modeUa[i+k]=mode[i+k];
                  if (modeDa[i+k]!=EMPTY_VALUE) modeDa[i+k]=mode[i+k];
            }                  
   }
   return(0);
         
}


//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (AlertsOn)
   {
      if (AlertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;

      if (trend[whichBar]!= trend[whichBar+1])
      {
         static datetime time1 = 0;
         static string   mess1 = "";
            if (trend[whichBar] ==  1) doAlert(time1,mess1," market mode changed to up");
            if (trend[whichBar] == -1) doAlert(time1,mess1," market mode changed to down");
      }
   }
}

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[0]) {
       previousAlert  = doWhat;
       previousTime   = Time[0];

       //
       //
       //
       //
       //

       message =  timeFrameToString(Period())+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+doWhat;
          if (AlertsMessage) Alert(message);
          if (AlertsEmail)   SendMail(timeFrameToString(Period())+" "+Symbol()+" Market mode",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);
}