//+------------------------------------------------------------------+
//|                   CloseIndividualPosition@Profit_Loss_Script.mq4 |
//|                        Copyright 2022, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property show_inputs

input double              MaxAccountLossInMoney                   = 500;
input double              MaxAccountProfitInMoney                 = 1000;
//+------------------------------------------------------------------+
void OnStart()
  {
//---
           OrdersCloseAll();
   
  }
//+------------------------------------------------------------------+
void OrdersCloseAll()
   {
  int total = OrdersTotal();
  bool result = false;
  for(int cnt=total-1;cnt>=0;cnt--)
   {
    if(OrderSelect(cnt, SELECT_BY_POS,MODE_TRADES))
     {
      //Close opened long positions
      if(OrderType()==OP_BUY&&
         (AccountProfit()>=MaxAccountProfitInMoney||
          AccountProfit()<=-MaxAccountLossInMoney))
       result = OrderClose( OrderTicket(), OrderLots(), Bid, 0, clrNONE );
      
      //Close opened short positions
      if(OrderType()==OP_SELL&&
         (AccountProfit()>=MaxAccountProfitInMoney||
          AccountProfit()<=-MaxAccountLossInMoney))
       result = OrderClose( OrderTicket(), OrderLots(), Ask, 0, clrNONE );
     }
    
    if(result == false)
     {
      Print(" OrdersCloseAll ", OrderTicket(), " failed - error code: ", GetLastError()); 
      Sleep(500);
     }
     else
     {
      Print(" OrdersCloseAll ", OrderTicket(), " success.");
     }  
   }
   
   }
//+------------------------------------------------------------------+
