//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_chart_window

//
//
//
//
//

extern string TimeFrame        = "current time frame";
extern int    MaPeriod        = 13;
//extern int   SlowPeriod =25; 
extern ENUM_MA_METHOD    MaMode =MODE_EMA;
//extern int    Price         = PRICE_TYPICAL;
extern string UniqueID         = "SSL zones";
extern color  ColorUp          = PaleGreen;
extern color  ColorDown        = LightSalmon;
extern bool   alertsOn         = false;
extern bool   alertsOnCurrent  = true;
extern bool   alertsMessage    = true;
extern bool   alertsSound      = false;
extern bool   alertsEmail      = false;
extern double Dummy            = -1;
extern string             button_note1          = "------------------------------";
extern int                btn_Subwindow = 0;
extern ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER; 
extern string             btn_text              = "SSL";
extern string             btn_Font              = "Arial";
extern int                btn_FontSize          = 10;                            
extern color              btn_text_ON_color     = clrLime;
extern color              btn_text_OFF_color    = clrRed;
extern string             btn_pressed           = "SSL OFF";            
extern string             btn_unpressed         = "SSL ON";
extern color              btn_background_color  = clrDimGray;
extern color              btn_border_color      = clrBlack;
extern int                button_x              = 850;                                 
extern int                button_y              = 0;                                   
extern int                btn_Width             = 65;                                 
extern int                btn_Height            = 20;                                
extern string             soundBT               = "tick.wav";  
extern string             button_note2          = "------------------------------";

bool                      show_data             = true;
string IndicatorName, IndicatorObjPrefix ,buttonId ;
double colors[];

int    timeFrame;
string indicatorFileName;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
string GenerateIndicatorName(const string target)
{
   string name = target;
   int try = 2;
   while (WindowFind(name) != -1)
   {
      name = target + " #" + IntegerToString(try++);
   }
   return name;
}
//+------------------------------------------------------------------------------------------------------------------+



//+------------------------------------------------------------------------------------------------------------------+
void createButton(string buttonID,string buttonText,int width,int height,string font,int fontSize,color bgColor,color borderColor,color txtColor)
{
      ObjectDelete    (ChartID(),buttonID);
      ObjectCreate (ChartID(),buttonID,OBJ_BUTTON,btn_Subwindow,0,0);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_COLOR,txtColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_BGCOLOR,bgColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_BORDER_COLOR,borderColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XSIZE,width);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_YSIZE,height);
      ObjectSetString (ChartID(),buttonID,OBJPROP_FONT,font);
      ObjectSetString (ChartID(),buttonID,OBJPROP_TEXT,buttonText);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_FONTSIZE,fontSize);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_SELECTABLE,0);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_CORNER,btn_corner);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_HIDDEN,1);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XDISTANCE,9999);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_YDISTANCE,9999);
}
//
//

int init()
{
   IndicatorBuffers(1);
   SetIndexBuffer(0,colors); SetIndexStyle(0,DRAW_NONE);
      timeFrame         = stringToTimeFrame(TimeFrame);
      indicatorFileName = WindowExpertName();
     IndicatorName = GenerateIndicatorName(btn_text);
   IndicatorObjPrefix = "__" + IndicatorName + "__";
   IndicatorShortName(WindowExpertName());
   IndicatorDigits(Digits);
      double val;
   if (GlobalVariableGet(IndicatorName + "_visibility", val))
   show_data = val != 0;

   ChartSetInteger(ChartID(), CHART_EVENT_MOUSE_MOVE, 1);
   buttonId = IndicatorObjPrefix+btn_text;
   createButton(buttonId, btn_text, btn_Width, btn_Height, btn_Font, btn_FontSize, btn_background_color, btn_border_color, btn_text_ON_color);
   ObjectSetInteger(ChartID(), buttonId, OBJPROP_YDISTANCE, button_y);
   ObjectSetInteger(ChartID(), buttonId, OBJPROP_XDISTANCE, button_x);     
      
   return(0);
}
int deinit()
{

ObjectsDeleteAll(0,"SSL");
   ObjectsDeleteAll(ChartID(), IndicatorObjPrefix);
   
   
   string lookFor       = UniqueID+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
bool recalc = true;
 void handleButtonClicks()
{
   if (ObjectGetInteger(ChartID(), buttonId, OBJPROP_STATE))
   {
      ObjectSetInteger(ChartID(), buttonId, OBJPROP_STATE, false);
      show_data = !show_data;
      GlobalVariableSet(IndicatorName + "_visibility", show_data ? 1.0 : 0.0);
      recalc = true;
      start();
   }
}
//+------------------------------------------------------------------------------------------------------------------+
void OnChartEvent(const int id, 
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
   handleButtonClicks();
   if (id==CHARTEVENT_OBJECT_CLICK && ObjectGet(sparam,OBJPROP_TYPE)==OBJ_BUTTON)
   {
   if (soundBT!="") PlaySound(soundBT);     
   }
}
//
//
//
int start()
{

  handleButtonClicks();
   recalc = false;
   //put start () here
   start2();
    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 (show_data)
         {
           ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_ON_color);
           
  
           
           
          
           start2();
         }
      else
         {
           ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_OFF_color);
        string lookFor       = UniqueID+":";
   int    lookForLength = StringLen(lookFor);
   for ( i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
   
   
         }
   return(0);
}
//

int start2()
{
   int i, limit = Bars;
         
         //
         //
         //
         //
         //

         datetime tDummy = Dummy;
         if (timeFrame!=Period()) 
         { 
            iCustom(NULL,timeFrame,indicatorFileName,"",MaPeriod,MaMode,UniqueID,ColorUp,ColorDown,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,Time[0],button_note1,btn_Subwindow,btn_corner,btn_text,btn_Font,btn_FontSize,btn_text_ON_color,btn_text_OFF_color,btn_pressed,btn_unpressed,btn_background_color,btn_border_color,button_x,button_y,btn_Width,btn_Height,soundBT,button_note2,0,0); 
            return(0); 
         }
         else if (Dummy<=Time[0]) tDummy = Time[0];
         static bool secondTime=false;
         if (secondTime)
         {
            int count=0;
            for (;limit<Bars; limit++) if (colors[limit]!=colors[limit+1]) { count++; if (count>1) break; }
         }
         else secondTime=true;

   //
   //
   //
   //
   //

      double MaxValue = High[0]*10.0;   
      for(i = limit; i>=0 ; i--)
      {
         if (i>Bars-2) continue;

         //
         //
         //
         //
         //
         
         double cci = iMA(NULL,0,1,0,0,PRICE_CLOSE,i)-iMA(NULL,0,MaPeriod,0,MaMode,PRICE_HIGH,i+1);
         double cci1 = iMA(NULL,0,1,0,0,PRICE_CLOSE,i)-iMA(NULL,0,MaPeriod,0,MaMode,PRICE_LOW,i+1);
         colors[i]  = colors[i+1];
            
            //
            //
            //
            //
            //

               if (cci>0) colors[i] =  1;
               if (cci1<0) colors[i] = -1;
               for (int index=i; index<Bars; index++) if (colors[index]!=colors[index+1]) break;
               string name = UniqueID+":"+Time[index+1]; ObjectDelete(name); ObjectDelete(UniqueID+":"+Time[1]);
               
               //
               //
               //
               //
               //
               
               datetime lastTime = Time[i-1]; if (i==0) { lastTime = tDummy; if (Time[index]==lastTime) lastTime = Time[0]+Period()*60;}
               ObjectCreate(name,OBJ_RECTANGLE,0,Time[index],0,lastTime,MaxValue);
                  ObjectSet(name,OBJPROP_BACK,true);
                  switch ((int)colors[i])
                  {
                     case -1 : ObjectSet(name,OBJPROP_COLOR,ColorDown); break;
                     default : ObjectSet(name,OBJPROP_COLOR,ColorUp);   break;
                  }
   }
   manageAlerts();
   return(0);
}


//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; 
      if (colors[whichBar] != colors[whichBar+1])
      {
         if (colors[whichBar] ==  1) doAlert(whichBar,"up");
         if (colors[whichBar] == -1) 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)+" SSL trend changed to "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," SSL zones "),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);
}