//+-------------------------------------------------------\!/--------------------------------------------------------+
//+ [Knowledge of the ancients]                          (ò ó)                           [XU-v65m-XARD-UNIVERSE-V1.6.mq4] +
//+-------------------------------------------------o0o---(_)---o0o--------------------------------------------------+
#property link        "https://forex-station.com/post1294848283.html#p1294848283"
#property description "THIS IS A FREE INDICATOR WITH NO TIME RESTRICTIONS"
#property description "                                                      "
#property description "Welcome to the XARD UNIVERSE"
#property description "                                                      "
#property description "Let the light shine and illuminate your trading world"
#property description "and with it secure your financial prosperity"
#property  indicator_chart_window
#property indicator_buffers 50
#define Version "XU-v65m-XARD UNIVERSE V1.6"
string ID = "Xard>";

string MyName="XU v65m-XARD UNIVERSE_semabgd",indicatorFileName;
bool show_data = true;
bool bgd_recalc = false;
string IndicatorObjPrefix, buttonId, buttonId2;
bool   bgd_method_sema = false; // false=V1.2 S3MA method, true=V1.4 SEMA method
bool   bgd_method_recalc = false;

//+------------------------------------------------------------------------------------------------------------------+
 input string Indicator                      = Version;
   input bool showVersion                    = true;
   input bool showBGDzones                   = true;
   input bool showTEXTx                      = true;
   input bool showTextBOX                    = true;
   input bool showOpenBias                   = true;
   input bool showSymbolHeader               = true;
          int getChartScale                  = WRONG_VALUE;  int Type;
//+------------------------------------------------------------------------------------------------------------------+
extern string STR00                          = "<<<==== [00] Lightweight Settings ====>>>";
    input int maxBars                        = 1500;               // Max bars to calculate (lightweight limit)
extern string STR01                          = "<<<==== [01] Ribbon Settings ====>>>";
   input bool showRib1                       = true;              // Show Ribbon?
  input color Rib1ClrUP                      = C'44,104,51';      // Ribbon Up Color
  input color Rib1ClrDN                      = C'114,44,51';      // Ribbon Down Color
       double Rib1a[],Rib1b[];
       
   input bool showRib2                       = true;              // Show Ribbon?
  input color Rib2ClrUP                      = C'33,55,42';       // Ribbon Up Color
  input color Rib2ClrDN                      = C'65,33,42';       // Ribbon Down Color
       double Rib2a[],Rib2b[];
//+------------------------------------------------------------------------------------------------------------------+
extern string STR02                          = "<<<==== [02] SEMA Settings ====>>>";
  extern bool showSEMA1=true,showSEMA2=true,showSEMA3=true,showSEMA4=true,showSEMA5=true;
   extern int DotPer1=9,DotPer2=36,DotPer3=144,DotPer4=144,DotPer5=576,deltazz;
       string Dev_Step_1="0,5",Dev_Step_2="0,5",Dev_Step_3="0,5",Dev_Step_4="0,5",Dev_Step_5="0,5";    
   extern int S1size=4,S2size=8,S3size=14,S4size=8,S5size=16,S1kod=108,S2kod=108,S3kod=108,S4kod=221,S5kod=110,S6kod=222;
 extern color cU1=clrSpringGreen,cD1=clrOrangeRed,cU2=clrDodgerBlue,cD2=clrOrchid,cU3=clrLimeGreen,cD3=clrCrimson,
              cU4=clrSnow,cD4=clrSnow,cU5=clrDarkGray,cD5=clrDarkGray;
          int APer,BPer,CPer,DPer,EPer,Dev1,Stp1,Dev2,Stp2,Dev3,Stp3,Dev4,Stp4,Dev5,Stp5;
       double ABufUp[],ABufDn[],BBufUp[],BBufDn[],CBufUp[],CBufDn[],DBufUp[],DBufDn[],EBufUp[],EBufDn[];
       double myPoint,mPoint;
       double SetPoint(){if(Digits<4) mPoint=0.01; else mPoint=0.0001; return(mPoint);} 
//+------------------------------------------------------------------------------------------------------------------+
extern string STR03                          = "<<<==== [03] Candle Settings ====>>>";
   input bool showCandles                    = true;              // Show Candles?
    input int cWick                          = 2;                 // Candle Wick Size
  input color CandleUp                       = C'96,170,204',     // Candle Up Color
              CandleWt                       = C'95,105,115',     // Candle Wait Color//clrDarkGray
              CandleDn                       = clrViolet;         // Candle Down Color
       double candle0[],candle1[],candle2[],candle3[],candle4[],candle5[],candle6[],candle7[];
//+------------------------------------------------------------------------------------------------------------------+
extern string STR04                          = "<<<==== [04] S1MA Trend Settings ====>>>";
   input bool showS1MA                       = false;             // Show S1MA?
    input int S1MAper                        =  1;                // S1MA high low period
        input ENUM_MA_METHOD  S1MAmode       = MODE_EMA;          // S1MA moving average method
    input int S1MAtf                         =  0;                // S1MA tf
    input int S1MAshft                       =  0;                // S1MA shift
    input int S1MAwidth                      =  3;                // S1MA line width
  input color S1MAwtclr                      = C'36,62,62';       // S1MA Wait Color
  input color S1MAupclr                      = C'65,145,71';      // S1MA Up Color
  input color S1MAdnclr                      = C'195,67,70';      // S1MA Down Color
         bool returnBars,calculateS1TREND;  double S1MAbgd[],S1MA[],S1MAdna[],S1MAdnb[],S1trend[];
//+------------------------------------------------------------------------------------------------------------------+
extern string STR05                          = "<<<==== [05] S2MA Trend Settings ====>>>";
   input bool showS2MA                       = true;              // Show S2MA?
    input int S2MAper                        = 13;                // S2MA high low period
        input ENUM_MA_METHOD  S2MAmode       = MODE_EMA;          // S2MA moving average method
    input int S2MAtf                         =  0;                // S2MA tf
    input int S2MAshft                       =  0;                // S2MA shift
    input int S2MAwidth                      =  2;                // S2MA line width
  input color S2MAwtclr                      = C'36,62,62';       // S2MA Wait Color
  input color S2MAupclr                      = C'65,145,71';      // S2MA Up Color
  input color S2MAdnclr                      = C'195,67,70';      // S2MA Down Color
         bool calculateS2TREND;  double S2MAbgd[],S2MA[],S2MAdna[],S2MAdnb[],S2trend[];
//+------------------------------------------------------------------------------------------------------------------+
extern string STR06                          = "<<<==== [06] S3MA Trend Settings ====>>>";
   input bool showS3MA                       = true;              // Show S3MA?
    input int S3MAper                        = 55;                // S3MA high low period
        input ENUM_MA_METHOD  S3MAmode       = MODE_EMA;          // S3MA moving average method
    input int S3MAtf                         =  0;                // S3MA tf
    input int S3MAshft                       =  0;                // S3MA shift
    input int S3MAwidth                      =  3;                // S3MA line width
  input color S3MAwtclr                      = C'36,62,62';       // S3MA Wait Color
  input color S3MAupclr                      = clrLime;           // S3MA Up Color
  input color S3MAdnclr                      = clrRed;            // S3MA Down Color
         bool calculateS3TREND;  double S3MAbgd[],S3MA[],S3MAdna[],S3MAdnb[],S3trend[];
//+------------------------------------------------------------------------------------------------------------------+
extern string STR07                          = "<<<==== [07] BGDzones Settings ====>>>";
  input color ColorUp                        = C'23,52,80',
              ColorDown                      = C'80,43,62',
              ColorWait                      = C'30,47,62';
       double Dummy=-1,colors1[],colors2[];
//+------------------------------------------------------------------------------------------------------------------+
extern string STR08                          = "<<<==== [08] BOXtxt Settings ====>>>";
       string BOXtxt,BOXtxt2;  
        color BOXclr,BOXclr2;
    input int FontSize3                      = 15,
              move_text_sideways             = 0,
              move_text_updown               = 0;
    input int moveTxtLR                      = 0,
              moveTxtUD                      = 0;
//+------------------------------------------------------------------------------------------------------------------+
extern string STR09                          = "<<<==== [09] Symbol Header Settings ====>>>";
    input int LR                             = 125,
              UD                             = 10,
              HDRsize                        = 40,
              HDRsize2                       = 14;  
        color Sbg                            = clrBlack,SymClr;
        color colCarlsberg;
       double OpenToday;
//+------------------------------------------------------------------------------------------------------------------+
extern string STR10                          = "<<<==== [10] Daily Open level Settings ====>>>";
    input int GmtShift,
              MA_Period                      = 2,
              MA_Method                      = MODE_SMMA,
              PriceMode                      = PRICE_WEIGHTED; 
   color UpCol=clrLime,DnCol=clrOrangeRed; double BUFdn[],BUFup[],OPening,Bufo;
//+------------------------------------------------------------------------------------------------------------------+
extern string STR11                          = "<<<==== [11] Alert Settings ====>>>";
   input bool inpAlertsOn                    = false;             // Turn alerts on?
   input bool inpAlertsOnCurrent             = false;             // Alerts on current (still opened) bar?
   input bool inpAlertsMessage               = true;              // Alerts should show pop-up message?
   input bool inpAlertsSound                 = false;             // Alerts should play alert sound?
   input bool inpAlertsPushNotif             = false;             // Alerts should send push notification?
   input bool inpAlertsEmail                 = false;             // Alerts should send email?
//+------------------------------------------------------------------------------------------------------------------+
       double TRX[],data1;  string TimeFrame="Current time frame";  int timeFrame;
       string FontType                       = "Arial Black";
//+------------------------------------------------------------------------------------------------------------------+
extern string STR12                          = "<<<==== [12] Background Button Settings ====>>>";
extern string             button_note1_         = "------------------------------";
extern int                btn_Subwindow         = 0;                               // What window to put the button on.  If <0, the button will use the same sub-window as the indicator.
extern ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER;               // button corner on chart for anchoring
extern string             btn_text              = "BGD";                            // a button name
extern string             btn_Font              = "Arial";                         // button font name
extern int                btn_FontSize          = 9;                               // button font size               
extern color              btn_text_ON_color     = clrLime;                         // ON color when the button is turned on
extern color              btn_text_OFF_color    = clrRed;                          // OFF color when the button is turned off
extern color              btn_background_color  = clrDimGray;                      // background color of the button
extern color              btn_border_color      = clrBlack;                        // border color the button
extern int                button_x              = 12;                              // x coordinate of the button     
extern int                button_y              = 25;                              // y coordinate of the button     
extern int                btn_Width             = 80;                              // button width
extern int                btn_Height            = 20;                              // button height
extern string             UniqueButtonID        = "XU_BGD_1";                      // Unique ID for each button        
extern string             button_note2          = "------------------------------";
//+------------------------------------------------------------------------------------------------------------------+
extern string STR12b                         = "<<<==== [12b] BGD Method Button Settings ====>>>";
extern string             btn2_text_S3MA     = "By MA";                            // label when S3MA method active
extern string             btn2_text_SEMA     = "By SEMA";                            // label when SEMA method active
extern color              btn2_text_S3MA_color = clrDeepSkyBlue;                  // colour for S3MA mode
extern color              btn2_text_SEMA_color = clrOrange;                       // colour for SEMA mode
extern color              btn2_background_color = clrDimGray;                     // background colour
extern color              btn2_border_color  = clrBlack;                          // border colour
extern int                button2_x          = 95;                                // x coord (right of BGD button)
extern int                button2_y          = 25;                                // y coordinate
extern int                btn2_Width         = 80;                                // button width
extern int                btn2_Height        = 20;                                // button height
extern string             UniqueButtonID2    = "XU_BGD_METHOD_1";                 // unique ID for method button
    input int FontSize                       = 12;
//+------------------------------------------------------------------------------------------------------------------+
extern string STR13 = "<<<==== [13] VWAP SSL Flip Settings (V1.6) ====>>>";
enum ENUM_VWAP_PERIOD { VWAP_DAILY, VWAP_WEEKLY, VWAP_MONTHLY };
input ENUM_VWAP_PERIOD VS_Period = VWAP_DAILY;   // VWAP SSL: anchor period (Daily/Weekly/Monthly)
input color VS_UpColor   = clrLimeGreen;         // VWAP SSL: uptrend line color
input color VS_DownColor = clrRed;               // VWAP SSL: downtrend line color
input int   VS_LineWidth = 3;                    // VWAP SSL: line thickness
input bool  VS_ShowVWAP  = true;                 // VWAP SSL: show VWAP line
input color VS_VWAPColor = clrGold;              // VWAP SSL: VWAP line color
input int   VS_VWAPWidth = 3;                    // VWAP SSL: VWAP line width
input ENUM_LINE_STYLE VS_VWAPStyle = STYLE_SOLID;// VWAP SSL: VWAP line style
input int   VS_MaxBars    = 1500;                // VWAP SSL: max bars to display / calculate
input int   VS_WarmupBars = 1500;                // VWAP SSL: extra warm-up bars (not plotted)
input bool  VS_AlertsOn        = true;           // VWAP SSL: alert when line color changes
input bool  VS_AlertsOnCurrent = true;           // VWAP SSL: alert on forming bar (false = closed bar)
input bool  VS_AlertsMessage   = true;           // VWAP SSL: popup alert
input bool  VS_AlertsSound     = true;           // VWAP SSL: play sound
input bool  VS_AlertsPush      = false;          // VWAP SSL: push notification
input bool  VS_AlertsEmail     = false;          // VWAP SSL: email alert
input string VS_AlertSoundFile = "alert.wav";    // VWAP SSL: sound file
extern string STR13b = "<<<==== [13b] VWAP SSL Button Settings (3rd button) ====>>>";
extern string VS_btn_text = "VWAP SSL";          // button text
extern int    VS_btn_FontSize = 9;               // button font size
extern color  VS_btn_text_ON_color  = clrLime;   // text color when ON
extern color  VS_btn_text_OFF_color = clrRed;    // text color when OFF
extern color  VS_btn_background_color = clrDimGray;
extern color  VS_btn_border_color = clrBlack;
extern int    VS_button_x = 12;                  // x coordinate of the button
extern int    VS_button_y = 50;                  // y coordinate of the button
extern int    VS_btn_Width = 80;
extern int    VS_btn_Height = 20;
extern string VS_UniqueButtonID = "XU_VWAPSSL_1";// unique ID for VWAP SSL button
double VS_Up[],VS_Down[],VS_Main[],VS_Trend[],VS_CumPVH[],VS_CumPVL[],VS_CumVol[],VS_CumPVT[];
int vs_Idx0=0; bool vs_show=true, vs_forceRecalc=false; string vs_btnId, vs_prefix, vs_gvKey;
datetime vs_lastAlertBarTime=0; int vs_lastAlertTrend=-1;
//+----OnInit Function-----------------------------------------------------------------------------------------------+
   int OnInit(){int Buffers=50,Buf=-1; IndicatorBuffers(Buffers);
   if(TimeFrame==0 || TimeFrame<Period()) TimeFrame=Period();  timeFrame=stringToTimeFrame(TimeFrame);
   IndicatorDigits(Digits); IndicatorShortName(MyName);
//+------------------------------------------------------------------------------------------------------------------+
   if(showRib1)           Type=DRAW_HISTOGRAM; else Type=DRAW_NONE;
   Buf+=1; SetIndexBuffer(Buf,Rib1a);        
   Buf+=1; SetIndexBuffer(Buf,Rib1b);       fSetBuffers();//01
   if(showRib2)           Type=DRAW_HISTOGRAM; else Type=DRAW_NONE;
   Buf+=1; SetIndexBuffer(Buf,Rib2a);        
   Buf+=1; SetIndexBuffer(Buf,Rib2b);       fSetBuffers();//03
//+------------------------------------------------------------------------------------------------------------------+
   if(DotPer1>0) APer=MathCeil(DotPer1*Period()); else APer=0;
   if(DotPer2>0) BPer=MathCeil(DotPer2*Period()); else BPer=0;
   if(DotPer3>0) CPer=MathCeil(DotPer3*Period()); else CPer=0;
   if(DotPer4>0) DPer=MathCeil(DotPer4*Period()); else DPer=0;
   if(DotPer5>0) EPer=MathCeil(DotPer5*Period()); else EPer=0;
//+---SML RED/GRN DOT (9)--------------------------------------------------------------------------------------------+
   if(showSEMA1)    Type=DRAW_ARROW; else Type=DRAW_NONE;
   if(DotPer1>0){
   Buf+=1; SetIndexBuffer(Buf,ABufUp); SetIndexStyle(Buf,Type,0,S1size,cU1);  SetIndexArrow(Buf,S1kod);
   Buf+=1; SetIndexBuffer(Buf,ABufDn); SetIndexStyle(Buf,Type,0,S1size,cD1);  SetIndexArrow(Buf,S1kod);}//05
//+---GOLD SQUARE (576)----------------------------------------------------------------------------------------------+
   if(showSEMA5)    Type=DRAW_ARROW; else Type=DRAW_NONE;
   if(DotPer5>0){
   Buf+=1; SetIndexBuffer(Buf,EBufUp); SetIndexStyle(Buf,Type,0,S5size,cU5);  SetIndexArrow(Buf,S5kod);
   Buf+=1; SetIndexBuffer(Buf,EBufDn); SetIndexStyle(Buf,Type,0,S5size,cD5);  SetIndexArrow(Buf,S5kod);}//07
//+---MED DODGERBLUE/ORCHID DOT (36)---------------------------------------------------------------------------------+
   if(showSEMA2)    Type=DRAW_ARROW; else Type=DRAW_NONE;
   if(DotPer2>0){
   Buf+=1; SetIndexBuffer(Buf,BBufUp); SetIndexStyle(Buf,Type,0,S2size,cU2);  SetIndexArrow(Buf,S2kod);
   Buf+=1; SetIndexBuffer(Buf,BBufDn); SetIndexStyle(Buf,Type,0,S2size,cD2);  SetIndexArrow(Buf,S2kod);}//09
//+---DODGERBLUE/PINK PERIMETER DOT (144)----------------------------------------------------------------------------+
   if(showSEMA3)    Type=DRAW_ARROW; else Type=DRAW_NONE;
   if(DotPer3>0){
   Buf+=1; SetIndexBuffer(Buf,CBufUp); SetIndexStyle(Buf,Type,0,S3size,cU3);  SetIndexArrow(Buf,S3kod);
   Buf+=1; SetIndexBuffer(Buf,CBufDn); SetIndexStyle(Buf,Type,0,S3size,cD3);  SetIndexArrow(Buf,S3kod);}//11
//+---ARROW DOT (144)------------------------------------------------------------------------------------------------+
   if(showSEMA4)    Type=DRAW_ARROW; else Type=DRAW_NONE;
   if(DotPer4>0){
   Buf+=1; SetIndexBuffer(Buf,DBufUp); SetIndexStyle(Buf,Type,0,S4size,cU4);  SetIndexArrow(Buf,S4kod);
   Buf+=1; SetIndexBuffer(Buf,DBufDn); SetIndexStyle(Buf,Type,0,S4size,cD4);  SetIndexArrow(Buf,S6kod);}//13
//+------------------------------------------------------------------------------------------------------------------+
   int CDev=0,CSt=0,Mass[],C=0;
   if(IntFromStr(Dev_Step_1,C,Mass)==1){Stp1=Mass[1]; Dev1=Mass[0];}
   if(IntFromStr(Dev_Step_2,C,Mass)==1){Stp2=Mass[1]; Dev2=Mass[0];}
   if(IntFromStr(Dev_Step_3,C,Mass)==1){Stp3=Mass[1]; Dev3=Mass[0];}
   if(IntFromStr(Dev_Step_4,C,Mass)==1){Stp4=Mass[1]; Dev4=Mass[0];}
   if(IntFromStr(Dev_Step_5,C,Mass)==1){Stp5=Mass[1]; Dev5=Mass[0];}   
//+------------------------------------------------------------------------------------------------------------------+
   if(showCandles)        Type=DRAW_HISTOGRAM; else Type=DRAW_NONE;
   Buf+=1; SetIndexBuffer(Buf,candle0);    SetIndexStyle(Buf,Type,EMPTY,cWick,CandleUp);
   Buf+=1; SetIndexBuffer(Buf,candle1);    SetIndexStyle(Buf,DRAW_NONE);
   Buf+=1; SetIndexBuffer(Buf,candle2);    SetIndexStyle(Buf,Type,EMPTY,cWick,CandleWt);
   Buf+=1; SetIndexBuffer(Buf,candle3);    SetIndexStyle(Buf,Type,EMPTY,cWick,CandleDn);
   Buf+=1; SetIndexBuffer(Buf,candle4);//18
   Buf+=1; SetIndexBuffer(Buf,candle5);    SetIndexStyle(Buf,DRAW_NONE);
   Buf+=1; SetIndexBuffer(Buf,candle6);//20
   Buf+=1; SetIndexBuffer(Buf,candle7);    fSetBuffers();//21
//+------------------------------------------------------------------------------------------------------------------+
   if(showS2MA)           Type=DRAW_LINE; else Type=DRAW_NONE; int S2W=S2MAwidth,S2B=S2W+4; color S2Wc=S2MAwtclr;
   Buf+=1; SetIndexBuffer(Buf,S2MAbgd);   SetIndexStyle(Buf,Type,0,S2B,S2Wc);       SetIndexDrawBegin(Buf,S2MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S2MA);      SetIndexStyle(Buf,Type,0,S2W,S2MAupclr);  SetIndexDrawBegin(Buf,S2MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S2MAdna);   SetIndexStyle(Buf,Type,0,S2W,S2MAdnclr);  SetIndexDrawBegin(Buf,S2MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S2MAdnb);   SetIndexStyle(Buf,Type,0,S2W,S2MAdnclr);  SetIndexDrawBegin(Buf,S2MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S2trend);   SetIndexStyle(Buf,DRAW_NONE);//26
//+------------------------------------------------------------------------------------------------------------------+
   if(showS3MA)           Type=DRAW_LINE; else Type=DRAW_NONE; int S3W=S3MAwidth,S3B=S3W+4; color S3Wc=S3MAwtclr;
   Buf+=1; SetIndexBuffer(Buf,S3MAbgd);   SetIndexStyle(Buf,Type,0,S3B,S3Wc);       SetIndexDrawBegin(Buf,S3MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S3MA);      SetIndexStyle(Buf,Type,0,S3W,S3MAupclr);  SetIndexDrawBegin(Buf,S3MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S3MAdna);   SetIndexStyle(Buf,Type,0,S3W,S3MAdnclr);  SetIndexDrawBegin(Buf,S3MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S3MAdnb);   SetIndexStyle(Buf,Type,0,S3W,S3MAdnclr);  SetIndexDrawBegin(Buf,S3MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S3trend);   SetIndexStyle(Buf,DRAW_NONE);//31
//+------------------------------------------------------------------------------------------------------------------+
   if(showS1MA)           Type=DRAW_LINE; else Type=DRAW_NONE; int S1W=S1MAwidth,S1B=S1W+4; color S1Wc=S1MAwtclr;
   Buf+=1; SetIndexBuffer(Buf,S1MAbgd);   SetIndexStyle(Buf,Type,0,S1B,S1Wc);       SetIndexDrawBegin(Buf,S1MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S1MA);      SetIndexStyle(Buf,Type,0,S1W,S1MAupclr);  SetIndexDrawBegin(Buf,S1MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S1MAdna);   SetIndexStyle(Buf,Type,0,S1W,S1MAdnclr);  SetIndexDrawBegin(Buf,S1MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S1MAdnb);   SetIndexStyle(Buf,Type,0,S1W,S1MAdnclr);  SetIndexDrawBegin(Buf,S1MAper+1);
   Buf+=1; SetIndexBuffer(Buf,S1trend);   SetIndexStyle(Buf,DRAW_NONE);//36
//+------------------------------------------------------------------------------------------------------------------+
   if(Period()<=PERIOD_H4){Type=DRAW_ARROW;} else Type=DRAW_NONE;
   Buf+=1; SetIndexBuffer(Buf,BUFdn); SetIndexStyle(Buf,Type,0,0,DnCol); SetIndexArrow(Buf,168);
   Buf+=1; SetIndexBuffer(Buf,BUFup); SetIndexStyle(Buf,Type,0,0,UpCol); SetIndexArrow(Buf,168);//38
//+------------------------------------------------------------------------------------------------------------------+
   Buf+=1; SetIndexBuffer(Buf,colors1);    SetIndexStyle(Buf,DRAW_NONE);
Buf+=1; SetIndexBuffer(Buf,colors2); SetIndexStyle(Buf,DRAW_NONE);
   Buf+=1; SetIndexBuffer(Buf,TRX);        SetIndexStyle(Buf,DRAW_NONE);//40
   VsInit(Buf);//41-48 VWAP SSL Flip buffers + 3rd button
//+------------------------------------------------------------------------------------------------------------------+
   IndicatorObjPrefix = "__" + btn_text + "__";
   buttonId = "_" + UniqueButtonID + IndicatorObjPrefix + "_BT_";
   if (ObjectFind(buttonId)<0)
      createButton(buttonId, btn_text, btn_Width, btn_Height, btn_Font, btn_FontSize, btn_background_color, btn_border_color, btn_text_ON_color);
   ObjectSetInteger(0, buttonId, OBJPROP_YDISTANCE, button_y);
   ObjectSetInteger(0, buttonId, OBJPROP_XDISTANCE, button_x);
   show_data = ObjectGetInteger(0, buttonId, OBJPROP_STATE);
   if (show_data) ObjectSetInteger(0, buttonId, OBJPROP_COLOR, btn_text_ON_color);
   else           ObjectSetInteger(0, buttonId, OBJPROP_COLOR, btn_text_OFF_color);
// ── Button 2 (BGD METHOD S3MA/SEMA) ─────────────────────────────────────
buttonId2 = "_" + UniqueButtonID2 + IndicatorObjPrefix + "_BT2_";
if (ObjectFind(buttonId2)<0)
   createButton(buttonId2, btn2_text_S3MA, btn2_Width, btn2_Height, btn_Font, btn_FontSize, btn2_background_color, btn2_border_color, btn2_text_S3MA_color);
ObjectSetInteger(0, buttonId2, OBJPROP_YDISTANCE, button2_y);
ObjectSetInteger(0, buttonId2, OBJPROP_XDISTANCE, button2_x);
bgd_method_sema = ObjectGetInteger(0, buttonId2, OBJPROP_STATE);
if (bgd_method_sema){ ObjectSetString(0,buttonId2,OBJPROP_TEXT,btn2_text_SEMA); ObjectSetInteger(0,buttonId2,OBJPROP_COLOR,btn2_text_SEMA_color); }
else { ObjectSetString(0,buttonId2,OBJPROP_TEXT,btn2_text_S3MA); ObjectSetInteger(0,buttonId2,OBJPROP_COLOR,btn2_text_S3MA_color); }
   EventSetMillisecondTimer(300);  indicatorFileName = WindowExpertName();  return(INIT_SUCCEEDED);}//End OnInit
//+------------------------------------------------------------------------------------------------------------------+
   void OnDeinit(const int reason){if(reason ==REASON_REMOVE){ ObjectsDeleteAll(0,MyName+":"); ObjectDelete(0,vs_btnId); GlobalVariableDel(vs_gvKey); }
   EventKillTimer( ); CleanUpOnAisle16();
   if(reason != REASON_CHARTCHANGE){ ObjectDelete(buttonId); ObjectDelete(buttonId2); }}
//+------------------------------------------------------------------------------------------------------------------+
void createButton(string buttonID,string buttonText,int width2,int height,string font,int fontSize,color bgColor,color borderColor,color txtColor)
{
   ObjectDelete    (0,buttonID);
   ObjectCreate    (0,buttonID,OBJ_BUTTON,btn_Subwindow,0,0);
   ObjectSetInteger(0,buttonID,OBJPROP_COLOR,txtColor);
   ObjectSetInteger(0,buttonID,OBJPROP_BGCOLOR,bgColor);
   ObjectSetInteger(0,buttonID,OBJPROP_BORDER_COLOR,borderColor);
   ObjectSetInteger(0,buttonID,OBJPROP_BORDER_TYPE,BORDER_RAISED);
   ObjectSetInteger(0,buttonID,OBJPROP_XSIZE,width2);
   ObjectSetInteger(0,buttonID,OBJPROP_YSIZE,height);
   ObjectSetString (0,buttonID,OBJPROP_FONT,font);
   ObjectSetString (0,buttonID,OBJPROP_TEXT,buttonText);
   ObjectSetInteger(0,buttonID,OBJPROP_FONTSIZE,fontSize);
   ObjectSetInteger(0,buttonID,OBJPROP_SELECTABLE,0);
   ObjectSetInteger(0,buttonID,OBJPROP_CORNER,btn_corner);
   ObjectSetInteger(0,buttonID,OBJPROP_HIDDEN,1);
   ObjectSetInteger(0,buttonID,OBJPROP_XDISTANCE,9999);
   ObjectSetInteger(0,buttonID,OBJPROP_YDISTANCE,9999);
   // Upon creation, set the initial state to "true" which is "on", so background is shown by default
   ObjectSetInteger(0, buttonId, OBJPROP_STATE, true);
}
//+------------------------------------------------------------------------------------------------------------------+
   int OnCalculate(const int rates_total,
                   const int prev_calculated,
                   const datetime &time[],
                   const double &open[],
                   const double &high[],
                   const double &low[],
                   const double &close[],
                   const long &tick_volume[],
                   const long &volume[],
                   const int &spread[]){
   fSetBuffers();
   int i,limit=(int)fmin(fmin(rates_total-prev_calculated+1,rates_total-1),maxBars-1);
//+---Semafor Function-----------------------------------------------------------------------------------------------+
   if(DotPer1>0) CountZZ(ABufUp,ABufDn,DotPer1,Dev1,Stp1);
   if(DotPer2>0) CountZZ(BBufUp,BBufDn,DotPer2,Dev2,Stp2);
   if(DotPer3>0) CountZZ(CBufUp,CBufDn,DotPer3,Dev3,Stp3);
   if(DotPer4>0) CountZZ(DBufUp,DBufDn,DotPer4,Dev4,Stp4);
   if(DotPer5>0) CountZZ(EBufUp,EBufDn,DotPer5,Dev5,Stp5);
//+---S1MA Function--------------------------------------------------------------------------------------------------+
   if(returnBars){S1MA[0]=limit+1; return(0);} if(calculateS1TREND || timeFrame == Period()){
   if(!calculateS1TREND && S1trend[limit]==-1) CleanPoint(limit,S1MAdna,S1MAdnb); 
   for(i=limit;i>=0;i--){S1MAdna[i]=EMPTY_VALUE; S1MAdnb[i]=EMPTY_VALUE; S1trend[i]=S1trend[i+1]; 
                  if(Close[i]>iMA(Symbol(),S1MAtf,S1MAper,S1MAshft,S1MAmode,PRICE_HIGH,i+1)) S1trend[i]= 1;
                  if(Close[i]<iMA(Symbol(),S1MAtf,S1MAper,S1MAshft,S1MAmode,PRICE_LOW, i+1)) S1trend[i]=-1;
   if(S1trend[i]==-1) S1MA[i]=iMA(Symbol(),S1MAtf,S1MAper,S1MAshft,S1MAmode,PRICE_WEIGHTED,i+0);
                else  S1MA[i]=iMA(Symbol(),S1MAtf,S1MAper,S1MAshft,S1MAmode,PRICE_WEIGHTED,i+0); S1MAbgd[i]=S1MA[i];
   if(!calculateS1TREND && S1trend[i]==-1) PlotPoint(i,S1MAdna,S1MAdnb,S1MA);}}//EOF S1MA
//+---S2MA Function--------------------------------------------------------------------------------------------------+
   if(returnBars){S2MA[0]=limit+1; return(0);} if(calculateS2TREND || timeFrame == Period()){
   if(!calculateS2TREND && S2trend[limit]==-1) CleanPoint(limit,S2MAdna,S2MAdnb); 
   for(i=limit;i>=0;i--){S2MAdna[i]=EMPTY_VALUE; S2MAdnb[i]=EMPTY_VALUE; S2trend[i]=S2trend[i+1]; 
                  if(Close[i]>iMA(Symbol(),S2MAtf,S2MAper,S2MAshft,S2MAmode,PRICE_HIGH,i+1)) S2trend[i]= 1;
                  if(Close[i]<iMA(Symbol(),S2MAtf,S2MAper,S2MAshft,S2MAmode,PRICE_LOW, i+1)) S2trend[i]=-1;
   if(S2trend[i]==-1) S2MA[i]=iMA(Symbol(),S2MAtf,S2MAper,S2MAshft,S2MAmode,PRICE_WEIGHTED,i+0);
                else  S2MA[i]=iMA(Symbol(),S2MAtf,S2MAper,S2MAshft,S2MAmode,PRICE_WEIGHTED,i+0); S2MAbgd[i]=S2MA[i];
   if(!calculateS2TREND && S2trend[i]==-1) PlotPoint(i,S2MAdna,S2MAdnb,S2MA);}}//EOF S2MA
//+---S3MA Function--------------------------------------------------------------------------------------------------+
   if(returnBars){S3MA[0]=limit+1; return(0);} if(calculateS3TREND || timeFrame == Period()){
   if(!calculateS3TREND && S3trend[limit]==-1) CleanPoint(limit,S3MAdna,S3MAdnb); 
   for(i=limit;i>=0;i--){S3MAdna[i]=EMPTY_VALUE; S3MAdnb[i]=EMPTY_VALUE; S3trend[i]=S3trend[i+1]; 
                  if(Close[i]>iMA(Symbol(),S3MAtf,S3MAper,S3MAshft,S3MAmode,PRICE_HIGH,i+1)) S3trend[i]= 1;
                  if(Close[i]<iMA(Symbol(),S3MAtf,S3MAper,S3MAshft,S3MAmode,PRICE_LOW, i+1)) S3trend[i]=-1;
   if(S3trend[i]==-1) S3MA[i]=iMA(Symbol(),S3MAtf,S3MAper,S3MAshft,S3MAmode,PRICE_WEIGHTED,i+0);
                else  S3MA[i]=iMA(Symbol(),S3MAtf,S3MAper,S3MAshft,S3MAmode,PRICE_WEIGHTED,i+0); S3MAbgd[i]=S3MA[i];
   if(!calculateS3TREND && S3trend[i]==-1) PlotPoint(i,S3MAdna,S3MAdnb,S3MA);}}//EOF S3MA
//+---Rib Function---------------------------------------------------------------------------------------------------+
   for(i=0;i<limit;i++){Rib1a[i]=S1MA[i]; Rib1b[i]=S2MA[i];}
   for(i=0;i<limit;i++){Rib2a[i]=S2MA[i]; Rib2b[i]=S3MA[i];}
//+---BGD Zones Function---------------------------------------------------------------------------------------------+
   if(showBGDzones){
      datetime tDummy=Dummy; if(Dummy<=Time[0]) tDummy=Time[0];
      double MaxValue=High[0]*10.0;

      // Full redraw on: first run, button OFF->ON, or method switch
      bool fullRedraw = (bgd_recalc || bgd_method_recalc || prev_calculated<=1);
      int  bgdLimit   = fullRedraw ? (int)fmin(rates_total-1, maxBars-1) : limit;

      // Clear old BGD rectangles when full redraw needed
      if(fullRedraw){
         string zn; int zt=ObjectsTotal();
         for(int z=zt-1; z>=0; z--){
            zn=ObjectName(z);
            if(StringSubstr(zn,0,StringLen(ID+"BGD:"))== ID+"BGD:") ObjectDelete(zn);
         }
         bgd_recalc        = false;
         bgd_method_recalc = false;
      }

      if(show_data){
         // Hoist shared loop variables to avoid re-declaration in both branches
         int      index;
         string   name;
         datetime lastTime;

         if(!bgd_method_sema){
            //--- METHOD 1: V1.2 S3MA crossing ---
            for(i=bgdLimit; i>=0; i--){
               if(i>Bars-2) continue;
               colors1[i]=colors1[i+1];
               if(S3trend[i]== 1) colors1[i]= 1;
               if(S3trend[i]==-1) colors1[i]=-1;
               for(index=i; index<Bars-1; index++) if(colors1[index]!=colors1[index+1]) break;
               name=ID+"BGD:"+Time[index+1];
               ObjectDelete(name);
               ObjectDelete(ID+"BGD:"+Time[1]);
               lastTime=Time[i]; if(i==0) lastTime=tDummy;
               ObjectCreate(name,OBJ_RECTANGLE,0,Time[index+1],0,lastTime,MaxValue);
               ObjectSet(name,OBJPROP_BACK,true);
               switch((int)colors1[i]){
                  case -1: ObjectSet(name,OBJPROP_COLOR,ColorDown); break;
                  case  1: ObjectSet(name,OBJPROP_COLOR,ColorUp);   break;
                  default: ObjectSet(name,OBJPROP_COLOR,ColorWait); break;
               }
            }
         } else {
            //--- METHOD 2: V1.4 SEMA dots (BBuf=36-period, ABuf=9-period) ---
            for(i=bgdLimit; i>=0; i--){
               if(i>Bars-2) continue;
               colors1[i]=colors1[i+1]; colors2[i]=colors2[i+1];
               if(BBufUp[i]) colors1[i]= 1;
               if(BBufDn[i]) colors1[i]=-1;
               if(ABufUp[i]) colors2[i]= 1;
               if(ABufDn[i]) colors2[i]=-1;
               for(index=i; index<Bars-1; index++) if(colors1[index]!=colors1[index+1]) break;
               name=ID+"BGD:"+Time[index+1];
               ObjectDelete(name);
               ObjectDelete(ID+"BGD:"+Time[1]);
               lastTime=Time[i]; if(i==0) lastTime=tDummy;
               ObjectCreate(name,OBJ_RECTANGLE,0,Time[index+1],0,lastTime,MaxValue);
               ObjectSet(name,OBJPROP_BACK,true);
               switch((int)colors1[i]){
                  case -1: ObjectSet(name,OBJPROP_COLOR,ColorDown); break;
                  case  1: ObjectSet(name,OBJPROP_COLOR,ColorUp);   break;
                  default: ObjectSet(name,OBJPROP_COLOR,ColorWait); break;
               }
            }
         }
         RefreshRates();
      }
   }
//+---Daily Open Function--------------------------------------------------------------------------------------------+
   for(i=limit;i>=0;i--){if(TimeDayOfWeek(Time[i+1])!=0){ 
   if(TimeDay(Time[i]) != TimeDay(Time[i+1])){OPening=Open[i-GmtShift];}}
   Bufo=iMA(Symbol(),0,MA_Period,0,MA_Method,PriceMode,i);   BUFdn[i-GmtShift]=OPening; BUFup[i-GmtShift]=OPening;
   if((OPening>Bufo)){BUFup[i]=EMPTY_VALUE;}}
//+----Directional Trading-------------------------------------------------------------------------------------------+
   for(i=limit;i>=0;i--)
   {candle(2,i); TRX[i]= 0; SymClr=CandleWt;
   
   if(S2trend[i]== 1 && S3trend[i]== 1){
   TRX[i]= 1; 
   candle(1,i);
   SymClr=CandleUp;}
   
   if(S2trend[i]==-1 && S3trend[i]==-1){
   TRX[i]=-1; 
   candle(3,i);
   SymClr=clrOrangeRed;}
//+---Select type of BIAS Square or Arrow in current TF--------------------------------------------------------------+
   color BXup=clrGreen,BXdn=clrMaroon;
   if(EBufUp[i]){BOXtxt="  UP SQUARE"; BOXclr=BXup;}
	if(EBufDn[i]){BOXtxt="  DN SQUARE"; BOXclr=BXdn;}
   if(CBufUp[i]){BOXtxt2=" UP ARROW";  BOXclr2=BXup;}   
	if(CBufDn[i]){BOXtxt2=" DN ARROW";  BOXclr2=BXdn;}
   }//End Directional Trading
//+---Power Label----------------------------------------------------------------------------------------------------+
   if(showOpenBias){string BOX2txt=" "; color TXT2clr=C'30,47,62',BOX2clr;
   if(Close[0]>OPening){BOX2txt="Price is Above the Daily Open Line"; BOX2clr=CandleUp;}
                  else {BOX2txt="Price is Below the Daily Open Line"; BOX2clr=CandleDn;}
   PanelsX(ID+"XB01",530-2,-4,"gggggggggggggggggggggg",FontSize+1,"Webdings",BOX2clr);
   LabelsX(ID+"XB02",536-1,-8); ObjectSetText(ID+"XB02",BOX2txt,FontSize+2,FontType,TXT2clr);}	
//+---Symbol Header Function-----------------------------------------------------------------------------------------+
   if(showSymbolHeader){for(i=limit;i>=0;i--){
   if(S3trend[i]== 1){colCarlsberg=clrDodgerBlue;} if(S3trend[i]==-1){colCarlsberg=clrOrangeRed;}
   SetTextRight(ID+"X001",StringSubstr(Symbol(),0,8)+" "+timeFrameToString(timeFrame),LR+280+134,UD+1,Sbg,HDRsize);
   SetTextRight(ID+"X002",StringSubstr(Symbol(),0,8)+" "+timeFrameToString(timeFrame),LR+279+134,UD+0,SymClr,HDRsize);
   SetTextRight(ID+"X003","Carlsberg Don't Do Charts ",LR+413,UD+54,clrBlack,HDRsize2);
   SetTextRight(ID+"X004","Carlsberg Don't Do Charts ",LR+414,UD+55,colCarlsberg,HDRsize2);}}//End Symbol Header
//+---Version Label--------------------------------------------------------------------------------------------------+
   if(showVersion){
   xLabels(ID+"Xard98",53,29); ObjectSetText(ID+"Xard98",Version,FontSize3,FontType,clrBlack);
   xLabels(ID+"Xard99",54,30); ObjectSetText(ID+"Xard99",Version,FontSize3,FontType,SymClr);}
   //+---TextBOX Display------------------------------------------------------------------------------------------------+
   if(showTextBOX){xPanels(ID+"Xard1",4,3,"ggggggg",FontSize3+2,"Webdings",BOXclr);
                   xLabels(ID+"Xard2",3,2); ObjectSetText(ID+"Xard2",BOXtxt,FontSize3,FontType,Snow);
                   xPanels(ID+"Xard3",4+166,3,"ggggggg",FontSize3+2,"Webdings",BOXclr2);
                   xLabels(ID+"Xard4",3+177,2); ObjectSetText(ID+"Xard4",BOXtxt2,FontSize3,FontType,Snow);}//End TextBOX
//+------------------------------------------------------------------------------------------------------------------+
   if(showTEXTx){
   printTEXT(ID+"Xard77",0,"COMPOUND INTEREST",14,"Arial Bold",C'145,125,88',2,4,340);
   printTEXT(ID+"Xard78",0,"'He who understands it, earns it... He who does not, pays it'.",14,"Arial Italic",clrSnow,2,4,564);}
//+------------------------------------------------------------------------------------------------------------------+
   VsRunCalc(rates_total,prev_calculated);
   manageAlerts();
   
   return(rates_total);}
//+------------------------------------------------------------------------------------------------------------------+
   void PanelsX(string aa3,int x,int y,string Text,int fontSize,string Font,color Color){
         ObjectDelete(aa3);
         ObjectCreate(aa3,OBJ_LABEL,0,0,0);
            ObjectSet(aa3,OBJPROP_CORNER,0);
            ObjectSet(aa3,OBJPROP_XDISTANCE,x+moveTxtLR+4);
            ObjectSet(aa3,OBJPROP_YDISTANCE,y+moveTxtUD+4);
            ObjectSet(aa3,OBJPROP_BACK,false);
        ObjectSetText(aa3,Text,fontSize,Font,Color);}
//+------------------------------------------------------------------------------------------------------------------+
   void LabelsX(string aa4,int x,int y){ 
         ObjectDelete(aa4);
         ObjectCreate(aa4,OBJ_LABEL,0,0,0);
            ObjectSet(aa4,OBJPROP_CORNER,0);
            ObjectSet(aa4,OBJPROP_XDISTANCE,x+moveTxtLR+4);
            ObjectSet(aa4,OBJPROP_YDISTANCE,y+moveTxtUD+4);
            ObjectSet(aa4,OBJPROP_BACK,false);}
//+------------------------------------------------------------------------------------------------------------------+
   void printTEXT(string xar,int Win,string Label,int FontS,string FontN,color FontC,int Corner,int yPos,int xPos){
   if(ObjectFind(xar)!=0) ObjectCreate(xar,OBJ_LABEL,0,0,0);
   ObjectSetText(xar,Label,FontS,FontN,FontC);
       ObjectSet(xar,OBJPROP_CORNER,Corner);
       ObjectSet(xar,OBJPROP_XDISTANCE,xPos);
       ObjectSet(xar,OBJPROP_YDISTANCE,yPos);}                 
//+------------------------------------------------------------------------------------------------------------------+
   void Panels(string aa3,int x,int y,string Text,int fontSize,string Font,color Color){
         ObjectDelete(aa3);
         ObjectCreate(aa3,OBJ_LABEL,0,0,0);
            ObjectSet(aa3,OBJPROP_CORNER,2);
            ObjectSet(aa3,OBJPROP_XDISTANCE,x+moveTxtLR+4);
            ObjectSet(aa3,OBJPROP_YDISTANCE,y+moveTxtUD+4);
            ObjectSet(aa3,OBJPROP_BACK,false);
        ObjectSetText(aa3,Text,fontSize,Font,Color);}
//+------------------------------------------------------------------------------------------------------------------+
   void Labels(string aa4,int x,int y){ 
         ObjectDelete(aa4);
         ObjectCreate(aa4,OBJ_LABEL,0,0,0);
            ObjectSet(aa4,OBJPROP_CORNER,2);
            ObjectSet(aa4,OBJPROP_XDISTANCE,x+moveTxtLR+4);
            ObjectSet(aa4,OBJPROP_YDISTANCE,y+moveTxtUD+4);
            ObjectSet(aa4,OBJPROP_BACK,false);}
//+------------------------------------------------------------------------------------------------------------------+
   void SetTextRight(string name,string text,int x,int y,color colour,int fontsize=10, string font="Arial Black"){
       ObjectDelete(name);
    if(ObjectCreate(0,name,OBJ_LABEL,0,0,0)) {
   ObjectSetInteger(0,name,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSetInteger(0,name,OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);}
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
   ObjectSetText(name,text,fontsize,font,colour);}
//+------------------------------------------------------------------------------------------------------------------+
   void label1(string name1,int corner,int xOffset,int yOffset,string text,string fontName,int fontSize,color txtColor){
	     ObjectCreate(name1,OBJ_LABEL,1,0,0);
	        ObjectSet(name1,OBJPROP_CORNER,3);
	        ObjectSet(name1,OBJPROP_XDISTANCE,xOffset); 
	        ObjectSet(name1,OBJPROP_YDISTANCE,yOffset);
	        ObjectSet(name1,OBJPROP_BACK,false);
	ObjectSetInteger(0,name1,OBJPROP_SELECTABLE,false);
	    ObjectSetText(name1,text,fontSize,fontName,txtColor); 
	ObjectSetString(0,name1,OBJPROP_TOOLTIP,"\n");}
//+------------------------------------------------------------------------------------------------------------------+
   void CleanPoint(int i,double& first[],double& second[]){
   if (i>=Bars-3) return;
   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 (i>=Bars-2) return;
   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);}
//+------------------------------------------------------------------------------------------------------------------+
   void manageAlerts(){
   if(inpAlertsOn){int whichBar = (inpAlertsOnCurrent) ? 0 : 1;
   if(TRX[whichBar] != TRX[whichBar+1]){
   if(TRX[whichBar] ==  1) doAlert(whichBar,"BUY BUY BUY");
   if(TRX[whichBar] == -1) doAlert(whichBar,"SELL SELL SELL"); }}}
//+------------------------------------------------------------------------------------------------------------------+
   void doAlert(int forBar, string doWhat){
   static string   previousAlert="nothing";
   static datetime previousTime;  string msg;
   if(previousAlert != doWhat || previousTime != iTime(_Symbol,_Period,forBar)){
      previousAlert  = doWhat;   previousTime  = iTime(_Symbol,_Period,forBar);
   msg=_Symbol+" "+timeFrameToString(_Period)+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" Direction changed to "+doWhat;
   if(inpAlertsMessage)   Alert(msg);
   if(inpAlertsEmail)     SendMail(_Symbol+" Trading ",msg);
   if(inpAlertsPushNotif) SendNotification(msg);
   if(inpAlertsSound)     PlaySound("alert2.wav"); }}
//+----Candle Function-----------------------------------------------------------------------------------------------+
   void candle(int direction,int i){double high,low,bodyHigh,bodyLow;
     bodyHigh = MathMax(Open[i],Close[i]);
     bodyLow  = MathMin(Open[i],Close[i]);
     high     = High[i];
     low      = Low[i];
     candle0[i] = low;     candle1[i] = low;     candle2[i] = low;     candle3[i] = low;
     candle4[i] = bodyLow; candle5[i] = bodyLow; candle6[i] = bodyLow; candle7[i] = bodyLow;
     switch (direction){
           case 1:candle0[i] = high; candle4[i] = bodyHigh; break;
           case 2:candle2[i] = high; candle6[i] = bodyHigh; break;
           case 3:candle3[i] = high; candle7[i] = bodyHigh; break; }}
//+---fSetBuffers Function-------------------------------------------------------------------------------------------+
   void fSetBuffers(){int iChartScale = int(ChartGetInteger(0,CHART_SCALE));
   if(getChartScale == iChartScale) return;
	   getChartScale = iChartScale; int iW=0,rW=0; switch(iChartScale){
		case 0: iW=1; rW=1; break; case 1: iW=1; rW=2; break; case 2: iW= 2; rW= 3; break;
		case 3: iW=4; rW=5; break; case 4: iW=7; rW=9; break; case 5: iW=14; rW=17; break;}
   if(showRib1)           Type=DRAW_HISTOGRAM; else Type=DRAW_NONE;
	SetIndexStyle(0,Type,0,rW,Rib1ClrUP);
	SetIndexStyle(1,Type,0,rW,Rib1ClrDN);
	if(showRib2)           Type=DRAW_HISTOGRAM; else Type=DRAW_NONE;
	SetIndexStyle(2,Type,0,rW,Rib2ClrUP);
	SetIndexStyle(3,Type,0,rW,Rib2ClrDN);
	if(showCandles)        Type=DRAW_HISTOGRAM; else Type=DRAW_NONE;
	SetIndexStyle(18,Type,0,iW,CandleUp);
   SetIndexStyle(20,Type,0,iW,CandleWt);
   SetIndexStyle(21,Type,0,iW,CandleDn);  ChartRedraw();}
//+----Clean Chart Function------------------------------------------------------------------------------------------+
   void CleanUpOnAisle16(){string name; for(int s=ObjectsTotal()-1; s>=0; s--){ name=ObjectName(s);
         if(StringSubstr(name,0,StringLen(ID))==ID){ ObjectDelete(name); }}}//EOF
//+----Semafor-------------------------------------------------------------------------------------------------------+
   int CountZZ(double& ExtMapBufferUp[],double& ExtMapBufferDn[],int Depth,int ExtDeviation,int ExtBackstep){
   int shiftZZ,back,lasthighpos,lastlowpos; double val,res,curlow,curhigh,lasthigh,lastlow;
   for(shiftZZ=Bars-Depth; shiftZZ>=0; shiftZZ--){val=Low[iLowest(NULL,0,MODE_LOW,Depth,shiftZZ)];
   if(val==lastlow) val=0.0;  else { lastlow=val;
   if((Low[shiftZZ]-val)>(ExtDeviation+.5*myPoint)) val=0.0;  else {
   for(back=1; back<=ExtBackstep+1; back++){res=ExtMapBufferUp[shiftZZ+back];
   if (res!=0.0) res = res+deltazz;
   if((res!=0.0)&&(res>val)) ExtMapBufferUp[shiftZZ+back]=0.0;}}}
   if(val==0.0) ExtMapBufferUp[shiftZZ]=0.0; else ExtMapBufferUp[shiftZZ]=val-deltazz;
//--- high
   val=High[iHighest(NULL,0,MODE_HIGH,Depth,shiftZZ)];
   if(val==lasthigh) val=0.0;  else { lasthigh=val;
   if((val-High[shiftZZ])>(ExtDeviation+.5*myPoint)) val=0.0; else {
   for(back=1; back<=ExtBackstep+1; back++){ res=ExtMapBufferDn[shiftZZ+back];
   if(res!=0.0) res = res-deltazz;
   if((res!=0.0)&&(res<val)) ExtMapBufferDn[shiftZZ+back]=0.0;}}}
   if(val==0.0) ExtMapBufferDn[shiftZZ]=0.0; else ExtMapBufferDn[shiftZZ]=val+deltazz;}
//--- final cutting
   lasthigh=-1;  lasthighpos=-1;  lastlow=-1;  lastlowpos=-1;
   for(shiftZZ=Bars-Depth; shiftZZ>=0; shiftZZ--){ curlow=ExtMapBufferUp[shiftZZ];
   if(curlow != 0.0) curlow = curlow+deltazz;    curhigh=ExtMapBufferDn[shiftZZ];
   if(curhigh != 0.0) curhigh = curhigh-deltazz;
   if((curlow==0.0)&&(curhigh==0.0)) continue;
//---
   if(curhigh!=0.0){if(lasthigh>0.0){
   if(lasthigh<curhigh) ExtMapBufferDn[lasthighpos]=0.0; else ExtMapBufferDn[shiftZZ]=0.0;}
//---
   if(lasthigh<curhigh || lasthigh<0.0){lasthigh=curhigh; lasthighpos=shiftZZ;} lastlow=-1;}
   if(curlow!=0.0){if(lastlow>0.0){
   if(lastlow>curlow) ExtMapBufferUp[lastlowpos]=0.0; else ExtMapBufferUp[shiftZZ]=0.0;}
//---
   if((curlow<lastlow)||(lastlow<0.0)){lastlow=curlow; lastlowpos=shiftZZ;} lasthigh=-1;}}
   for(shiftZZ=Bars-1; shiftZZ>=0; shiftZZ--){
   if(shiftZZ>=Bars-Depth) ExtMapBufferUp[shiftZZ]=0.0; else {break;}} return(0);}
//+------------------------------------------------------------------------------------------------------------------+
   int Str2Massive(string VStr,int& M_Count,int& VMass[]){int val=StrToInteger(VStr); if(val>0){M_Count++;
   int mc=ArrayResize(VMass,M_Count); if(mc==0)return(-1); VMass[M_Count-1]=val; return(1);} else return(0);}
//+------------------------------------------------------------------------------------------------------------------+
   int IntFromStr(string ValStr,int& M_Count, int& VMass[]){if(StringLen(ValStr)==0) return(-1);
   string SS=ValStr; int NP=0; string CS; M_Count=0; ArrayResize(VMass,M_Count);
   while(StringLen(SS)>0){NP=StringFind(SS,",");
   if(NP>0){CS=StringSubstr(SS,0,NP); SS=StringSubstr(SS,NP+1,StringLen(SS));}  else {
   if(StringLen(SS)>0){CS=SS; SS="";}} if(Str2Massive(CS,M_Count,VMass)==0){return(-2);}} return(1);}
//+----VWAP SSL Flip (merged from VWAP_SSL_Flip_V1.2)----------------------------------------------------------------+
void VsInit(int &Buf){
   Buf+=1; SetIndexBuffer(Buf,VS_Up);     SetIndexLabel(Buf,"SSL VWAP Up");
   Buf+=1; SetIndexBuffer(Buf,VS_Down);   SetIndexLabel(Buf,"SSL VWAP Down");
   Buf+=1; SetIndexBuffer(Buf,VS_Main);   SetIndexLabel(Buf,"VWAP");
   Buf+=1; SetIndexBuffer(Buf,VS_Trend);  SetIndexStyle(Buf,DRAW_NONE); SetIndexLabel(Buf,NULL);
   Buf+=1; SetIndexBuffer(Buf,VS_CumPVH); SetIndexStyle(Buf,DRAW_NONE); SetIndexLabel(Buf,NULL);
   Buf+=1; SetIndexBuffer(Buf,VS_CumPVL); SetIndexStyle(Buf,DRAW_NONE); SetIndexLabel(Buf,NULL);
   Buf+=1; SetIndexBuffer(Buf,VS_CumVol); SetIndexStyle(Buf,DRAW_NONE); SetIndexLabel(Buf,NULL);
   Buf+=1; SetIndexBuffer(Buf,VS_CumPVT); SetIndexStyle(Buf,DRAW_NONE); SetIndexLabel(Buf,NULL);
   vs_Idx0 = Buf-7;
   for(int k=vs_Idx0;k<=Buf;k++) SetIndexEmptyValue(k,EMPTY_VALUE);
   vs_prefix = "__" + VS_btn_text + "__";
   vs_btnId  = "_" + VS_UniqueButtonID + vs_prefix + "_BT_";
   vs_gvKey  = "XU_VWAPSSL_BTN_" + VS_UniqueButtonID;
   if(ObjectFind(0,vs_btnId)<0){
      bool initial = GlobalVariableCheck(vs_gvKey) ? (GlobalVariableGet(vs_gvKey)!=0.0) : true;
      createButton(vs_btnId, VS_btn_text, VS_btn_Width, VS_btn_Height, btn_Font, VS_btn_FontSize, VS_btn_background_color, VS_btn_border_color, VS_btn_text_ON_color);
      ObjectSetInteger(0,vs_btnId,OBJPROP_STATE,initial);
   }
   ObjectSetInteger(0,vs_btnId,OBJPROP_XDISTANCE,VS_button_x);
   ObjectSetInteger(0,vs_btnId,OBJPROP_YDISTANCE,VS_button_y);
   vs_show = ObjectGetInteger(0,vs_btnId,OBJPROP_STATE);
   GlobalVariableSet(vs_gvKey, vs_show?1.0:0.0);
   ObjectSetInteger(0,vs_btnId,OBJPROP_COLOR, vs_show?VS_btn_text_ON_color:VS_btn_text_OFF_color);
   VsApplyVisibility();
   if(!vs_show){ VsClearBuffers(); }
}
//+------------------------------------------------------------------------------------------------------------------+
void VsApplyVisibility(){
   int dt = vs_show ? DRAW_LINE : DRAW_NONE;
   SetIndexStyle(vs_Idx0,  dt,STYLE_SOLID,VS_LineWidth,VS_UpColor);
   SetIndexStyle(vs_Idx0+1,dt,STYLE_SOLID,VS_LineWidth,VS_DownColor);
   int vw = VS_VWAPWidth<1 ? 1 : VS_VWAPWidth;
   int vst = (vw>1) ? STYLE_SOLID : VS_VWAPStyle;
   SetIndexStyle(vs_Idx0+2,(vs_show&&VS_ShowVWAP)?DRAW_LINE:DRAW_NONE,vst,vw,VS_VWAPColor);
}
//+------------------------------------------------------------------------------------------------------------------+
void VsClearBuffers(){
   int n=ArraySize(VS_Up);
   for(int i=0;i<n;i++){
      VS_Up[i]=EMPTY_VALUE; VS_Down[i]=EMPTY_VALUE; VS_Main[i]=EMPTY_VALUE; VS_Trend[i]=EMPTY_VALUE;
      VS_CumPVH[i]=EMPTY_VALUE; VS_CumPVL[i]=EMPTY_VALUE; VS_CumVol[i]=EMPTY_VALUE; VS_CumPVT[i]=EMPTY_VALUE;
   }
}
//+------------------------------------------------------------------------------------------------------------------+
void VsOnClick(){
   vs_show = ObjectGetInteger(0,vs_btnId,OBJPROP_STATE);
   GlobalVariableSet(vs_gvKey, vs_show?1.0:0.0);
   ObjectSetInteger(0,vs_btnId,OBJPROP_COLOR, vs_show?VS_btn_text_ON_color:VS_btn_text_OFF_color);
   VsApplyVisibility();
   if(vs_show){ vs_forceRecalc=true; VsRunCalc(Bars,0); }
   else VsClearBuffers();
   ChartRedraw(); WindowRedraw();
}
//+------------------------------------------------------------------------------------------------------------------+
bool VsIsNewPeriod(const int pos,const int total){
   if(pos>=total-1) return(true);
   datetime a=Time[pos], b=Time[pos+1];
   switch(VS_Period){
      case VWAP_WEEKLY:  return(TimeDayOfWeek(a)<TimeDayOfWeek(b));
      case VWAP_MONTHLY: return(TimeMonth(a)!=TimeMonth(b));
      default:           return(TimeDay(a)!=TimeDay(b));
   }
}
//+------------------------------------------------------------------------------------------------------------------+
void VsRunCalc(const int total,const int prev){
   if(!vs_show || total<=3) return;
   int maxDisp=MathMax(VS_MaxBars,10); if(maxDisp>total) maxDisp=total;
   int capBars=MathMin(maxDisp+MathMax(VS_WarmupBars,0),total);
   bool full=(prev<=0 || vs_forceRecalc || (total-prev)>2);
   vs_forceRecalc=false;
   int limit,startCalc=-1;
   if(full){
      int sb=maxDisp-1, cap=capBars-1;
      while(sb<cap && !VsIsNewPeriod(sb,total)) sb++;
      startCalc=sb; limit=sb;
      for(int i=sb+1;i<total;i++){ VS_Up[i]=EMPTY_VALUE; VS_Down[i]=EMPTY_VALUE; VS_Main[i]=EMPTY_VALUE; VS_Trend[i]=EMPTY_VALUE; }
   } else {
      limit=total-prev; if(limit<0) limit=0; if(limit>total-2) limit=total-2;
   }
   for(int pos=limit;pos>=0;pos--){
      bool first=(full && pos==startCalc);
      bool np=first || VsIsNewPeriod(pos,total);
      double vol=(double)Volume[pos];
      double typ=(High[pos]+Low[pos]+Close[pos])/3.0;
      if(np){
         VS_CumPVH[pos]=High[pos]*vol; VS_CumPVL[pos]=Low[pos]*vol; VS_CumVol[pos]=vol; VS_CumPVT[pos]=typ*vol;
      } else {
         VS_CumPVH[pos]=VS_CumPVH[pos+1]+High[pos]*vol; VS_CumPVL[pos]=VS_CumPVL[pos+1]+Low[pos]*vol;
         VS_CumVol[pos]=VS_CumVol[pos+1]+vol; VS_CumPVT[pos]=VS_CumPVT[pos+1]+typ*vol;
      }
      double vwapHigh=EMPTY_VALUE, vwapLow=EMPTY_VALUE;
      if(VS_CumVol[pos]>0.0){ vwapHigh=VS_CumPVH[pos]/VS_CumVol[pos]; vwapLow=VS_CumPVL[pos]/VS_CumVol[pos]; }
      int prevTrend=(first || pos>=total-1) ? -1 : (int)VS_Trend[pos+1];
      if(prevTrend!=0 && prevTrend!=1) prevTrend=-1;
      int currentTrend=prevTrend;
      if(vwapHigh!=EMPTY_VALUE){
         if(prevTrend==-1) currentTrend=(Close[pos]>=vwapHigh)?0:1;
         else if(prevTrend==0 && Close[pos]<vwapLow) currentTrend=1;
         else if(prevTrend==1 && Close[pos]>vwapHigh) currentTrend=0;
      }
      VS_Trend[pos]=currentTrend;
      VS_Up[pos]=EMPTY_VALUE; VS_Down[pos]=EMPTY_VALUE; VS_Main[pos]=EMPTY_VALUE;
      if(pos<maxDisp && VS_ShowVWAP && VS_CumVol[pos]>0.0) VS_Main[pos]=VS_CumPVT[pos]/VS_CumVol[pos];
      if(pos<maxDisp && vwapHigh!=EMPTY_VALUE){
         if(currentTrend==0) VS_Up[pos]=vwapLow; else if(currentTrend==1) VS_Down[pos]=vwapHigh;
      }
   }
   if(!full) VsCheckAlert(total);
}
//+------------------------------------------------------------------------------------------------------------------+
void VsCheckAlert(const int total){
   if(!VS_AlertsOn || total<3) return;
   int alertBar=VS_AlertsOnCurrent?0:1;
   if(alertBar+1>=total) return;
   int currentTrend=(int)VS_Trend[alertBar], prevTrend=(int)VS_Trend[alertBar+1];
   if(currentTrend<0 || prevTrend<0 || currentTrend==prevTrend) return;
   datetime barTime=Time[alertBar];
   if(vs_lastAlertBarTime==barTime && vs_lastAlertTrend==currentTrend) return;
   int maxAgeSec=(VS_AlertsOnCurrent?2:3)*PeriodSeconds(_Period);
   if(TimeCurrent()-barTime>maxAgeSec) return;
   vs_lastAlertBarTime=barTime; vs_lastAlertTrend=currentTrend;
   string dir=(currentTrend==0)?"UP (Green)":"DOWN (Red)";
   string msg="VWAP SSL Flip "+_Symbol+" "+timeFrameToString(_Period)+": line flipped to "+dir;
   if(VS_AlertsMessage) Alert(msg);
   if(VS_AlertsSound)   PlaySound(VS_AlertSoundFile);
   if(VS_AlertsPush)    SendNotification(msg);
   if(VS_AlertsEmail)   SendMail("VWAP SSL Flip "+_Symbol,msg);
}
//+---OnChartEvent Function------------------------------------------------------------------------------------------+
   void OnChartEvent(const int id, const long& lparam, const double& dparam, const string& sparam){
   if(id==CHARTEVENT_OBJECT_CREATE || id==CHARTEVENT_OBJECT_DELETE) return;
   if(id==CHARTEVENT_MOUSE_MOVE    || id==CHARTEVENT_MOUSE_WHEEL)   return;
   if(id==CHARTEVENT_OBJECT_CLICK && sparam==vs_btnId){ VsOnClick(); return; }
   if(id==CHARTEVENT_OBJECT_CLICK && ObjectGet(sparam,OBJPROP_TYPE)==OBJ_BUTTON){
      if(StringFind(sparam,MyName+":back:",0)==0) ObjectSet(sparam,OBJPROP_STATE,false);
      // ── Button 1: BGD ON/OFF ──────────────────────────────────────────────────
      if(sparam == buttonId){
         show_data = ObjectGetInteger(0, buttonId, OBJPROP_STATE);
         if(show_data){
            ObjectSetInteger(0, buttonId, OBJPROP_COLOR, btn_text_ON_color);
            bgd_recalc = true;
         } else {
            ObjectSetInteger(0, buttonId, OBJPROP_COLOR, btn_text_OFF_color);
            string delName;
            for(int d=ObjectsTotal()-1; d>=0; d--){
               delName=ObjectName(d);
               if(StringSubstr(delName,0,StringLen(ID+"BGD:"))== ID+"BGD:") ObjectDelete(delName);
            }
         }
         ChartRedraw(); WindowRedraw();
      }
      // ── Button 2: BGD METHOD S3MA <-> SEMA ──────────────────────────────
      if(sparam == buttonId2){
         bgd_method_sema = ObjectGetInteger(0, buttonId2, OBJPROP_STATE);
         if(bgd_method_sema){
            ObjectSetString (0, buttonId2, OBJPROP_TEXT,  btn2_text_SEMA);
            ObjectSetInteger(0, buttonId2, OBJPROP_COLOR, btn2_text_SEMA_color);
         } else {
            ObjectSetString (0, buttonId2, OBJPROP_TEXT,  btn2_text_S3MA);
            ObjectSetInteger(0, buttonId2, OBJPROP_COLOR, btn2_text_S3MA_color);
         }
         string delName3;
         for(int d3=ObjectsTotal()-1; d3>=0; d3--){
            delName3=ObjectName(d3);
            if(StringSubstr(delName3,0,StringLen(ID+"BGD:"))== ID+"BGD:") ObjectDelete(delName3);
         }
         bgd_method_recalc = true;
         ChartRedraw(); WindowRedraw();
      }
      if(IsStopped()) return; fSetBuffers();}  OnInit();}
//+------------------------------------------------------------------------------------------------------------------+
   void xPanels(string M5,int x,int y,string Text,int fontSize,string Font,color Color){
   static int window=0; if(window<0) window=WindowFind(ID); 
          ObjectCreate(M5,OBJ_LABEL,window,0,0);
             ObjectSet(M5,OBJPROP_CORNER,2);
             ObjectSet(M5,OBJPROP_XDISTANCE,x+move_text_sideways);
             ObjectSet(M5,OBJPROP_YDISTANCE,y+move_text_updown);
             ObjectSet(M5,OBJPROP_BACK,false);
         ObjectSetText(M5,Text,fontSize,Font,Color);}
//+------------------------------------------------------------------------------------------------------------------+
   void xLabels(string M6,int x,int y){
   static int window=0; if(window<0) window=WindowFind(ID);
          ObjectCreate(M6,OBJ_LABEL,window,0,0);
             ObjectSet(M6,OBJPROP_CORNER,2);
             ObjectSet(M6,OBJPROP_XDISTANCE,x+move_text_sideways);
             ObjectSet(M6,OBJPROP_YDISTANCE,y+move_text_updown);
             ObjectSet(M6,OBJPROP_BACK,false);}
//+----END OF FILE---------------------------------------------------------------------------------------------------+