OrderClose error 4051

 
the errors

Hello everyone,

I have an issue with error 4051 as you can see in attached picture. Code for closing is:

      for(int p=0;p<OrdersTotal();p++)
      { 
      if(OrderSelect(p, SELECT_BY_POS, MODE_TRADES) && OrderType()==OP_BUY && trend_M5==false && ST_M5 > 70)
      ticket=OrderTicket();
        {
      objednavka = OrderClose(ticket, loty, Bid, 2, Blue);
      }

    }

Do someone know what is wrong with that?

Thanks for responses

 
for(int p=0;p<OrdersTotal();p++){ 

   if(OrderSelect(p, SELECT_BY_POS, MODE_TRADES) && OrderType()==OP_BUY && trend_M5==false && ST_M5 > 70) ticket=OrderTicket();

   objednavka = OrderClose(ticket, loty, Bid, 2, Blue);

}
  1. Don't paste code
    Play video
    Please edit your post.
    For large amounts of code, attach it.

  2. The above code is yours cleaned up. You only set ticket if you have a valid condition but always try to close every order.
  3. In the presence of multiple orders (one EA multiple charts, multiple EA's, manual trading) you must count down when closing/deleting/modifying in a position loop. Get in the habit of always counting down. Loops and Closing or Deleting Orders - MQL4 forum
  4. You try to close using the current chart's price, but no where do you check if the order is on your chart, created by your EA. See #3.
  5. Are you also sure that loty is never changing, thus matches the order? Why not use OrderLots() and be sure.