Is it possible to choose the last losing position? IN MQL4

 

Hi

With this code, I can close all the positions when, for example, (buy) when the profit is positive Now, when the close position is provided,

I want the positions (buy) to be closed. If the profit is positive, it will be closed, plus the last position that is at a loss.

I asked the professors for guidance

void closePostion(int number)
  {
   double totalProfit = totalProfit(number);

   if(totalProfit > 0)
     {
      for(int i = OrdersTotal() - 1; i >= 0; i--)
        {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderSymbol() == Symbol()&& OrderMagicNumber() == number && OrderType()<=OP_SELL)
            bool result=OrderClose(OrderTicket(), OrderLots(), Ask,slippage, Yellow);
            
            if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderSymbol() == Symbol() && OrderMagicNumber() == number && OrderType()<=OP_BUY)
            bool result=OrderClose(OrderTicket(),OrderLots(),Bid,slippage,Green);
           
           }
     }
  }

//+------------------------------------------------------------------+
double totalProfit(int number)
  {
   double totalProfit = 0;

   for(int i = OrdersTotal() - 1; i >= 0; i--)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderSymbol() == Symbol() && OrderMagicNumber() == number)
         totalProfit += (OrderProfit() + OrderCommission() + OrderSwap());
     }

   return totalProfit;
  }
  
//+------------------------------------------------------------------+
 
Naqibjan:

Hi

With this code, I can close all the positions when, for example, (buy) when the profit is positive Now, when the close position is provided,

I want the positions (buy) to be closed. If the profit is positive, it will be closed, plus the last position that is at a loss.

I asked the professors for guidance

My EA is closing the bunch of profitable order at once , how can I add the last order which is on loss , on this group

So I want the close the orders on the loss one by one

Sample
Buy 0.05: - $ 30
Buy 0.06: - $ 40
Buy 0.08: - $ 10
Buy 0.12: $ 15
Buy 0.15: $ 30
Buy 0.18: $ 50
$ 50 + $ 30 + $ 15 + - $ 10 = + $ 85


Thank you all friends.