My EA is not working properly on MT5

 
My EA did not properly implement the sell limit condition that I was requesting. At "// Check the conditions for a sell signa"l and "// Check the conditions for a sell signal" seem to be logically correct.
Can you check and point out errors for me? Thank you !
input double RiskUSD = 10.0; // USD risked per trade
input double TakeProfitFactor = 2.0; // Take profit distance factor
input int MaxWaitingBars = 8; // Maximum number of bars to wait before canceling the order

double high[]; // Array containing the highest price of bars
double close[]; // Array containing the closing price of bars
double open[]; // Array containing the opening price of bars
double low[]; // Array containing the lowest price of bars
ulong localTicket   = ULONG_MAX; // Global variable for the order localTicket 

datetime orderTime; // Time when the order was placed

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Check if the current timeframe is 15 minutes
    if(Period() != PERIOD_M15 )
    {
        Print("This EA can only be applied on a 15-minute timeframe.");
        return(INIT_FAILED);
    }
    

    string symbol = _Symbol;
    if(symbol != "EURUSD" && symbol != "GBPUSD" && symbol != "XAUUSD" &&
       symbol != "EURJPY" && symbol != "GBPJPY" && symbol != "USDCHF" &&
       symbol != "EURCHF" && symbol != "GBPCHF" && symbol != "BTCUSD")
    {
        Print("This EA can only be applied on specified symbols.");
        return(INIT_FAILED);
    }
    
        return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    // Define and populate new local arrays
    int barsNeeded = 5; // Number of bars needed
    double localHigh[], localClose[], localLow[], localOpen[]; 
    if(CopyHigh(_Symbol, _Period, 0, barsNeeded, localHigh) < barsNeeded ||
       CopyClose(_Symbol, _Period, 0, barsNeeded, localClose) < barsNeeded ||
       CopyLow(_Symbol, _Period, 0, barsNeeded, localLow) < barsNeeded||
       CopyOpen(_Symbol, _Period, 0, barsNeeded, localOpen) < barsNeeded)
    {
        Print("Error: Not enough data to populate arrays.");
        return; // Exit if there's not enough data
    }

     // Check for sell conditions
     if(localTicket == ULONG_MAX && CheckSellConditions()) {
        // Define the entry, stop loss, and take profit prices
        double entryPrice = (localHigh[0] + localClose[0]) / 2; 
        double stopLossPrice = localHigh[4]; // Stop loss at the high of candle 5
        double stopLossDistance = stopLossPrice - entryPrice;
        double takeProfitPrice = entryPrice - (2 * stopLossDistance); 
        double lotSize = CalculateLotSize(3, stopLossDistance); 

    
        if(lotSize > 0)
        {
            MqlTradeRequest request={};
            MqlTradeResult  result={};

            request.action = TRADE_ACTION_PENDING; 
            request.symbol = _Symbol; 
            request.volume = lotSize; 
            request.type = ORDER_TYPE_SELL_LIMIT; 
            request.price = entryPrice; 
            request.sl = stopLossPrice; 
            request.tp = takeProfitPrice; 
            request.comment = "Sell Limit"; 
            request.magic = 0; 
            request.type_filling = ORDER_FILLING_IOC;

            // Send trade request
            if(trade.OrderSend(request, result))
            { 
                localTicket  = result.order; 
                orderTime = TimeCurrent();
                Print("Sell limit order placed successfully with localTicket : ", localTicket );
            }
            else
            {
                Print("Error placing sell limit order: ", result.comment);
            }
        }
    }

    // Check if the limit order needs to be canceled
    if(localTicket  >= 0 && TimeCurrent() - orderTime > MaxWaitingBars * PeriodSeconds())
    {
        if(PositionSelectByTicket (localTicket ))
        {
            if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                bool result = trade.PositionClose(localTicket );
                if(result)
                {
                    Print("Sell limit order ", localTicket , " has been canceled due to timeout.");
                    localTicket  = ULONG_MAX;
                }
                else
                {
                    Print("Error canceling sell limit order: ", GetLastError());
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Check Sell Conditions                                            |
//+------------------------------------------------------------------+
bool CheckSellConditions()
{
    int barsToCopy = 5; // Number of bars needed, including index 4
    double openPrices[], closePrices[], lowPrices[], highPrices[];

    // Copy the high, open, low, and close prices
    if(CopyHigh(_Symbol, _Period, 0, barsToCopy, highPrices) < barsToCopy)
    {
        Print("Error copying high prices: ", GetLastError());
        return false;
    }
    if(CopyOpen(_Symbol, _Period, 0, barsToCopy, openPrices) < barsToCopy)
    {
        Print("Error copying open prices: ", GetLastError());
        return false;
    }
    if(CopyClose(_Symbol, _Period, 0, barsToCopy, closePrices) < barsToCopy)
    {
        Print("Error copying close prices: ", GetLastError());
        return false;
    }
    if(CopyLow(_Symbol, _Period, 0, barsToCopy, lowPrices) < barsToCopy)
    {
        Print("Error copying low prices: ", GetLastError());
        return false;
    }

    // Check the conditions for a sell signal
   if(closePrices[4] > openPrices[4] && closePrices[3] < openPrices[3]  
      && closePrices[1] > openPrices[1] && highPrices[1] < highPrices[4] 
      && closePrices[0] < openPrices[0] && lowPrices[0] < lowPrices[4] 
      && lowPrices[0] < lowPrices[3] && lowPrices[0] < lowPrices[1] && highPrices[0] < highPrices[4])
    {
        return true;
    }

    return false;
}



//+----------CalculateLotSize--------------------------------------------------------+
//| Calculate the lot size                                           |
//+------------------------------------------------------------------+
double CalculateLotSize(double maxRiskUSD, double StopLossDistanceInPips)
{
    // Check for valid stop loss distance
    if(StopLossDistanceInPips <= 0)
    {
        Print("StopLossDistance must be greater than 0");
        return 0;
    }
    
    // Retrieve symbol properties
    double tickValue, pipValue, lotStep, minLotSize, maxLotSize;
    if(!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE, tickValue) ||
       !SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE, pipValue) ||
       !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP, lotStep) ||
       !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN, minLotSize) ||
       !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX, maxLotSize))
    {
        Print("Error getting symbol info.");
        return 0;
    }
    
    // Calculate the pip value per lot
    double pipValuePerLot = tickValue / pipValue;
    
    // Calculate the required lot size
    double lotSize = maxRiskUSD / (StopLossDistanceInPips * pipValuePerLot);
    
    // Normalize the lot size to the nearest lot step
    lotSize = MathFloor(lotSize / lotStep) * lotStep;
    
    // Ensure the lot size is within the min and max range
    lotSize = MathMax(minLotSize, MathMin(lotSize, maxLotSize));
    
    // Round to the nearest lot step
    lotSize = NormalizeDouble(lotSize, _Digits);
    
    return lotSize;
}

 
double entryPrice = (localHigh[0] + localClose[0]) / 2;

it looks like your entry price calculation is wrong. may be you need to calculate from candle 1 not 0!

I do not know logic behind your strategy but current high and close for JUST opened candle are same values. I mean, in first tick of current candle high=low=open=close. 

you can not set a pending order for current price specially if there are limits like Stop Level or Freeze Level.

 

You may check this. You cannot open a pending order too close to current price.

if(entry>Bid+SYMBOL_TRADE_FREEZE_LEVEL*_Point)
   trade.SellLimit(...);