
//+------------------------------------------------------------------+
//|                                                     FractalEA.mq5|
//|                      Generated by ChatGPT                        |
//+------------------------------------------------------------------+
#property strict

// Input parameters for fractal detection and risk management
input int FractalBars = 2;              // Adjustable number of bars/candles for fractal
input int MaxTradesPerDay = 5;          // Maximum trades allowed per day
input double MaxLotPerDay = 1.0;        // Maximum lot size allowed per day
input int TradeStartHour = 9;           // Start hour (in server time) for trade execution
input int TradeEndHour = 17;            // End hour (in server time) for trade execution
input double MaxDrawdownPercent = 5;    // Max allowable drawdown percentage for the day
input double LotSize = 0.1;             // Lot size for trades
input int Slippage = 10;                // Maximum slippage allowed for trade execution
input int MagicNumber = 123456;         // Magic number to identify trades by this EA

// Input parameters for visualization
input color SupportLineColor = Lime;    // Support line color
input color ResistanceLineColor = Red;  // Resistance line color
input color UptrendLineColor = Green;   // Uptrend line color
input color DowntrendLineColor = Orange;// Downtrend line color
input int LineWidth = 2;                // Line width for trend lines

// Global variables to track trades and risk
int TradesOpenedToday = 0;              // Track the number of trades opened today
double TotalLotsToday = 0.0;            // Track the total lots opened today
double DailyHighBalance;                // Track the highest account balance during the day
double FractalUp, FractalDown;          // Store fractal levels (high/low)
int FractalUpBar, FractalDownBar;       // Store the fractal bar numbers
int LastFractalUpBar = 0, LastFractalDownBar = 0; // Track the last fractal bar numbers

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Initialize variables
   DailyHighBalance = AccountInfoDouble(ACCOUNT_BALANCE);

   // Display EA status message on the chart
   Comment("EA is active. Monitoring for signals.");

   // Return success
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   // Reset trade counters at the start of a new day
   ResetDailyTradeLimits();

   // Check if within trading time window and if max drawdown is not exceeded
   if(!IsWithinTradeWindow() || CheckDrawdownLimit())
     {
      Comment("Trading paused. Outside trading hours or drawdown limit reached.");
      return;
     }

   // Redraw fractals and trendlines on the chart
   RedrawFractals();

   // Example: If fractal conditions are met, open a trade
   // Check fractal breakouts for buy or sell signals
   CheckFractalBreakout();
  }
//+------------------------------------------------------------------+
//| Function to check for fractal breakouts and open trades          |
//+------------------------------------------------------------------+
void CheckFractalBreakout()
  {
   // Check for breakout above fractal high
   if(FractalUp != 0 && iClose(NULL, 0, 0) > FractalUp)
     {
      OpenTrade(0, LotSize); // Buy signal
      Comment("Fractal Breakout: Buy order executed.");
     }

   // Check for breakout below fractal low
   if(FractalDown != 0 && iClose(NULL, 0, 0) < FractalDown)
     {
      OpenTrade(1, LotSize); // Sell signal
      Comment("Fractal Breakout: Sell order executed.");
     }
  }
//+------------------------------------------------------------------+
//| Function to open a trade                                         |
//+------------------------------------------------------------------+
void OpenTrade(int tradeType, double lotSize)
  {
   // Check if daily trade and lot limits are reached
   if(TradesOpenedToday >= MaxTradesPerDay || TotalLotsToday + lotSize > MaxLotPerDay)
     {
      Comment("Trade not executed. Daily trade or lot limit reached.");
      return;
     }

   int ticket;
   if(tradeType == 0) // Buy
     {
      ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, Slippage, 0, 0, "Buy", MagicNumber, 0, Green);
     }
   else // Sell
     {
      ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, Slippage, 0, 0, "Sell", MagicNumber, 0, Red);
     }

   // If trade is successful, update trade count and lot size
   if(ticket > 0)
     {
      TradesOpenedToday++;
      TotalLotsToday += lotSize;
      Comment("Trade opened. Total trades today: ", TradesOpenedToday, ", Total lots: ", TotalLotsToday);
     }
   else
     {
      Print("Error opening trade. Error code: ", GetLastError());
     }
  }
//+------------------------------------------------------------------+
//| Function to redraw fractals and trend lines on the chart         |
//+------------------------------------------------------------------+
void RedrawFractals()
  {
   // Clear previous fractal objects
   ObjectsDeleteAll(0, 0);

   // Find most recent fractals (William's method)
   FractalUp = GetWilliamFractal(true);   // True for upper fractal (resistance)
   FractalDown = GetWilliamFractal(false);// False for lower fractal (support)

   // Draw support and resistance lines
   DrawSupportResistance();

   // Draw trendlines connecting the fractals
   DrawFractalTrendLines();

   // Display status on chart
   Comment("EA Active | Fractal Up: ", FractalUp, " | Fractal Down: ", FractalDown);
  }
//+------------------------------------------------------------------+
//| Get William's fractal (upper or lower)                           |
//+------------------------------------------------------------------+
double GetWilliamFractal(bool isUpper)
  {
   for(int i = FractalBars + 2; i < Bars; i++)
     {
      // Check for upper fractal (swing high)
      if(isUpper && IsFractalHigh(i))
        {
         FractalUpBar = i;
         return iHigh(NULL, 0, i);
        }

      // Check for lower fractal (swing low)
      if(!isUpper && IsFractalLow(i))
        {
         FractalDownBar = i;
         return iLow(NULL, 0, i);
        }
     }
   return 0; // No fractal found
  }
//+------------------------------------------------------------------+
//| Check if a bar is a fractal high (William's method)              |
//+------------------------------------------------------------------+
bool IsFractalHigh(int barIndex)
  {
   return (iHigh(NULL, 0, barIndex) > iHigh(NULL, 0, barIndex + 1) &&
           iHigh(NULL, 0, barIndex) > iHigh(NULL, 0, barIndex + 2) &&
           iHigh(NULL, 0, barIndex) > iHigh(NULL, 0, barIndex - 1) &&
           iHigh(NULL, 0, barIndex) > iHigh(NULL, 0, barIndex - 2));
  }
//+------------------------------------------------------------------+
//| Check if a bar is a fractal low (William's method)               |
//+------------------------------------------------------------------+
bool IsFractalLow(int barIndex)
  {
   return (iLow(NULL, 0, barIndex) < iLow(NULL, 0, barIndex + 1) &&
           iLow(NULL, 0, barIndex) < iLow(NULL, 0, barIndex + 2) &&
           iLow(NULL, 0, barIndex) < iLow(NULL, 0, barIndex - 1) &&
           iLow(NULL, 0, barIndex) < iLow(NULL, 0, barIndex - 2));
  }
//+------------------------------------------------------------------+
//| Draw support and resistance lines based on recent fractals       |
//+------------------------------------------------------------------+
void DrawSupportResistance()
  {
   if(FractalUp != 0)
     {
      // Draw resistance line
      string resistanceLine = "FractalResistance";
      ObjectCreate(0, resistanceLine, OBJ_HLINE, 0, Time[FractalUpBar], FractalUp);
      ObjectSetInteger(0, resistanceLine, OBJPROP_COLOR, ResistanceLineColor);
      ObjectSetInteger(0, resistanceLine,



