# Stucked

1405

Have this code to close first ticket when orderstotal is higher than 1:

```         if(OrdersTotal()>1&&OrderTicket()==OrderTicket()){
if(!OrderClose(OrderTicket(),OrderLots(),ClosePrice,3,clrGold)){
RefreshRates();
return;
}```

As the loop is forward counter it closes first order with no mistake, this way I close first open at reversal signal.

Now trying to do the same but when BuyOrders==1&&SellOrders==1.

```         if(BuyOrders==1&&SellOrders==1){
if(!OrderClose(OrderTicket(),OrderLots(),ClosePrice,3,clrGold)){
RefreshRates();
return;
}```

It's closing last order continuously. I'm trying to do this for if it's more than 1 order in some direction then I want it to close at profit by averaging.

So the main problem is why it's closing last open this wayand don't actually know. Any idea?
247

You will have to find the first or the last order in the symbol & then close it if you have more than one order in the same symbol.

Here is my example code for you:

```int i = 0, totalOrders = OrdersTotal(), myOrders = 0;
int firstOrderTicket, lastOrderTicket;
for(; i < totalOrders; i++){
if(OrderSymbol() == Symbol()){
firstOrderTicket = OrderTicket();
lastOrderTicket = OrderTicket();
myOrders ++;
}
}
}
if(myOrders == 0){
return;//Nothing to do next if have no order.
}
if(myOrders > 1){
for(i = 0; i < totalOrders; i++){
if(OrderSymbol() == Symbol()){
if(OrderTicket() > lastOrderTicket){
lastOrderTicket = OrderTicket();
}
if(OrderTicket() < firstOrderTicket){
firstOrderTicket = OrderTicket();
}
}
}
}
}
//Now you have clearly first order & last order of that symbol. You can do anything as you want.
//..```
247

Due you may have both buying & selling positions on the symbol, so you can add more condition in the for loop to define everything more clearly.

```int firstSellOrderTicket, lastSellOrderTicket;//Define selling order ticket.
if(OrderSymbol() == Symbol() && OrderType() == OP_SELL)//Add more condition in if statement.```
Moderator
20423

David Diez:

Have this code to close first ticket when orderstotal is higher than 1:

As the loop is forward counter it closes first order with no mistake, this way I close first open at reversal signal.

Now trying to do the same but when BuyOrders==1&&SellOrders==1.

It's closing last order continuously. I'm trying to do this for if it's more than 1 order in some direction then I want it to close at profit by averaging.

So the main problem is why it's closing last open this wayand don't actually know. Any idea?

You are not selecting an order in either of your codes so your codes will close whichever was the last order selected.