//+------------------------------------------------------------------+
//|                     Fixed EMA Line Indicator                     |
//+------------------------------------------------------------------+
#property indicator_chart_window

// Input parameters
input int EMAPeriod = 240;                 // EMA period (main EMA)
input int EMAPeriod2 = 55;                 // EMA period (second EMA)
input ENUM_MA_METHOD MA_Method = MODE_EMA; // Moving average method
input ENUM_APPLIED_PRICE AppliedPrice = PRICE_TYPICAL; // Applied price for EMA
input color LineColor = clrRed;            // Line color for main EMA
input color LineColor2 = clrBlue;          // Line color for second EMA
input ENUM_LINE_STYLE ObjectStyle = STYLE_DASHDOTDOT; // Line style for main EMA
input ENUM_LINE_STYLE ObjectStyle2 = STYLE_SOLID;     // Line style for second EMA
input ENUM_TIMEFRAMES MA_Timeframe = PERIOD_M30;      // Timeframe for EMA calculation

// Line names
string LineName = "Invalidation_Line";
string LineName2 = "Invalidation_Line_2";  // Second EMA line

// Variables to store the fixed EMA values
double FixedEMAValue = 0.0;
double FixedEMAValue2 = 0.0;               // For the second EMA

datetime lastResetTime = 0; // Time of the last reset
int lastTimeframe = -1;     // Track the last chart timeframe

//+------------------------------------------------------------------+
//| Initialization function                                          |
//+------------------------------------------------------------------+
int OnInit()
{
    ResetEMAs();
    Print("Indicator initialized successfully.");
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Deinitialization function                                        |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    DeleteAllObjects(); // Delete all objects when the indicator is removed
}

//+------------------------------------------------------------------+
//| Function to delete all objects created by the indicator          |
//+------------------------------------------------------------------+
void DeleteAllObjects()
{
    if (ObjectFind(0, LineName) != -1)
        ObjectDelete(0, LineName);

    if (ObjectFind(0, LineName2) != -1)
        ObjectDelete(0, LineName2);
}

//+------------------------------------------------------------------+
//| Reset EMA lines and manage their visibility                      |
//+------------------------------------------------------------------+
void ResetEMAs()
{
    Print("Current Timeframe: ", Period(), ", Selected Timeframe: ", MA_Timeframe);
    DeleteAllObjects(); // Delete existing objects

    // Only display lines if the current timeframe matches the selected timeframe
    if (Period() == MA_Timeframe)
    {
        CalculateEMAAtStartOfDay();

        datetime startTime = StringToTime(TimeToString(TimeGMT(), TIME_DATE) + " 00:00");
        datetime endTime = TimeGMT() + 8 * 3600; // Current time + 8 hours

        // Create the main trend line (EMA 240)
        if (!ObjectCreate(0, LineName, OBJ_TREND, 0, startTime, FixedEMAValue, endTime, FixedEMAValue))
        {
            Print("Failed to create object: ", LineName, " Error: ", GetLastError());
            return;
        }
        SetLineProperties(LineName, LineColor, ObjectStyle);

        // Create the second trend line (EMA 55)
        if (!ObjectCreate(0, LineName2, OBJ_TREND, 0, startTime, FixedEMAValue2, endTime, FixedEMAValue2))
        {
            Print("Failed to create object: ", LineName2, " Error: ", GetLastError());
            return;
        }
        SetLineProperties(LineName2, LineColor2, ObjectStyle2);
    }
    else
    {
        Print("Timeframe mismatch. Lines will not be drawn.");
    }
}

//+------------------------------------------------------------------+
//| Set line properties                                              |
//+------------------------------------------------------------------+
void SetLineProperties(string lineName, color lineColor, ENUM_LINE_STYLE lineStyle)
{
    ObjectSetInteger(0, lineName, OBJPROP_COLOR, lineColor);
    ObjectSetInteger(0, lineName, OBJPROP_STYLE, lineStyle);
    ObjectSetInteger(0, lineName, OBJPROP_WIDTH, 2); // Increase line thickness
    ObjectSetInteger(0, lineName, OBJPROP_RAY, false); // Line should not extend
    ObjectSetInteger(0, lineName, OBJPROP_BACK, true); // Line drawn behind the candles
}

//+------------------------------------------------------------------+
//| Calculate EMA at the start of the day                            |
//+------------------------------------------------------------------+
void CalculateEMAAtStartOfDay()
{
    datetime currentTime = TimeGMT();
    datetime startOfDay = StringToTime(TimeToString(currentTime, TIME_DATE) + " 00:00");

    int startIndex = iBarShift(NULL, MA_Timeframe, startOfDay);
    if (startIndex < 0)
    {
        Print("Failed to find start of day bar.");
        return;
    }

    FixedEMAValue = iMA(NULL, MA_Timeframe, EMAPeriod, 0, MA_Method, AppliedPrice, startIndex);
    FixedEMAValue2 = iMA(NULL, MA_Timeframe, EMAPeriod2, 0, MA_Method, AppliedPrice, startIndex);

    // Check if EMA values are valid
    if (FixedEMAValue == 0.0 || FixedEMAValue2 == 0.0)
    {
        Print("Invalid EMA values. Check historical data.");
        return;
    }
}

//+------------------------------------------------------------------+
//| Periodically check if EMAs need resetting                        |
//+------------------------------------------------------------------+
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[])
{
    // Check if the timeframe has changed
    if (lastTimeframe != Period() && Period() == MA_Timeframe)
    {
        lastTimeframe = Period();
        ResetEMAs(); // Reset lines for the new timeframe
    }

    // Check if it's a new day
    datetime currentDay = StringToTime(TimeToString(TimeGMT(), TIME_DATE) + " 00:00");
    if (lastResetTime < currentDay)
    {
        lastResetTime = TimeGMT();
        ResetEMAs();
    }

    return(rates_total);
}
//+------------------------------------------------------------------+