//+-------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-station.com"
//+-------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  ForestGreen
#property indicator_color2  OrangeRed
#property indicator_color3  OrangeRed
#property indicator_color4  DarkGray
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_style4  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    LsmaPeriod         = 25;
extern bool   alertsOn           = false;
extern bool   alertsOnCurrent    = true;
extern bool   alertsOnSlope      = false;
extern bool   alertsMessage      = true;
extern bool   alertsNotification = false;
extern bool   alertsSound        = false;
extern bool   alertsEmail        = false;
extern bool   ShowLines          = false;
extern string linesID            = " BSF";
extern color  linesUpColor       = Lime;
extern color  linesDnColor       = Red;
extern int    linesStyle         = STYLE_SOLID;
extern int    linesWidth         = 3;


double beh[];
double behda[];
double behdb[];
double sig[];
double trend[];
double cross[];
string indicatorFileName;
bool   returnBars;
int    timeFrame;
string shortName;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(6);
   SetIndexBuffer(0,beh);
   SetIndexBuffer(1,behda);
   SetIndexBuffer(2,behdb);
   SetIndexBuffer(3,sig);
   SetIndexBuffer(4,trend);
   SetIndexBuffer(5,cross);
      shortName         = linesID+", ("+EmaPeriod+","+HighLowPeriod+","+LwmaPeriod+","+LsmaPeriod+","+PriceShift+")";
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame == "returnBars";     if (returnBars)     return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);
   IndicatorShortName(shortName);
   return(0);
}
int deinit()
{
   string find = linesID+":";
   for (int i=ObjectsTotal()-1; i>= 0; i--)
   {
      string name = ObjectName(i); if (StringFind(name,find)==0) ObjectDelete(name);
   }
   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 (timeFrame!=Period())
            {
               limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
               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,LsmaPeriod,alertsOn,alertsOnCurrent,alertsOnSlope,alertsMessage,alertsNotification,alertsSound,alertsEmail,ShowLines,linesID,linesUpColor,linesDnColor,linesStyle,linesWidth,0,y);
                     behda[i] = EMPTY_VALUE;
                     behdb[i] = EMPTY_VALUE;
                     sig[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Price,PriceShift,EmaPeriod,HighLowPeriod,LwmaPeriod,LsmaPeriod,alertsOn,alertsOnCurrent,alertsOnSlope,alertsMessage,alertsNotification,alertsSound,alertsEmail,ShowLines,linesID,linesUpColor,linesDnColor,linesStyle,linesWidth,3,y);
                     trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",Price,PriceShift,EmaPeriod,HighLowPeriod,LwmaPeriod,LsmaPeriod,alertsOn,alertsOnCurrent,alertsOnSlope,alertsMessage,alertsNotification,alertsSound,alertsEmail,ShowLines,linesID,linesUpColor,linesDnColor,linesStyle,linesWidth,4,y);
                        if (trend[i]==-1) PlotPoint(i,behda,behdb,beh);
               }
               return(0);                  
            }
            if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);

   //
   //
   //
   //
   //
           
   if (trend[limit]==-1) CleanPoint(limit,behda,behdb);
   int window = WindowFind(shortName);
   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]);
         }
         behda[i] = EMPTY_VALUE;
         behdb[i] = EMPTY_VALUE;
         beh[i]   = iLwma(work[r]*(max-min),LwmaPeriod,r);
         sig[i]   = iLinr(beh[i],LsmaPeriod,r);
         trend[i] = trend[i+1];
         cross[i] = cross[i+1];
         if (beh[i]>0) cross[i] =  1;
         if (beh[i]<0) cross[i] = -1;
         if (alertsOnSlope)
         {
            if (beh[i]>beh[i+1]) trend[i] =  1;
            if (beh[i]<beh[i+1]) trend[i] = -1;
         }
         else
         {
            if (beh[i]>sig[i]) trend[i] =  1;
            if (beh[i]<sig[i]) trend[i] = -1;
         }            
         if (trend[i]==-1) PlotPoint(i,behda,behdb,beh);
         
         //
         //
         //
         //
         //
     
         if (ShowLines && window > -1)
         {
           string name = linesID+":"+Time[i];
           ObjectDelete(name);
           if (cross[i]!= cross[i+1])
           {
                color theColor  = linesUpColor; if (cross[i]==-1) theColor = linesDnColor;
                   ObjectCreate(name,OBJ_VLINE,window,Time[i],0);
                      ObjectSet(name,OBJPROP_WIDTH,linesWidth);
                      ObjectSet(name,OBJPROP_STYLE,linesStyle);
                      ObjectSet(name,OBJPROP_COLOR,theColor);
           }
        }
      }
   }
   manageAlerts();
   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[][1];
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);
}

//
//
//
//
//

double workLinr[][1];
double iLinr(double price, double period, int r, int instanceNo=0)
{
   if (ArrayRange(workLinr,0)!= Bars) ArrayResize(workLinr,Bars);

   //
   //
   //
   //
   //
   
      period = MathMax(period,1);
      workLinr[r][instanceNo] = price;
         double lwmw = period; double lwma = lwmw*price;
         double sma  = price;
         for(int k=1; k<period && (r-k)>=0; k++)
         {
            double weight = period-k;
                   lwmw  += weight;
                   lwma  += weight*workLinr[r-k][instanceNo];  
                   sma   +=        workLinr[r-k][instanceNo];
         }             
   
   return(3.0*lwma/lwmw-2.0*sma/period);
}


//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

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;
      }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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 (alertsOnSlope)
            {
               if (trend[whichBar] ==  1) doAlert(prevTime1,prevAlert1," Behgozin slope changed up");
               if (trend[whichBar] == -1) doAlert(prevTime1,prevAlert1," Behgozin slope changed down");
            }
            else
            {
               if (trend[whichBar] ==  1) doAlert(prevTime1,prevAlert1," Behgozin crossed signal line up");
               if (trend[whichBar] == -1) doAlert(prevTime1,prevAlert1," Behgozin crossed signal line 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(),"Wilder\'s DMI "),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)
{
   StringToUpper(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("");
}