//+------------------------------------------------------------------+
//|                     Fixed EMA Line Indicator                     |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1 clrRed        // Color for main EMA
#property indicator_color2 clrBlue       // Color for second EMA

// 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 ENUM_TIMEFRAMES MA_Timeframe = PERIOD_M30; // Timeframe for EMA calculation

// Buffers for EMA values
double EMA1Buffer[];
double EMA2Buffer[];

// Line names
string LineName = "FixedTrendLine";
string LineName2 = "FixedTrendLine2"; // 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

//+------------------------------------------------------------------+
//| Initialization function                                          |
//+------------------------------------------------------------------+
int OnInit()
{
    // Indicator buffers
    SetIndexBuffer(0, EMA1Buffer);
    SetIndexBuffer(1, EMA2Buffer);

    // Check if the current chart timeframe matches the MA_Timeframe
    if (Period() != MA_Timeframe)
    {
        Print("This indicator can only be used on the ", EnumToString(MA_Timeframe), " timeframe.");
        return (INIT_FAILED);
    }

    // Perform the initial EMA calculation and line creation
    ResetEMAs();
    return (INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Deinitialization function                                        |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Delete both lines when the indicator is removed
    ObjectDelete(0, LineName);
    ObjectDelete(0, LineName2);
}

//+------------------------------------------------------------------+
//| Calculate EMA values and update trend lines                      |
//+------------------------------------------------------------------+
void ResetEMAs()
{
    // Delete the existing lines first to avoid duplicates
    ObjectDelete(0, LineName);
    ObjectDelete(0,LineName2);

    // Calculate the EMA values at the start of the day
    CalculateEMAAtStartOfDay();

    // Define the time range for the trend lines
    datetime startTime = StringToTime(TimeToString(TimeCurrent(), TIME_DATE) + " 00:00");
    datetime endTime = TimeCurrent() + 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("Error creating trend line: ", GetLastError());
    }

    // Create the second trend line (EMA 55)
    if (!ObjectCreate(0, LineName2, OBJ_TREND, 0, startTime, FixedEMAValue2, endTime, FixedEMAValue2))
    {
        Print("Error creating second trend line: ", GetLastError());
    }

    // Store the time when the reset occurred
    lastResetTime = TimeCurrent();
}

//+------------------------------------------------------------------+
//| Calculate EMA at the start of the day                            |
//+------------------------------------------------------------------+
void CalculateEMAAtStartOfDay()
{
    // Get the current date and time
    datetime currentTime = TimeCurrent();

    // Find the start of the day for the current date
    datetime startOfDay = StringToTime(TimeToString(currentTime, TIME_DATE) + " 00:00");

    // Get the index of the first bar of the day
    int startIndex = iBarShift(_Symbol, MA_Timeframe, startOfDay);
    if (startIndex >= 0)
    {
        // Calculate the EMAs
        for (int i = startIndex; i < startIndex + EMAPeriod + 1; i++) // Ensure we cover the range for EMA calculation
        {
            EMA1Buffer[i] = iMA(_Symbol, MA_Timeframe, EMAPeriod, 0, MA_Method, AppliedPrice);
            EMA2Buffer[i] = iMA(_Symbol, MA_Timeframe, EMAPeriod2, 0, MA_Method, AppliedPrice);
        }
        
        // Store the latest EMA values
        FixedEMAValue = EMA1Buffer[startIndex];  // Current EMA 240
        FixedEMAValue2 = EMA2Buffer[startIndex]; // Current EMA 55
        
        Print("EMA 240 at the start of the day is: ", FixedEMAValue);
        Print("EMA 55 at the start of the day is: ", FixedEMAValue2);
    }
    else
    {
        Print("Start of the day not found.");
    }
}

//+------------------------------------------------------------------+
//| This function checks if a reset is required                      |
//+------------------------------------------------------------------+
void CheckForReset()
{
    // Get the current date
    datetime currentDay = StringToTime(TimeToString(TimeCurrent(), TIME_DATE) + " 00:00");

    // If it's a new day, reset the EMAs and the trend lines
    if (lastResetTime < currentDay)
    {
        ResetEMAs();
    }
}

//+------------------------------------------------------------------+
//| Called periodically to check and reset the EMAs if necessary     |
//+------------------------------------------------------------------+
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[])
{
    // Periodically check if a reset is needed
    CheckForReset();

    return (rates_total);
}
//+------------------------------------------------------------------+
