Trade not closing when candle flips - error 4108 & 4051

JoeMSC.FX
11
JoeMSC.FX  

I'm fairly certain this is a ticket selection issue but I can't quite work out where I'm going wrong or how to fix it.

Basically, if my entry indicator changes direction it should close the open trade, it's not currently doing that... it just keeps it open and I get error 4108 or 4051 in the journal.

Can anyone help me identify the cause of the error and how to solve it?

*I've highlighted in yellow the portion of the code that should be closing orders.

#property copyright "MSC"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property show_inputs

#include <CustomFunctions.mqh>

int input Entry_Period = 14;
input int ATR_Period = 14;
input double ATR_TP_Multiple = 2.5;
input double ATR_BE_TP_Multiple = 1;
input double ATR_SL_Multiple = 1.5;
input double Risk = 1.00;
input int magicNB = 55555;
input double Spread_Multiple = 1; //% of SL as Pips for allowable spread

int OrderID;
double beTpPrice;  
datetime orderOpenTime;
datetime orderModifyTime;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   Print("Entryv2 Initiated");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Print("Entryv2 Deinitiated");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
 
   
   double preSignal = iCustom(Symbol(),Period(),"NNFX\\Entry",Entry_Period,0,2);
   double signal = iCustom(Symbol(),Period(),"NNFX\\Entry",Entry_Period,0,1);
   double ATR = iATR(Symbol(),Period(),ATR_Period,0);
   
   //Select order and identify its open time for if formula to prevent multiple orders on the same candle.
   if(OrderSelect(OrderID,SELECT_BY_TICKET)==true) orderOpenTime = OrderOpenTime(); 
   if(OrderSelect(OrderID,SELECT_BY_TICKET)==true) orderModifyTime = OrderCloseTime();
  
  
   if(orderModifyTime < Time[0])
   {
      if(CheckIfOpenOrdersByMagicNB(magicNB)==true)
      {
         if(OrderType() == 0 && Bid > beTpPrice)
         {
            OrderModify(OrderID,OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0);         
            OrderClose(OrderID,OrderLots()/2,Bid,0);
         }
         else if(OrderType() == 1 && Ask < beTpPrice)
         {
            OrderModify(OrderID,OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0);      
            OrderClose(OrderID,OrderLots()/2,Ask,0);
         }
      }
      else
      {    
               if(orderOpenTime < Time[0])
               {
                  if(!CheckIfOpenOrdersByMagicNB(magicNB)==true)
                  {
                     if(preSignal < 0 && signal > 0 && IsSpreadAcceptable(Spread_Multiple,ATR,ATR_SL_Multiple)==true) //Long
                     {
                        //Get Stop Loss & Take Profit Price
                        double stopLossPrice = NormalizeDouble(Ask-(ATR*ATR_SL_Multiple),Digits);
                        double takeProfitPrice = NormalizeDouble(Ask+(ATR*ATR_TP_Multiple),Digits);   
                        
                        //Setting Break Even & first Take Profit Price
                        beTpPrice = NormalizeDouble(Ask+(ATR*ATR_BE_TP_Multiple),Digits);
                        
                        //Send Buy Order & Print Any Errors
                        OrderID = OrderSend(NULL,OP_BUY,OptimalLotSize(Risk,Ask,stopLossPrice),Ask,0,stopLossPrice,takeProfitPrice,0,magicNB);
                        if(GetLastError() > 0) Print("Order Error: " + GetLastError()); 
                     }
                     else if (preSignal > 0 && signal < 0 && IsSpreadAcceptable(Spread_Multiple,ATR,ATR_SL_Multiple)==true) //Short
                     {
                        //Get Stop Loss & Take Profit Price
                        double stopLossPrice = NormalizeDouble(Bid+(ATR*ATR_SL_Multiple),Digits);
                        double takeProfitPrice = NormalizeDouble(Bid-(ATR*ATR_TP_Multiple),Digits);    
                     
                        //Setting Break Even & first Rake Profit Price
                        beTpPrice = NormalizeDouble(Bid-(ATR*ATR_BE_TP_Multiple),Digits);
                        
                        //Send Sell Order & Print Any Errors
                        OrderID = OrderSend(NULL,OP_SELL,OptimalLotSize(Risk,Bid,stopLossPrice),Bid,0,stopLossPrice,takeProfitPrice,0,magicNB);
                        if(GetLastError() > 0) Print("Order Error: " + GetLastError());
                     } 
                  } 
                  else
                  {
                     if(OrderType()==0 && preSignal > 0 && signal < 0)
                     {
                        double closePrice=NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),Digits);
                  
                        OrderClose(OrderID,OrderLots(),closePrice,0);
                     }
                     else if(OrderType()==1 && preSignal < 0 && signal > 0) 
                     {
                        double closePrice=NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),Digits);
                  
                        OrderClose(OrderID,OrderLots(),closePrice,0);
                     }
                  }
               }
               return; 
      }
   }
   return;
  }
//+------------------------------------------------------------------+

The Custom Function: 

bool CheckIfOpenOrdersByMagicNB(int magicNB)
{
   int openOrders = OrdersTotal();
   
   for(int i = 0; i < openOrders; i++)
   {
      if(OrderSelect(i,SELECT_BY_POS)==true)
      {
         if(OrderMagicNumber() == magicNB) 
         {
            return true;
         }  
      }
   }
   return false;
}