//+------------------------------------------------------------------+
//|                                          Parabolic SAR of MA.mq4 |
//+------------------------------------------------------------------+

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1  LimeGreen
#property indicator_color2  Orange
#property indicator_color3  Lime
#property indicator_color4  Red
#property indicator_width3  4
#property indicator_width4  4
//

extern string TimeFrame       = "current time frame";
extern int    MaPeriod        = 14;
extern int    MaMethod        = MODE_LWMA;
extern int    MaPrice         = PRICE_CLOSE;
extern double AccLimit        = 0.5;
extern double AccStep         = 0.2;
extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = true;
extern bool   alertsEmail     = false;
extern bool   DrawAsDots      = false;

double sarUp[];
double sarDn[];
double saraUp[];
double saraDn[];

string indicatorFileName;
bool   returnBars;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   int type = DRAW_LINE; if (DrawAsDots) type = DRAW_ARROW;
      SetIndexBuffer(0,sarUp);  SetIndexStyle(0,type);       SetIndexArrow(0,159);
      SetIndexBuffer(1,sarDn);  SetIndexStyle(1,type);       SetIndexArrow(1,159);
      SetIndexBuffer(2,saraUp); SetIndexStyle(2,DRAW_ARROW); SetIndexArrow(2,159);
      SetIndexBuffer(3,saraDn); SetIndexStyle(3,DRAW_ARROW); SetIndexArrow(3,159);
         indicatorFileName = WindowExpertName();
         timeFrame         = stringToTimeFrame(TimeFrame);
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
Comment("-------------------------------------------Sell---------------------------------------------------------------");
   return(0);
}
int deinit() { return(0); }

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int 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) { sarUp[0] = MathMin(limit+1,Bars-1); return(0); }
           if (timeFrame!=_Period)
           {
               limit = (int)MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
               for (int i=limit; i>=0; i--)
               {
                  int y = iBarShift(NULL,timeFrame,Time[i]);
                     sarUp[i]  = iCustom(NULL,timeFrame,indicatorFileName,"",MaPeriod,MaMethod,MaPrice,AccLimit,AccStep,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,0,y);
                     sarDn[i]  = iCustom(NULL,timeFrame,indicatorFileName,"",MaPeriod,MaMethod,MaPrice,AccLimit,AccStep,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,1,y);
                     saraUp[i] = EMPTY_VALUE;
                     saraDn[i] = EMPTY_VALUE;
                     if (y!=iBarShift(NULL,timeFrame,Time[i+1]))
                     {
                        saraUp[i] = iCustom(NULL,timeFrame,indicatorFileName,"",MaPeriod,MaMethod,MaPrice,AccLimit,AccStep,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,2,y);
                        saraDn[i] = iCustom(NULL,timeFrame,indicatorFileName,"",MaPeriod,MaMethod,MaPrice,AccLimit,AccStep,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,3,y);
                     }
               }
               return(0);
            }               

   //
   //
   //
   //
   //
    
      for(i = limit; i >= 0; i--)
      {
         double sarClose;
         double sarOpen;
         double sarPosition;
         double sarChange;
         double price = iMA(NULL,0,MaPeriod,0,MaMethod,MaPrice,i);
            iParabolic(price,price,AccStep,AccLimit,sarClose,sarOpen,sarPosition,sarChange,i);
            sarUp[i]  = EMPTY_VALUE;
            sarDn[i]  = EMPTY_VALUE;
            saraUp[i] = EMPTY_VALUE;
            saraDn[i] = EMPTY_VALUE;
            if (sarPosition==1)
                  sarUp[i] = sarClose;
            else  sarDn[i] = sarClose;
            if (sarChange!=0)
               if (sarChange==1)
                     saraUp[i] = sarClose;
               else  saraDn[i] = sarClose;
      }
      manageAlerts();
      return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workSar[][7];
#define _high     0
#define _low      1
#define _ohigh    2
#define _olow     3
#define _open     4
#define _position 5
#define _af       6

void iParabolic(double high, double low, double step, double limit, double& pClose, double& pOpen, double& pPosition, double& pChange, int i)
{
   if (ArrayRange(workSar,0)!=Bars) ArrayResize(workSar,Bars); i = Bars-i-1;
   
   //
   //
   //
   //
   //
   
      pChange = 0;
         workSar[i][_ohigh] = high;
         workSar[i][_olow]  = low;
            if (i<1)
               {
                  workSar[i][_high]     = high;
                  workSar[i][_low]      = low;
                  workSar[i][_open]     = high;
                  workSar[i][_position] = -1;
                  return;
               }
         workSar[i][_open]     = workSar[i-1][_open];
         workSar[i][_af]       = workSar[i-1][_af];
         workSar[i][_position] = workSar[i-1][_position];
         workSar[i][_high]     = MathMax(workSar[i-1][_high],high);
         workSar[i][_low]      = MathMin(workSar[i-1][_low] ,low );
      
   //
   //
   //
   //
   //
            
   if (workSar[i][_position] == 1)
      if (low<=workSar[i][_open])
         {
            workSar[i][_position] = -1;
               pChange = -1;
               pClose  = workSar[i][_high];
                         workSar[i][_high] = high;
                         workSar[i][_low]  = low;
                         workSar[i][_af]   = step;
                         workSar[i][_open] = pClose + workSar[i][_af]*(workSar[i][_low]-pClose);
                            if (workSar[i][_open]<workSar[i  ][_ohigh]) workSar[i][_open] = workSar[i  ][_ohigh];
                            if (workSar[i][_open]<workSar[i-1][_ohigh]) workSar[i][_open] = workSar[i-1][_ohigh];
         }
      else
         {
               pClose = workSar[i][_open];
                    if (workSar[i][_high]>workSar[i-1][_high] && workSar[i][_af]<limit) workSar[i][_af] = MathMin(workSar[i][_af]+step,limit);
                        workSar[i][_open] = pClose + workSar[i][_af]*(workSar[i][_high]-pClose);
                            if (workSar[i][_open]>workSar[i  ][_olow]) workSar[i][_open] = workSar[i  ][_olow];
                            if (workSar[i][_open]>workSar[i-1][_olow]) workSar[i][_open] = workSar[i-1][_olow];
         }
   else
      if (high>=workSar[i][_open])
         {
            workSar[i][_position] = 1;
               pChange = 1;
               pClose  = workSar[i][_low];
                         workSar[i][_low]  = low;
                         workSar[i][_high] = high;
                         workSar[i][_af]   = step;
                         workSar[i][_open] = pClose + workSar[i][_af]*(workSar[i][_high]-pClose);
                            if (workSar[i][_open]>workSar[i  ][_olow]) workSar[i][_open] = workSar[i  ][_olow];
                            if (workSar[i][_open]>workSar[i-1][_olow]) workSar[i][_open] = workSar[i-1][_olow];
         }
      else
         {
               pClose = workSar[i][_open];
               if (workSar[i][_low]<workSar[i-1][_low] && workSar[i][_af]<limit) workSar[i][_af] = MathMin(workSar[i][_af]+step,limit);
                   workSar[i][_open] = pClose + workSar[i][_af]*(workSar[i][_low]-pClose);
                            if (workSar[i][_open]<workSar[i  ][_ohigh]) workSar[i][_open] = workSar[i  ][_ohigh];
                            if (workSar[i][_open]<workSar[i-1][_ohigh]) workSar[i][_open] = workSar[i-1][_ohigh];
         }

   //
   //
   //
   //
   //
   
   pOpen     = workSar[i][_open];
   pPosition = workSar[i][_position];
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      if (saraUp[whichBar] != EMPTY_VALUE || saraDn[whichBar] != EMPTY_VALUE)
      {
         if (saraUp[whichBar] !=  EMPTY_VALUE) doAlert(whichBar,"up");
         if (saraDn[whichBar] !=  EMPTY_VALUE) doAlert(whichBar,"down");
      }
   }
}

//
//
//
//
//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  timeFrameToString(_Period)+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" parabolic SAR of MA trend cahnged to "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"parabolic SAR of MA"),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==""+(string)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("");
}