//+-------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-station.com"
//+-------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 7
#property indicator_color1  DimGray
#property indicator_color2  LimeGreen
#property indicator_color3  LimeGreen
#property indicator_color4  OrangeRed
#property indicator_color5  OrangeRed
#property indicator_color6  DarkGray
#property indicator_color7  DarkGray
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_width4  2
#property indicator_width5  2
#property indicator_style6  STYLE_DOT
#property indicator_style7  STYLE_DOT

//
//
//
//
//

extern string TimeFrame        = "Current time frame";
extern int  Price              = PRICE_CLOSE;
extern int  PriceShift         = 0;
extern int  EmaPeriod          = 32;
extern int  HighLowPeriod      = 100;
extern int  LwmaPeriod         = 6;
extern int  ObOsPeriod         = 25;
extern bool alertsOn           = false;
extern bool alertsOnCurrent    = true;
extern bool alertsMessage      = true;
extern bool alertsNotification = false;
extern bool alertsSound        = false;
extern bool alertsEmail        = false;

double beh[];
double behua[];
double behub[];
double behda[];
double behdb[];
double levu[];
double levd[];
double trend[];

int    timeFrame;
string indicatorFileName;
bool   returnBars;
bool   calculateValue;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,beh);
   SetIndexBuffer(1,behua);
   SetIndexBuffer(2,behub);
   SetIndexBuffer(3,behda);
   SetIndexBuffer(4,behdb);
   SetIndexBuffer(5,levu);
   SetIndexBuffer(6,levd);
   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)+" Behgozin Strength Finder ("+EmaPeriod+","+HighLowPeriod+","+LwmaPeriod+","+ObOsPeriod+","+PriceShift+")");
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double work[];
int start()
{
   int i,r,counted_bars=IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
            int limit=Bars-counted_bars;
            if (returnBars) { beh[0] = limit+1; return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      if (trend[limit]== 1) CleanPoint(limit,behua,behub);
      if (trend[limit]==-1) CleanPoint(limit,behda,behdb);
      double alpha = 2.0/(1.0+ObOsPeriod);           
      for(i=limit, r=Bars-i-1; i>=0; i--,r++)
      {
         if ((i+PriceShift)>=0)
         {
            double price = iMA(NULL,0,1,0,MODE_SMA,Price,i+PriceShift);
            double ema   = iEma(price,EmaPeriod,r);
               if (ema != 0)
                     work[r] = 100.0*(price-ema)/ema;
               else  work[r] = 0;    
            double max = work[r];
            double min = work[r];
            for (int k=1; k<HighLowPeriod && (r-k)>=0; k++)
            {
               max = MathMax(max,work[r-k]);
               min = MathMin(min,work[r-k]);
            }
            beh[i]   = iLwma(work[r]*(max-min),LwmaPeriod,r);
            levu[i]  = levu[i+1];
            levd[i]  = levd[i+1];
            behda[i] = EMPTY_VALUE;
            behdb[i] = EMPTY_VALUE;
            behua[i] = EMPTY_VALUE;
            behub[i] = EMPTY_VALUE;
               if (beh[i]>0) levu[i] = levu[i+1]+alpha*(beh[i]-levu[i+1]);
               if (beh[i]<0) levd[i] = levd[i+1]+alpha*(beh[i]-levd[i+1]);
               trend[i] = 0;
                  if (beh[i]>levu[i]) trend[i] =  1;
                  if (beh[i]<levd[i]) trend[i] = -1;
                  if (trend[i]== 1) PlotPoint(i,behua,behub,beh);
                  if (trend[i]==-1) PlotPoint(i,behda,behdb,beh);
         }
      }
      manageAlerts();
      return(0);         
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (trend[limit]== 1) CleanPoint(limit,behua,behub);
   if (trend[limit]==-1) CleanPoint(limit,behda,behdb);
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         beh[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Price,PriceShift,EmaPeriod,HighLowPeriod,LwmaPeriod,ObOsPeriod,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,0,y);
         levu[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Price,PriceShift,EmaPeriod,HighLowPeriod,LwmaPeriod,ObOsPeriod,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,5,y);
         levd[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Price,PriceShift,EmaPeriod,HighLowPeriod,LwmaPeriod,ObOsPeriod,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,6,y);
         behda[i] = EMPTY_VALUE;
         behdb[i] = EMPTY_VALUE;
         behua[i] = EMPTY_VALUE;
         behub[i] = EMPTY_VALUE;
         trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Price,PriceShift,EmaPeriod,HighLowPeriod,LwmaPeriod,ObOsPeriod,alertsOn,alertsOnCurrent,alertsMessage,alertsNotification,alertsSound,alertsEmail,7,y);
                  if (trend[i]== 1) PlotPoint(i,behua,behub,beh);
                  if (trend[i]==-1) PlotPoint(i,behda,behdb,beh);
   }               
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workEma[][1];
double iEma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workEma,0)!= Bars) ArrayResize(workEma,Bars);

   //
   //
   //
   //
   //
      
   double alpha = 2.0 / (1.0+period);
          workEma[r][instanceNo] = workEma[r-1][instanceNo]+alpha*(price-workEma[r-1][instanceNo]);
   return(workEma[r][instanceNo]);
}

//
//
//
//
//

double workLwma[][2];
double iLwma(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workLwma,0)!= Bars) ArrayResize(workLwma,Bars);
   
   //
   //
   //
   //
   //
   
   workLwma[r][instanceNo] = price;
      double sumw = period;
      double sum  = period*price;

      for(int k=1; k<period && (r-k)>=0; k++)
      {
         double weight = period-k;
                sumw  += weight;
                sum   += weight*workLwma[r-k][instanceNo];  
      }             
      return(sum/sumw);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      
      //
      //
      //
      //
      //
      
      static datetime prevTime1  = 0;
      static string   prevAlert1 = "";
         if (trend[whichBar] != trend[whichBar+1])
         {
            if (trend[whichBar] ==  1) doAlert(prevTime1,prevAlert1," Behgozin broke upper level up");
            if (trend[whichBar] == -1) doAlert(prevTime1,prevAlert1," Behgozin broke lower level 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 (alertsNotification) SendNotification(message);
          if (alertsEmail)        SendMail(StringConcatenate(Symbol(),"Behgozin strenngth finder "),message);
          if (alertsSound)        PlaySound("alert2.wav");
   }
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

//
//
//
//
//

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (first[i+1] == EMPTY_VALUE)
      {
         if (first[i+2] == EMPTY_VALUE) {
                first[i]   = from[i];
                first[i+1] = from[i+1];
                second[i]  = EMPTY_VALUE;
            }
         else {
                second[i]   =  from[i];
                second[i+1] =  from[i+1];
                first[i]    = EMPTY_VALUE;
            }
      }
   else
      {
         first[i]  = from[i];
         second[i] = EMPTY_VALUE;
      }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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);
}