//+------------------------------------------------------------------+
//|                         Laguerre Filters (on chart) ATR Bands BT |
//|                                                          v. 1.01 |
//|                     Enhanced with Multi-ATR Bands & Toggle Button|
//+------------------------------------------------------------------+
#property copyright "© TASC 2025.07 Laguerre Filters"
#property link      "https://www.tradingview.com/script/6QWQYUT8-TASC-2025-07-Laguerre-Filters/"
#property version   "1.01"
#property indicator_chart_window
#property indicator_buffers 34      // 5 (Candles) + 2 (Main) + 20 (10 ATR Bands) + 1 (FilterCalculations) + 6 (L0-L5)
#property indicator_plots   12      // 1 Colored Candles + 1 Laguerre Filter + 10 ATR Bands

//--- Plot definitions
// PLOT 0: Colored Candles (Drawn first so lines render cleanly on top)
#property indicator_label1  "Colored Candles"
#property indicator_type1   DRAW_COLOR_CANDLES
#property indicator_color1  C'72,209,150',C'255,0,128' // Mint Green (Up), Neon Magenta (Down)
#property indicator_width1  1

// PLOT 1: Laguerre Filter (Color Line)
#property indicator_label2  "Laguerre Filter"
#property indicator_type2   DRAW_COLOR_LINE
#property indicator_color2  clrDarkGreen,C'178,34,34' // Green (Up), Red (Down)
#property indicator_width2  3
#property indicator_style2  STYLE_SOLID

// PLOT 2-11: ATR BANDS (10 bands)
#property indicator_label3  "ATR 1.1 Up"
#property indicator_type3   DRAW_COLOR_LINE
#property indicator_color3  clrSpringGreen,clrHotPink
#property indicator_width3  1
#property indicator_style3  STYLE_DOT

#property indicator_label4  "ATR 1.2 Up"
#property indicator_type4   DRAW_COLOR_LINE
#property indicator_color4  clrSpringGreen,clrHotPink
#property indicator_width4  1
#property indicator_style4  STYLE_DOT

#property indicator_label5  "ATR 1.3 Up"
#property indicator_type5   DRAW_COLOR_LINE
#property indicator_color5  clrSpringGreen,clrHotPink
#property indicator_width5  1
#property indicator_style5  STYLE_DOT

#property indicator_label6  "ATR 1.4 Up"
#property indicator_type6   DRAW_COLOR_LINE
#property indicator_color6  clrSpringGreen,clrHotPink
#property indicator_width6  1
#property indicator_style6  STYLE_SOLID

#property indicator_label7  "ATR 1.5 Up"
#property indicator_type7   DRAW_COLOR_LINE
#property indicator_color7  clrSpringGreen,clrHotPink
#property indicator_width7  2
#property indicator_style7  STYLE_SOLID

#property indicator_label8  "ATR 1.1 Down"
#property indicator_type8   DRAW_COLOR_LINE
#property indicator_color8  clrSpringGreen,clrHotPink
#property indicator_width8  1
#property indicator_style8  STYLE_DOT

#property indicator_label9  "ATR 1.2 Down"
#property indicator_type9   DRAW_COLOR_LINE
#property indicator_color9  clrSpringGreen,clrHotPink
#property indicator_width9  1
#property indicator_style9  STYLE_DOT

#property indicator_label10 "ATR 1.3 Down"
#property indicator_type10  DRAW_COLOR_LINE
#property indicator_color10 clrSpringGreen,clrHotPink
#property indicator_width10 1
#property indicator_style10 STYLE_DOT

#property indicator_label11 "ATR 1.4 Down"
#property indicator_type11  DRAW_COLOR_LINE
#property indicator_color11 clrSpringGreen,clrHotPink
#property indicator_width11 1
#property indicator_style11 STYLE_SOLID

#property indicator_label12 "ATR 1.5 Down"
#property indicator_type12  DRAW_COLOR_LINE
#property indicator_color12 clrSpringGreen,clrHotPink
#property indicator_width12 2
#property indicator_style12 STYLE_SOLID

//--- Input parameters
input group "=== Laguerre Filter Settings ==="
input ENUM_APPLIED_PRICE SourceInput     = PRICE_CLOSE;
input int                FilterPeriod    = 30;
input double             GammaValue      = 0.5;

input group "=== Candlestick Colors ==="
input bool               ColorCandles    = true;           // Color Candlesticks
input color              Candle_ColorUp  = C'72,209,150';   // Candlestick Uptrend Color (Mint Green)
input color              Candle_ColorDn  = C'255,0,128';   // Candlestick Downtrend Color (Neon Magenta)

input group "=== ATR Bands Settings ==="
input bool               ShowATRBands    = true;           // Show ATR Bands
input color              ATR_ColorUp     = clrSpringGreen; // ATR Bands Uptrend Color
input color              ATR_ColorDn     = clrHotPink;     // ATR Bands Downtrend Color
input int                ATR_Period      = 14;             // ATR Period
input double             ATR_Multiplier1 = 1.1;            // ATR Multiplier 1
input double             ATR_Multiplier2 = 1.2;            // ATR Multiplier 2
input double             ATR_Multiplier3 = 1.3;            // ATR Multiplier 3
input double             ATR_Multiplier4 = 1.4;            // ATR Multiplier 4
input double             ATR_Multiplier5 = 1.5;            // ATR Multiplier 5

//Forex-Station copy & paste code; Button code start 11
input group "=== Toggle Button Settings ==="
input string             button_note1          = "------------------------------"; // ------------------------------
input int                btn_Subwindow         = 0;                  // What window to put the button on
input ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER;  // chart btn_corner for anchoring
input string             btn_text              = "Laguerre: ON";     // Display id
input string             btn_Font              = "Arial";            // button font name
input int                btn_FontSize          = 9;                  // btn__font size
input color              btn_text_ON_color     = clrLime;            // ON color when the button is turned on
input color              btn_text_OFF_color    = clrRed;             // OFF color when the button is turned off
input color              btn_background_color  = clrDimGray;         // background color of the button
input color              btn_border_color      = clrBlack;           // border color the button
input int                button_x              = 20;                 // Horizontal location
input int                button_y              = 40;                 // Vertical location
input int                btn_Width             = 80;                 // btn__width
input int                btn_Height            = 20;                 // btn__height
input string             UniqueButtonID        = "Laguerre_ATR_BT";  // Unique Button for each button                      
input string             button_note2          = "------------------------------"; // ------------------------------
string indicatorFileName, IndicatorName, IndicatorObjPrefix, buttonId;
//Forex-Station copy & paste code; Button code end 11

bool     IndicatorEnabled = true;
bool     IndicatorHidden  = false; // True when hidden via toggle button
string   ToggleButtonName;        // Name of toggle button object
string   g_gvHidden;              // GlobalVariable name to persist toggle state across timeframe/symbol changes
string   g_prefix;

//--- Indicator buffers (34 buffers total)
// Buffers 0-4: Colored Candles (Plot 0)
double CandleOpen[];
double CandleHigh[];
double CandleLow[];
double CandleClose[];
double CandleColor[];

// Buffers 5-6: Main Line (Plot 1)
double FilterBuffer[];
double ColorBuffer[];

// Buffers 7-26: ATR Bands (Plots 2-11, Data and Color buffers for 10 bands)
double ATR_Up11[], Color_Up11[];
double ATR_Up12[], Color_Up12[];
double ATR_Up13[], Color_Up13[];
double ATR_Up14[], Color_Up14[];
double ATR_Up15[], Color_Up15[];

double ATR_Dn11[], Color_Dn11[];
double ATR_Dn12[], Color_Dn12[];
double ATR_Dn13[], Color_Dn13[];
double ATR_Dn14[], Color_Dn14[];
double ATR_Dn15[], Color_Dn15[];

// Buffer 27: Calculations
double FilterCalculations[];

// Buffers 28-33: Laguerre State (INDICATOR_CALCULATIONS - MT5 managed)
double L0[], L1[], L2[], L3[], L4[], L5[];

//+------------------------------------------------------------------+
//| HELPER - resolve button text based on state                      |
//+------------------------------------------------------------------+
string GetButtonText(bool isEnabled)
{
   string t = btn_text;
   if(isEnabled)
   {
      if(StringFind(t, "OFF") >= 0) StringReplace(t, "OFF", "ON");
      else if(StringFind(t, "Off") >= 0) StringReplace(t, "Off", "On");
      else if(StringFind(t, "off") >= 0) StringReplace(t, "off", "on");
   }
   else
   {
      if(StringFind(t, "ON") >= 0) StringReplace(t, "ON", "OFF");
      else if(StringFind(t, "On") >= 0) StringReplace(t, "On", "Off");
      else if(StringFind(t, "on") >= 0) StringReplace(t, "on", "off");
   }
   return t;
}

//Forex-Station copy & paste code; Button code start 12
string GenerateIndicatorName(const string target) //don't change anything here
{
   string name = target;
   int try_idx = 2;
   while(ChartWindowFind(0, name) != -1)
   {
      name = target + " #" + IntegerToString(try_idx++);
   }
   return name;
}

void CreateToggleButton()
{
   if(ObjectFind(0, buttonId) < 0)
   {
      int y_pos = button_y;
      int obj_total = ObjectsTotal(0, -1, OBJ_BUTTON);
      bool collision = true;
      while(collision)
      {
         collision = false;
         for(int i = 0; i < obj_total; i++)
         {
            string name = ObjectName(0, i, -1, OBJ_BUTTON);
            if(name == buttonId) continue;
            if((ENUM_BASE_CORNER)ObjectGetInteger(0, name, OBJPROP_CORNER) != btn_corner) continue;
            if(ObjectGetInteger(0, name, OBJPROP_XDISTANCE) == button_x &&
               ObjectGetInteger(0, name, OBJPROP_YDISTANCE) == y_pos)
            {
               y_pos += btn_Height + 4;
               collision = true;
               break;
            }
         }
      }

      ObjectCreate(0, buttonId, OBJ_BUTTON, btn_Subwindow, 0, 0);

      ObjectSetInteger(0, buttonId, OBJPROP_CORNER,       btn_corner);
      ObjectSetInteger(0, buttonId, OBJPROP_XDISTANCE,    button_x);
      ObjectSetInteger(0, buttonId, OBJPROP_YDISTANCE,    y_pos);
      ObjectSetInteger(0, buttonId, OBJPROP_XSIZE,        btn_Width);
      ObjectSetInteger(0, buttonId, OBJPROP_YSIZE,        btn_Height);
      ObjectSetString (0, buttonId, OBJPROP_FONT,         btn_Font);
      ObjectSetInteger(0, buttonId, OBJPROP_FONTSIZE,     btn_FontSize);
      ObjectSetInteger(0, buttonId, OBJPROP_BGCOLOR,      btn_background_color);
      ObjectSetInteger(0, buttonId, OBJPROP_BORDER_COLOR, btn_border_color);
      ObjectSetInteger(0, buttonId, OBJPROP_BORDER_TYPE,  BORDER_RAISED);
      ObjectSetInteger(0, buttonId, OBJPROP_SELECTABLE,   false);
      ObjectSetInteger(0, buttonId, OBJPROP_HIDDEN,       true);
      ObjectSetInteger(0, buttonId, OBJPROP_TIMEFRAMES,   OBJ_ALL_PERIODS);
   }

   UpdateToggleButton();
}

void UpdateToggleButton()
{
   if(ObjectFind(0, buttonId) < 0) return;

   IndicatorEnabled = !IndicatorHidden;

   string labelText  = GetButtonText(IndicatorEnabled);
   color  textColor  = IndicatorEnabled ? btn_text_ON_color : btn_text_OFF_color;

   ObjectSetString (0, buttonId, OBJPROP_TEXT,         labelText);
   ObjectSetString (0, buttonId, OBJPROP_FONT,         btn_Font);
   ObjectSetInteger(0, buttonId, OBJPROP_FONTSIZE,     btn_FontSize);
   ObjectSetInteger(0, buttonId, OBJPROP_COLOR,        textColor);
   ObjectSetInteger(0, buttonId, OBJPROP_BGCOLOR,      btn_background_color);
   ObjectSetInteger(0, buttonId, OBJPROP_BORDER_COLOR, btn_border_color);
   ObjectSetInteger(0, buttonId, OBJPROP_CORNER,       btn_corner);
   ObjectSetInteger(0, buttonId, OBJPROP_XDISTANCE,    button_x);
   ObjectSetInteger(0, buttonId, OBJPROP_XSIZE,        btn_Width);
   ObjectSetInteger(0, buttonId, OBJPROP_YSIZE,        btn_Height);
   ObjectSetInteger(0, buttonId, OBJPROP_STATE,        IndicatorEnabled);

   ChartRedraw(0);
}

//+------------------------------------------------------------------+
//| Set Candles visibility and colors                                |
//+------------------------------------------------------------------+
void SetCandlesVisibility(bool visible)
{
    if(visible && !IndicatorHidden)
    {
        PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_COLOR_CANDLES);
        PlotIndexSetInteger(0, PLOT_COLOR_INDEXES, 2);
        PlotIndexSetInteger(0, PLOT_LINE_COLOR, 0, Candle_ColorUp);
        PlotIndexSetInteger(0, PLOT_LINE_COLOR, 1, Candle_ColorDn);
    }
    else
    {
        PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_NONE);
    }
}

//+------------------------------------------------------------------+
//| Set ATR bands visibility, styles, and colors                     |
//+------------------------------------------------------------------+
void SetATRBandsVisibility(bool visible)
{
    if(visible && !IndicatorHidden)
    {
        for(int i = 2; i <= 11; i++)
        {
            PlotIndexSetInteger(i, PLOT_DRAW_TYPE, DRAW_COLOR_LINE);
            PlotIndexSetInteger(i, PLOT_COLOR_INDEXES, 2);
            PlotIndexSetInteger(i, PLOT_LINE_COLOR, 0, ATR_ColorUp);
            PlotIndexSetInteger(i, PLOT_LINE_COLOR, 1, ATR_ColorDn);
        }
        
        PlotIndexSetInteger(2, PLOT_LINE_STYLE, STYLE_DOT);
        PlotIndexSetInteger(3, PLOT_LINE_STYLE, STYLE_DOT);
        PlotIndexSetInteger(4, PLOT_LINE_STYLE, STYLE_DOT);
        PlotIndexSetInteger(5, PLOT_LINE_STYLE, STYLE_SOLID);
        PlotIndexSetInteger(6, PLOT_LINE_STYLE, STYLE_SOLID);
        PlotIndexSetInteger(7, PLOT_LINE_STYLE, STYLE_DOT);
        PlotIndexSetInteger(8, PLOT_LINE_STYLE, STYLE_DOT);
        PlotIndexSetInteger(9, PLOT_LINE_STYLE, STYLE_DOT);
        PlotIndexSetInteger(10, PLOT_LINE_STYLE, STYLE_SOLID);
        PlotIndexSetInteger(11, PLOT_LINE_STYLE, STYLE_SOLID);
        
        PlotIndexSetInteger(6, PLOT_LINE_WIDTH, 2);
        PlotIndexSetInteger(11, PLOT_LINE_WIDTH, 2);
        for(int i = 2; i <= 5; i++) PlotIndexSetInteger(i, PLOT_LINE_WIDTH, 1);
        for(int i = 7; i <= 10; i++) PlotIndexSetInteger(i, PLOT_LINE_WIDTH, 1);
    }
    else
    {
        for(int i = 2; i <= 11; i++) PlotIndexSetInteger(i, PLOT_DRAW_TYPE, DRAW_NONE);
    }
}

//+------------------------------------------------------------------+
//| Apply Plots Style based on button toggle state                   |
//+------------------------------------------------------------------+
void ApplyPlotsStyle()
{
    if(IndicatorHidden)
    {
        for(int p = 0; p < 12; p++)
            PlotIndexSetInteger(p, PLOT_DRAW_TYPE, DRAW_NONE);
    }
    else
    {
        SetCandlesVisibility(ColorCandles);
        PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_COLOR_LINE);
        SetATRBandsVisibility(ShowATRBands);
    }
}

void ToggleIndicatorVisibility()
{
    IndicatorHidden  = !IndicatorHidden;
    IndicatorEnabled = !IndicatorHidden;

    if(g_gvHidden != "")
        GlobalVariableSet(g_gvHidden, IndicatorHidden ? 1.0 : 0.0);

    ApplyPlotsStyle();
    UpdateToggleButton();
    ChartRedraw(0);
}

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
    if(id == CHARTEVENT_OBJECT_CLICK)
    {
        string altId = "_" + UniqueButtonID + IndicatorObjPrefix + "_BT_";
        if(sparam == buttonId || sparam == ToggleButtonName || sparam == altId)
        {
            ToggleIndicatorVisibility();
        }
    }
}
//Forex-Station copy & paste code; Button code end 12

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
{
    IndicatorObjPrefix = "__" + btn_text + "__";
    buttonId           = IndicatorObjPrefix + UniqueButtonID;
    ToggleButtonName   = buttonId;
    IndicatorName      = "Laguerre Filters (" + string(FilterPeriod) + "," + string(GammaValue) + ") ATR Bands BT [" + UniqueButtonID + "]";
    g_prefix           = "LF_ATR_" + UniqueButtonID + "_";
    g_gvHidden         = g_prefix + IntegerToString(ChartID()) + "_Hidden";

    // Clean up any temporary buttons from previous format if present
    string altId = "_" + UniqueButtonID + IndicatorObjPrefix + "_BT_";
    if(ObjectFind(0, altId) >= 0 && altId != buttonId)
        ObjectDelete(0, altId);

    // Clean up any old '#' phantom buttons from earlier runs
    int total_objs = ObjectsTotal(0, -1, OBJ_BUTTON);
    for(int i = total_objs - 1; i >= 0; i--)
    {
        string bName = ObjectName(0, i, -1, OBJ_BUTTON);
        if(StringFind(bName, btn_text + " #") >= 0)
            ObjectDelete(0, bName);
    }

    // Restore toggle state across timeframe/symbol changes
    bool hasSavedState = false;
    bool savedHidden   = false;

    if(ObjectFind(0, buttonId) >= 0)
    {
        string btnTxt = ObjectGetString(0, buttonId, OBJPROP_TEXT);
        long   btnSt  = ObjectGetInteger(0, buttonId, OBJPROP_STATE);

        if(StringFind(btnTxt, "OFF") >= 0 || StringFind(btnTxt, "Off") >= 0 || btnSt == 0)
            savedHidden = true;
        else if(StringFind(btnTxt, "ON") >= 0 || StringFind(btnTxt, "On") >= 0 || btnSt != 0)
            savedHidden = false;
        hasSavedState = true;
    }

    if(!hasSavedState && GlobalVariableCheck(g_gvHidden))
    {
        savedHidden   = (GlobalVariableGet(g_gvHidden) > 0.5);
        hasSavedState = true;
    }

    if(hasSavedState)
        IndicatorHidden = savedHidden;
    else
        IndicatorHidden = false;

    IndicatorEnabled = !IndicatorHidden;

    if(g_gvHidden != "")
        GlobalVariableSet(g_gvHidden, IndicatorHidden ? 1.0 : 0.0);

    // Buffers 0-4: Colored Candles (Plot 0)
    SetIndexBuffer(0, CandleOpen,  INDICATOR_DATA);
    SetIndexBuffer(1, CandleHigh,  INDICATOR_DATA);
    SetIndexBuffer(2, CandleLow,   INDICATOR_DATA);
    SetIndexBuffer(3, CandleClose, INDICATOR_DATA);
    SetIndexBuffer(4, CandleColor, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(0, PLOT_LABEL, "Colored Candles");
    PlotIndexSetInteger(0, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, 0.0);
    
    // Buffers 5-6: Main Line (Plot 1)
    SetIndexBuffer(5, FilterBuffer, INDICATOR_DATA);
    SetIndexBuffer(6, ColorBuffer,  INDICATOR_COLOR_INDEX);
    PlotIndexSetString(1, PLOT_LABEL, "Laguerre Filter");
    PlotIndexSetInteger(1, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    // Buffers 7-16: ATR Upper Bands (Plots 2-6)
    SetIndexBuffer(7, ATR_Up11, INDICATOR_DATA);
    SetIndexBuffer(8, Color_Up11, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(2, PLOT_LABEL, "ATR 1.1 Up");
    PlotIndexSetInteger(2, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    SetIndexBuffer(9, ATR_Up12, INDICATOR_DATA);
    SetIndexBuffer(10, Color_Up12, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(3, PLOT_LABEL, "ATR 1.2 Up");
    PlotIndexSetInteger(3, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(3, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    SetIndexBuffer(11, ATR_Up13, INDICATOR_DATA);
    SetIndexBuffer(12, Color_Up13, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(4, PLOT_LABEL, "ATR 1.3 Up");
    PlotIndexSetInteger(4, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(4, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    SetIndexBuffer(13, ATR_Up14, INDICATOR_DATA);
    SetIndexBuffer(14, Color_Up14, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(5, PLOT_LABEL, "ATR 1.4 Up");
    PlotIndexSetInteger(5, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(5, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    SetIndexBuffer(15, ATR_Up15, INDICATOR_DATA);
    SetIndexBuffer(16, Color_Up15, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(6, PLOT_LABEL, "ATR 1.5 Up");
    PlotIndexSetInteger(6, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(6, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    // Buffers 17-26: ATR Lower Bands (Plots 7-11)
    SetIndexBuffer(17, ATR_Dn11, INDICATOR_DATA);
    SetIndexBuffer(18, Color_Dn11, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(7, PLOT_LABEL, "ATR 1.1 Down");
    PlotIndexSetInteger(7, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(7, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    SetIndexBuffer(19, ATR_Dn12, INDICATOR_DATA);
    SetIndexBuffer(20, Color_Dn12, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(8, PLOT_LABEL, "ATR 1.2 Down");
    PlotIndexSetInteger(8, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(8, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    SetIndexBuffer(21, ATR_Dn13, INDICATOR_DATA);
    SetIndexBuffer(22, Color_Dn13, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(9, PLOT_LABEL, "ATR 1.3 Down");
    PlotIndexSetInteger(9, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(9, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    SetIndexBuffer(23, ATR_Dn14, INDICATOR_DATA);
    SetIndexBuffer(24, Color_Dn14, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(10, PLOT_LABEL, "ATR 1.4 Down");
    PlotIndexSetInteger(10, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(10, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    SetIndexBuffer(25, ATR_Dn15, INDICATOR_DATA);
    SetIndexBuffer(26, Color_Dn15, INDICATOR_COLOR_INDEX);
    PlotIndexSetString(11, PLOT_LABEL, "ATR 1.5 Down");
    PlotIndexSetInteger(11, PLOT_COLOR_INDEXES, 2);
    PlotIndexSetDouble(11, PLOT_EMPTY_VALUE, EMPTY_VALUE);
    
    // Buffer 27: Calculations
    SetIndexBuffer(27, FilterCalculations, INDICATOR_CALCULATIONS);
    
    // Buffers 28-33: Laguerre State (INDICATOR_CALCULATIONS)
    // Using INDICATOR_CALCULATIONS means MT5 manages these arrays properly
    // and handles index shifting when new bars appear - THIS FIXES REPAINTING
    SetIndexBuffer(28, L0, INDICATOR_CALCULATIONS);
    SetIndexBuffer(29, L1, INDICATOR_CALCULATIONS);
    SetIndexBuffer(30, L2, INDICATOR_CALCULATIONS);
    SetIndexBuffer(31, L3, INDICATOR_CALCULATIONS);
    SetIndexBuffer(32, L4, INDICATOR_CALCULATIONS);
    SetIndexBuffer(33, L5, INDICATOR_CALCULATIONS);
    
    ApplyPlotsStyle();
    CreateToggleButton();
    
    IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
    IndicatorSetString(INDICATOR_SHORTNAME, IndicatorName);
    
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Custom Indicator Deinitialization                                |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   if(reason == REASON_REMOVE || reason == REASON_CHARTCLOSE)
   {
      ObjectDelete(0, buttonId);
      ObjectDelete(0, ToggleButtonName);
      if(g_gvHidden != "")
         GlobalVariableDel(g_gvHidden);
   }
   else if(reason == REASON_PARAMETERS)
   {
      ObjectDelete(0, buttonId);
      ObjectDelete(0, ToggleButtonName);
   }
   else
   {
      // Switch timeframe/symbol:
      // keep button, state preserved via g_gvHidden and button text
   }
}

//+------------------------------------------------------------------+
//| Calculate Multi-ATR Bands                                        |
//+------------------------------------------------------------------+
void CalculateATRBands(const double &high[], const double &low[], const double &close[], int start_index, int total_rates)
{
    if(total_rates < ATR_Period + 1) return;

    for(int i = start_index; i >= 0; i--)
    {
        if(i > total_rates - ATR_Period - 1)
        {
            ATR_Up11[i] = EMPTY_VALUE;
            ATR_Up12[i] = EMPTY_VALUE;
            ATR_Up13[i] = EMPTY_VALUE;
            ATR_Up14[i] = EMPTY_VALUE;
            ATR_Up15[i] = EMPTY_VALUE;
            ATR_Dn11[i] = EMPTY_VALUE;
            ATR_Dn12[i] = EMPTY_VALUE;
            ATR_Dn13[i] = EMPTY_VALUE;
            ATR_Dn14[i] = EMPTY_VALUE;
            ATR_Dn15[i] = EMPTY_VALUE;
            continue;
        }

        double atr_sum = 0;
        for(int j = 0; j < ATR_Period; j++)
        {
            int sample_idx = i + j;
            int prev_sample_idx = sample_idx + 1;
            if(prev_sample_idx >= total_rates) continue;
            
            double tr = MathMax(high[sample_idx] - low[sample_idx],
                       MathMax(MathAbs(high[sample_idx] - close[prev_sample_idx]),
                               MathAbs(low[sample_idx] - close[prev_sample_idx])));
            atr_sum += tr;
        }
        double atr = atr_sum / ATR_Period;
        
        double center_value = FilterBuffer[i];
        if(center_value == EMPTY_VALUE || center_value == 0)
        {
            ATR_Up11[i] = EMPTY_VALUE;
            ATR_Up12[i] = EMPTY_VALUE;
            ATR_Up13[i] = EMPTY_VALUE;
            ATR_Up14[i] = EMPTY_VALUE;
            ATR_Up15[i] = EMPTY_VALUE;
            ATR_Dn11[i] = EMPTY_VALUE;
            ATR_Dn12[i] = EMPTY_VALUE;
            ATR_Dn13[i] = EMPTY_VALUE;
            ATR_Dn14[i] = EMPTY_VALUE;
            ATR_Dn15[i] = EMPTY_VALUE;
            continue;
        }
        
        ATR_Up11[i] = center_value + (atr * ATR_Multiplier1);
        ATR_Up12[i] = center_value + (atr * ATR_Multiplier2);
        ATR_Up13[i] = center_value + (atr * ATR_Multiplier3);
        ATR_Up14[i] = center_value + (atr * ATR_Multiplier4);
        ATR_Up15[i] = center_value + (atr * ATR_Multiplier5);
        
        ATR_Dn11[i] = center_value - (atr * ATR_Multiplier1);
        ATR_Dn12[i] = center_value - (atr * ATR_Multiplier2);
        ATR_Dn13[i] = center_value - (atr * ATR_Multiplier3);
        ATR_Dn14[i] = center_value - (atr * ATR_Multiplier4);
        ATR_Dn15[i] = center_value - (atr * ATR_Multiplier5);

        // Assign trend color index to all ATR Bands (upper and lower):
        // 0 = clrSpringGreen (Uptrend)
        // 1 = clrHotPink (Downtrend)
        double trend_color = ColorBuffer[i];
        
        Color_Up11[i] = trend_color;
        Color_Up12[i] = trend_color;
        Color_Up13[i] = trend_color;
        Color_Up14[i] = trend_color;
        Color_Up15[i] = trend_color;
        
        Color_Dn11[i] = trend_color;
        Color_Dn12[i] = trend_color;
        Color_Dn13[i] = trend_color;
        Color_Dn14[i] = trend_color;
        Color_Dn15[i] = trend_color;
    }
}

//+------------------------------------------------------------------+
//| Get source price                                                 |
//+------------------------------------------------------------------+
double GetSourcePrice(int index, ENUM_APPLIED_PRICE price_type,
                     const double &open[], const double &high[],
                     const double &low[], const double &close[])
{
    if(index >= ArraySize(open) || index < 0) return 0;
    switch(price_type)
    {
        case PRICE_OPEN:    return open[index];
        case PRICE_HIGH:    return high[index];
        case PRICE_LOW:     return low[index];
        case PRICE_CLOSE:   return close[index];
        case PRICE_MEDIAN:  return (high[index] + low[index]) / 2.0;
        case PRICE_TYPICAL: return (high[index] + low[index] + close[index]) / 3.0;
        case PRICE_WEIGHTED:return (high[index] + low[index] + close[index] + close[index]) / 4.0;
        default:            return close[index];
    }
}

//+------------------------------------------------------------------+
//| OnCalculate                                                      |
//+------------------------------------------------------------------+
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[])
{
    if(rates_total < 10) return(0);

    // Set all arrays as series
    ArraySetAsSeries(CandleOpen,  true);
    ArraySetAsSeries(CandleHigh,  true);
    ArraySetAsSeries(CandleLow,   true);
    ArraySetAsSeries(CandleClose, true);
    ArraySetAsSeries(CandleColor, true);

    ArraySetAsSeries(FilterBuffer, true);
    ArraySetAsSeries(ColorBuffer,  true);
    
    ArraySetAsSeries(ATR_Up11, true);
    ArraySetAsSeries(Color_Up11, true);
    ArraySetAsSeries(ATR_Up12, true);
    ArraySetAsSeries(Color_Up12, true);
    ArraySetAsSeries(ATR_Up13, true);
    ArraySetAsSeries(Color_Up13, true);
    ArraySetAsSeries(ATR_Up14, true);
    ArraySetAsSeries(Color_Up14, true);
    ArraySetAsSeries(ATR_Up15, true);
    ArraySetAsSeries(Color_Up15, true);
    
    ArraySetAsSeries(ATR_Dn11, true);
    ArraySetAsSeries(Color_Dn11, true);
    ArraySetAsSeries(ATR_Dn12, true);
    ArraySetAsSeries(Color_Dn12, true);
    ArraySetAsSeries(ATR_Dn13, true);
    ArraySetAsSeries(Color_Dn13, true);
    ArraySetAsSeries(ATR_Dn14, true);
    ArraySetAsSeries(Color_Dn14, true);
    ArraySetAsSeries(ATR_Dn15, true);
    ArraySetAsSeries(Color_Dn15, true);
    
    ArraySetAsSeries(FilterCalculations, true);
    ArraySetAsSeries(L0, true);
    ArraySetAsSeries(L1, true);
    ArraySetAsSeries(L2, true);
    ArraySetAsSeries(L3, true);
    ArraySetAsSeries(L4, true);
    ArraySetAsSeries(L5, true);
    
    ArraySetAsSeries(open,  true);
    ArraySetAsSeries(high,  true);
    ArraySetAsSeries(low,   true);
    ArraySetAsSeries(close, true);
    
    if(prev_calculated <= 0)
    {
       CreateToggleButton();
       ApplyPlotsStyle();
    }
    
    // Calculate coefficients
    double a1 = MathExp(-1.414 * M_PI / FilterPeriod);
    double c2 = 2.0 * a1 * MathCos(1.414 * M_PI / FilterPeriod);
    double c3 = -a1 * a1;
    double c1 = (1.0 + c2 - c3) / 4.0;
    double g1 = 1.0 - GammaValue;
    
    // Determine start index
    int start;
    if(prev_calculated == 0)
        start = rates_total - 1;
    else
        start = rates_total - prev_calculated + 1;
    
    if(start >= rates_total) start = rates_total - 1;
    if(start < 0) start = 0;

    for(int i = start; i >= 0; i--)
    {
        double src = GetSourcePrice(i, SourceInput, open, high, low, close);
        
        // Calculate L0 (Super-Smoother)
        if(rates_total - 1 - i < 4)
        {
            L0[i] = src;
        }
        else
        {
            double src1 = GetSourcePrice(i+1, SourceInput, open, high, low, close);
            double src2 = GetSourcePrice(i+2, SourceInput, open, high, low, close);
            
            // L0[i+1] and L0[i+2] are now MT5-managed buffers - stable history
            L0[i] = (1.0 - c1) * src + 
                    (2.0 * c1 - c2) * src1 - 
                    (c1 + c3) * src2 + 
                    c2 * L0[i+1] + 
                    c3 * L0[i+2];
        }
        
        // Calculate Laguerre cascade
        if(rates_total - 1 - i == 0)
        {
            L1[i] = L0[i];
            L2[i] = L0[i];
            L3[i] = L0[i];
            L4[i] = L0[i];
            L5[i] = L0[i];
        }
        else
        {
            L1[i] = g1 * L0[i+1] + GammaValue * L1[i+1];
            L2[i] = g1 * L1[i+1] + GammaValue * L2[i+1];
            L3[i] = g1 * L2[i+1] + GammaValue * L3[i+1];
            L4[i] = g1 * L3[i+1] + GammaValue * L4[i+1];
            L5[i] = g1 * L4[i+1] + GammaValue * L5[i+1];
        }
        
        // Final value
        double current_value = (L0[i] + 4.0 * L1[i] + 6.0 * L2[i] + 4.0 * L3[i] + L5[i]) / 16.0;
        
        FilterBuffer[i] = current_value;
        FilterCalculations[i] = current_value;
        
        // Determine color: 0 = Uptrend, 1 = Downtrend
        if(i == rates_total - 1)
        {
            ColorBuffer[i] = 0;
        }
        else
        {
            double previous_value = FilterBuffer[i+1];
            if(current_value > previous_value)
                ColorBuffer[i] = 0; // Uptrend
            else if(current_value < previous_value)
                ColorBuffer[i] = 1; // Downtrend
            else
                ColorBuffer[i] = ColorBuffer[i+1];
        }

        // Assign Candlestick values and color
        if(ColorCandles)
        {
            CandleOpen[i]  = open[i];
            CandleHigh[i]  = high[i];
            CandleLow[i]   = low[i];
            CandleClose[i] = close[i];
            CandleColor[i] = ColorBuffer[i];
        }
        else
        {
            CandleOpen[i]  = 0.0;
            CandleHigh[i]  = 0.0;
            CandleLow[i]   = 0.0;
            CandleClose[i] = 0.0;
            CandleColor[i] = 0;
        }
    }
    
    if(ShowATRBands)
    {
        CalculateATRBands(high, low, close, start, rates_total);
    }
    
    return(rates_total);
}
//+------------------------------------------------------------------+