Correcting code

i want it to “n” bar appears you sell and buy at the same time i have a very bad knowledge of coding please help thank you

// Define input parameters
extern int n = 5; // The number of bars to wait before opening a new trade
extern int stopLossPips = 10; // Stop loss in pips
extern int takeProfitPips = 12; // Take profit in pips

// Define global variables
int lastTradeBar = 0;

// Define trade direction enumeration
enum TradeDirection {
Buy,
Sell,
None
};

// Custom function to check if the current time is within the specified hours range
bool IsWithinTradingHours() {
int currentHour = Hour();
return (currentHour >= 4 && currentHour <= 18);
}

// Custom function to open a trade with the given direction (buy/sell)
void OpenTrade(TradeDirection direction) {
double openPrice = direction == Buy ? Ask : Bid;
double stopLossPrice = direction == Buy ? openPrice - stopLossPips * Point : openPrice + stopLossPips * Point;
double takeProfitPrice = direction == Buy ? openPrice + takeProfitPips * Point : openPrice - takeProfitPips * Point;

if (direction != None) {
    // Check if there are no open trades before opening a new one
    if (OrderSend(Symbol(), direction, 1.0, openPrice, 3, stopLossPrice, takeProfitPrice) > 0) {
        lastTradeBar = iBarShift(NULL, 0, TimeCurrent());
    }
}

}

// Custom function to close all open trades
void CloseAllTrades() {
for (int i = OrdersTotal() - 1; i >= 0; i–) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
OrderClose(OrderTicket(), OrderLots(), Bid, 3);
}
}
}

// Expert Advisor Start function
void OnStart() {
while (!IsTradeAllowed()) {
Sleep(60000); // Wait for the next minute if trading is not allowed yet
}

while (true) {
    // Check if we are within trading hours
    if (IsWithinTradingHours()) {
        int currentBar = iBarShift(NULL, 0, TimeCurrent());
        
        // Check if enough bars have passed since the last trade
        if (currentBar - lastTradeBar >= n) {
            // Close all open trades before opening new ones
            CloseAllTrades();
            
            // Open new trades
            OpenTrade(Buy);
            OpenTrade(Sell);
        }
    }
    
    Sleep(1000); // Wait for 1 second before checking again
}

}

Why have you got the check inside an infinite loop? The timer and tick functions are what you want to do that in. If you want to do something every nth candle, then a timer works ok, but you need to synchronise the timer with the candles, or run it more often so you get the entry close to the right time.

I can’t see when your code is even running. OnStart is for initializing things, it only runs once on startup.

Is there any method for the code to be formatted here?

Like the code in the picture below: