#include <Trade\Trade.mqh>          // Include the Trades Execution Library
#include <Trade\OrderInfo.mqh>      // Include the Orders Information Library
#include <Trade\PositionInfo.mqh>   // Include the Positions Information Library

// Input Parameters
input double LotSize = 0.1;                 // Lot size
input int OpenTimeMinutes = 540;            // Time to open position in minutes (e.g., 540 for 9:00 AM)
input int CloseTimeMinutes = 900;           // Time to close position in minutes (e.g., 900 for 3:00 PM)

// Instantiate Trade and Information Objects
CTrade         m_trade; 
COrderInfo     m_order; 
CPositionInfo  m_position; 

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   Print("Time-Based EA Initialized with OpenTime: ", OpenTimeMinutes, " minutes, CloseTime: ", CloseTimeMinutes, " minutes.");
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   Print("Time-Based EA Deinitialized.");
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   static bool positionOpened = false;
   datetime currentTime = TimeCurrent();

   // Extract current time in minutes since midnight
   MqlDateTime timeStruct;
   TimeToStruct(currentTime, timeStruct); // Break down datetime into components
   int currentMinutes = timeStruct.hour * 60 + timeStruct.min;

   // Open position at specified time
   if (currentMinutes >= OpenTimeMinutes && currentMinutes < CloseTimeMinutes && !positionOpened)
   {
      if (PositionsTotal() == 0) // Ensure no positions are already open
      {
         if (OpenLongPosition())
         {
            positionOpened = true;
            Print("Long position opened successfully at ", currentMinutes, " minutes.");
         }
         else
         {
            Print("Failed to open long position.");
         }
      }
   }

   // Close all orders and positions at specified time
   if (currentMinutes >= CloseTimeMinutes && positionOpened)
   {
      Close_all();
      positionOpened = false;
      Print("All orders and positions closed at ", currentMinutes, " minutes.");
   }
}

//+------------------------------------------------------------------+
//| Open Long Position                                               |
//+------------------------------------------------------------------+
bool OpenLongPosition()
{
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

   // Check minimum volume
   double minimumVolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double tradeVolume = MathMax(LotSize, minimumVolume);

   // Check margin requirements
   double requiredMargin = 0.0;
   if (!OrderCalcMargin(ORDER_TYPE_BUY, _Symbol, tradeVolume, ask, requiredMargin))
   {
      Print("Failed to calculate margin: ", GetLastError());
      return false;
   }

   if (AccountInfoDouble(ACCOUNT_FREEMARGIN) < requiredMargin)
   {
      Print("Not enough margin to open position.");
      return false;
   }

   MqlTradeRequest request;
   MqlTradeResult result;

   ZeroMemory(request);
   ZeroMemory(result);

   request.action = TRADE_ACTION_DEAL;
   request.symbol = _Symbol;
   request.volume = tradeVolume;
   request.price = ask;
   request.deviation = 10;
   request.type = ORDER_TYPE_BUY;

   if (OrderSend(request, result))
   {
      Print("Order opened successfully: ", result.order);
      return true;
   }
   else
   {
      Print("Error opening order: ", GetLastError());
      return false;
   }
}

//+------------------------------------------------------------------+
//| Close All Orders and Positions                                   |
//+------------------------------------------------------------------+
void Close_all()
{
   double totalProfit = 0.0; // Variable to track profit and loss
   
   // Close all positions
   for (int i = PositionsTotal() - 1; i >= 0; i--) 
   {
      if (m_position.SelectByIndex(i))  
      {
         double positionProfit = m_position.Profit();
         totalProfit += positionProfit; // Add the profit of the position
         
         if (m_trade.PositionClose(m_position.Ticket()))
         {
            Print("Position closed: ", m_position.Ticket(), " | Profit: ", positionProfit);
         }
         else
         {
            Print("Error closing position: ", GetLastError());
         }
         Sleep(100); // Relax for 100 ms
      }
   }

   // Delete all pending orders
   for (int i = OrdersTotal() - 1; i >= 0; i--) 
   {
      if (m_order.SelectByIndex(i))  
      {
         if (m_trade.OrderDelete(m_order.Ticket()))
         {
            Print("Order deleted: ", m_order.Ticket());
         }
         else
         {
            Print("Error deleting order: ", GetLastError());
         }
         Sleep(100); // Relax for 100 ms
      }
   }

   // Print total profit/loss for this session
   Print("Total Profit/Loss for this session: ", totalProfit);
}
