Hedge

 
Im trying to make a hedge but it wont perform as I want. If I have several orders open in the same position (Have already defined openorders as that), i am defining it that my EA has failed. So then I want to check the trend by using MA on 320 on 15 min charts if its either an BUY or SELL position/trend. If the trend is the other way I want to make an hedgebuy/sell, and then sell it when the trend is changing direction. Also I dont want to make new buys in the wrong direction so I have HedgeActive=0 in my other code. Can you see what it is i am missing here? Its not closing correctly


  void CloseHedge(int ticket, color theColor)
{
        if (OrderSelect(ticket,SELECT_BY_TICKET) && OrderMagicNumber()==MagicNrHedge)
        {                       
                if (!OrderClose(ticket,OrderLots(),(OrderType()==OP_BUY)?Bid:Ask,3,theColor))
                   Print ("OrderClose last error ", GetLastError());
    }
        
        return;
}

if(OpenOrders()==0)
{
double HedgeActive=0;
}

//HEDGE
int ticket = 0;
  
   int total=OrdersTotal();
   int h = 0;
   for(h = total; h >=0; h--)
   {
      if(OrderSelect(h,SELECT_BY_POS) && OrderSymbol()==Symbol() && EnableHedge==true && OpenOrders()>=3)
      {
        if(OrderType()==OP_BUY && Close[0] < MA(0))
        { 
          ticket = OrderSend(Symbol(),OP_SELL,(OpenOrders()*Lots),Bid,3,0,0,"Reverse Sell",MagicNrHedge,0,clrNONE);
            HedgeActive=1;
            ticketHedge=OrderTicket();
        }
      if(OrderType()==OP_SELL && Close[0] > MA(0))
      {
         ticket = OrderSend(Symbol(),OP_BUY,(OpenOrders()*Lots),Ask,3,0,0,"Reverse Buy",MagicNrHedge,0,clrNONE);
            HedgeActive=2;
            ticketHedge=OrderTicket();
      }
     }
    }    


//CLOSING HEDGE
if(OrderSymbol() == Symbol() && OrderMagicNumber()==MagicNrHedge && HedgeActive==2 && Close[0] < MA(0))
{
CloseHedge(ticketHedge,Yellow);
HedgeActive=0;
}

if(OrderSymbol() == Symbol() && OrderMagicNumber()==MagicNrHedge && HedgeActive==1 && Close[0] > MA(0))
{
CloseHedge(ticketHedge,Yellow);
HedgeActive=0;
}