Cooldown Activates Immediately instead of After Closing trade

 

Hello, I am working on an MQL5 trading bot, but I have an issue with the cooldown period. Right now, my bot activates cooldown immediately after opening a trade instead of waiting for the trade to close.

Here is my OnTick() function:

void OnTick() {
    static datetime lastDay = 0;
    datetime today = TimeCurrent() - (TimeCurrent() % 86400);

    if (today > lastDay) {
        lastDay = today;
        TotalDailyProfit = 0;
        TradesToday = 0;
        isCooldownPeriod = false;
    }
    
    if (isCooldownPeriod) {
        if (TimeCurrent() - cooldownStartTime >= 900) { 
            isCooldownPeriod = false;
            Print("Cooldown period ended.");
        } else {
            return;  
        }
    }

    if (TotalDailyProfit >= DailyProfitTarget || isCooldownPeriod) {
        return;
    }
    
    CloseTrades();
    
    if (PositionsTotal() > 0) return;
    
    if (AnalyzeMarket()) {
        Print("Bullish signal detected. Opening BUY trade.");
        OpenTrade(ORDER_TYPE_BUY);
    } else {
        Print("Bearish signal detected. Opening SELL trade.");
        OpenTrade(ORDER_TYPE_SELL);
    }
   isCooldownPeriod = true;
    cooldownStartTime = TimeCurrent();
    Print("Cooldown activated.");
   if (isCooldownPeriod) {
        if (TimeCurrent() - cooldownStartTime >= 900) { 
            isCooldownPeriod = false;
            Print("Cooldown period ended.");
        } else {
            return;  
        }
        }
        }
this is my close trade function;
void CloseTrades() {
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        ulong ticket = PositionGetTicket(i);
        if (PositionSelectByTicket(ticket)) {
            double profit = PositionGetDouble(POSITION_PROFIT);
            if (trade.PositionClose(ticket)) {
                TotalDailyProfit += profit;
                TradesToday--;
                Print("Closed trade ", ticket, " Profit: ", profit);
            } else {
                Print("Failed to close trade. Error: ", GetLastError());
            }
        }
    }
}
 

Where do you ever set lastDay?

If an interrupt occurs, suspending execution, the second TC call could be one greater, resulting in today being lastDay minus one.

    static datetime lastDay = 0;
    datetime today = TimeCurrent() - (TimeCurrent() % 86400);

    if (today > lastDay) {
Where do you ever set TotalDailyProfit?
If TDP exceeds your target, you return, never closing any trades.
    if (TotalDailyProfit >= DailyProfitTarget || isCooldownPeriod) {
        return;
    }
After all trades are closed (you call CloseTrades), you open a new trade. Therefor, there can be no “cool down.”
    if (AnalyzeMarket()) {
        Print("Bullish signal detected. Opening BUY trade.");
        OpenTrade(ORDER_TYPE_BUY);
    } else {
        Print("Bearish signal detected. Opening SELL trade.");
        OpenTrade(ORDER_TYPE_SELL);
    }