#property copyright "KK"
#property strict

#property description "RSI indicator in separate window with 5 switchable periods"
#property description "Periods: 14, 28, 50, 100, 200"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1

#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_width1 1
#property indicator_label1 "RSI"

#property indicator_level1 70
#property indicator_level2 50
#property indicator_level3 30
#property indicator_levelcolor clrBlack
#property indicator_levelstyle STYLE_DOT

input int RSI_Period_1 = 14;    // RSI Period 1
input int RSI_Period_2 = 28;    // RSI Period 2
input int RSI_Period_3 = 50;    // RSI Period 3
input int RSI_Period_4 = 100;   // RSI Period 4
input int RSI_Period_5 = 200;   // RSI Period 5
input int ButtonX = 1450;         // Button X Position
input int ButtonY = 20;         // Button Y Position

double RSIBuffer[];

int RSI_Periods[5];
int CurrentPeriodIndex = 0;
int CurrentRSI_Period;

string ButtonNames[5];

int RSI_Handles[5];

void OnInit()
{
    // Initialize RSI periods from inputs
    RSI_Periods[0] = RSI_Period_1;
    RSI_Periods[1] = RSI_Period_2;
    RSI_Periods[2] = RSI_Period_3;
    RSI_Periods[3] = RSI_Period_4;
    RSI_Periods[4] = RSI_Period_5;
    
    // Read saved period index from global variable
    string gvName = "RSI_Window_Period_Index_" + _Symbol + "_" + IntegerToString(_Period);
    if(GlobalVariableCheck(gvName))
    {
        CurrentPeriodIndex = (int)GlobalVariableGet(gvName);
        if(CurrentPeriodIndex < 0 || CurrentPeriodIndex > 4)
            CurrentPeriodIndex = 0;
    }
    
    CurrentRSI_Period = RSI_Periods[CurrentPeriodIndex];

    SetIndexBuffer(0, RSIBuffer, INDICATOR_DATA);
    
    ArraySetAsSeries(RSIBuffer, true);
    
    PlotIndexSetString(0, PLOT_LABEL, "RSI(" + IntegerToString(CurrentRSI_Period) + ")");
    
    IndicatorSetString(INDICATOR_SHORTNAME, "RSI (" + IntegerToString(CurrentRSI_Period) + ")");
    IndicatorSetInteger(INDICATOR_DIGITS, 2);
    
    // Create ALL RSI handles
    for(int i = 0; i < 5; i++)
    {
        RSI_Handles[i] = iRSI(NULL, 0, RSI_Periods[i], PRICE_CLOSE);
    }
    
    CreateButtons();
}

void OnDeinit(const int reason)
{
    DeleteButtons();
    
    for(int i = 0; i < 5; i++)
    {
        if(RSI_Handles[i] != INVALID_HANDLE) IndicatorRelease(RSI_Handles[i]);
    }
}

void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
    if(id == CHARTEVENT_OBJECT_CLICK)
    {
        for(int i = 0; i < 5; i++)
        {
            if(sparam == ButtonNames[i])
            {
                ObjectSetInteger(0, ButtonNames[i], OBJPROP_STATE, false);
                
                if(CurrentPeriodIndex == i) return;
                
                CurrentPeriodIndex = i;
                CurrentRSI_Period = RSI_Periods[i];
                
                string gvName = "RSI_Window_Period_Index_" + _Symbol + "_" + IntegerToString(_Period);
                GlobalVariableSet(gvName, CurrentPeriodIndex);
                
                UpdateButtons();
                UpdateIndicatorName();
                
                long chartID = ChartID();
                string symbol = ChartSymbol(chartID);
                ENUM_TIMEFRAMES period = ChartPeriod(chartID);
                
                ChartSetSymbolPeriod(chartID, symbol, period);
                
                return;
            }
        }
    }
}

void CreateButtons()
{
    int buttonWidth = 70;
    int buttonHeight = 25;
    int buttonSpacing = 5;
    
    int windowNumber = ChartWindowFind();
    
    for(int i = 0; i < 5; i++)
    {
        ButtonNames[i] = "RSI_Win_Button_" + IntegerToString(RSI_Periods[i]);
        
        if(ObjectCreate(0, ButtonNames[i], OBJ_BUTTON, windowNumber, 0, 0))
        {
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_XDISTANCE, ButtonX);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_YDISTANCE, ButtonY + (buttonHeight + buttonSpacing) * i);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_XSIZE, buttonWidth);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_YSIZE, buttonHeight);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_CORNER, CORNER_LEFT_UPPER);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_FONTSIZE, 9);
            ObjectSetString(0, ButtonNames[i], OBJPROP_TEXT, "RSI " + IntegerToString(RSI_Periods[i]));
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_COLOR, clrWhite);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_BGCOLOR, (i == CurrentPeriodIndex) ? clrGreen : clrDarkSlateGray);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_BORDER_COLOR, clrBlack);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_SELECTABLE, false);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_SELECTED, false);
        }
    }
}

void UpdateButtons()
{
    for(int i = 0; i < 5; i++)
    {
        if(ObjectFind(0, ButtonNames[i]) >= 0)
        {
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_BGCOLOR, (i == CurrentPeriodIndex) ? clrGreen : clrDarkSlateGray);
            ObjectSetInteger(0, ButtonNames[i], OBJPROP_STATE, false);
        }
    }
}

void DeleteButtons()
{
    for(int i = 0; i < 5; i++)
    {
        if(ObjectFind(0, ButtonNames[i]) >= 0)
        {
            ObjectDelete(0, ButtonNames[i]);
        }
    }
}

void UpdateIndicatorName()
{
    IndicatorSetString(INDICATOR_SHORTNAME, "RSI (" + IntegerToString(CurrentRSI_Period) + ")");
    PlotIndexSetString(0, PLOT_LABEL, "RSI(" + IntegerToString(CurrentRSI_Period) + ")");
}

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[])
{
    ArraySetAsSeries(time, true);
    
    int counted_bars = prev_calculated;
    if (counted_bars > 0) counted_bars--;
    int limit = rates_total - 1 - counted_bars;
    
    double TempRSIBuffer[];
    
    if(CopyBuffer(RSI_Handles[CurrentPeriodIndex], 0, 0, rates_total, TempRSIBuffer) <= 0)
        return 0;
    
    ArraySetAsSeries(TempRSIBuffer, true);
    
    for(int i = 0; i < limit; i++)
    {
        RSIBuffer[i] = TempRSIBuffer[i];
    }
    
    return rates_total;
}
//+------------------------------------------------------------------+