Problem with include trailingstop in my code

 

Hello,

I hope you are well.



I have problem with  my code.


I have more trades with profit:
0.20
-0.50
1.20
-30
35.20


I need to close all trades with losses trades. In my case: -0.50 and -30

and I need to use trailing stop with currently profit trades: 0.20, 1.20 and 35.20


My code close all loses trades but I need all my trades if is in profit to add TrailingStop


Thanks.



void CloseAllMarketOrders()

{
   int retryCount = 0;
   
   for(int Counter = 0; Counter <= OrdersTotal()-1; Counter++)
   {
      if(OrderSelect(Counter,SELECT_BY_POS))
      {
         if(OrderMagicNumber() == MagicNumber && OrderSymbol() == _Symbol && (OrderType() == OP_BUY || OrderType() == OP_SELL))
         {
            // Close Order
            int CloseTicket = OrderTicket();
            double CloseLots = OrderLots();
            while(IsTradeContextBusy()) Sleep(10);
            
             if(OrderProfit()<0)
             {
            
            RefreshRates();            
            double ClosePrice = MarketInfo(_Symbol,MODE_BID);
            if(OrderType() == OP_SELL) ClosePrice = MarketInfo(_Symbol, MODE_ASK);

            bool Closed = OrderClose(CloseTicket,CloseLots,ClosePrice,Slippage,Red);
            // Error Handling
            if(Closed == false)
            {
               int ErrorCode = GetLastError();
               string ErrAlert = StringConcatenate("Close All Market Orders - Error ",ErrorCode,".");
               Alert(ErrAlert);
               Print(ErrAlert);
            } else Counter--;
            }
         }
         
         if (OrderProfit()>0)
         {
             int TrailingStop=50;
         
           if(TrailingStop>0)
              for(int order = 0; order <= OrdersTotal() - 1; order++)
   {
           
    
     OrderSelect(order,SELECT_BY_TICKET);
      if(Bid-OrderOpenPrice()>Point*TrailingStop)
      {
      if(OrderStopLoss()<Bid-Point*TrailingStop)
           {
           bool res=OrderModify(order,OrderOpenPrice(),NormalizeDouble(Bid-Point*TrailingStop,Digits),OrderTakeProfit(),0,Blue);
           if(!res)
               Print("Error in OrderModify. Error code=",GetLastError());
            else
               Print("Order modified successfully.");
           
           }
      
      }
     
     }
     
   
         
         }
         
         
      }  
    }
}
 
  1. Why did you post your MT4 question in the MT5 EA section instead of the MQL4 section, (bottom of the Root page)?
              General rules and best pratices of the Forum. - General - MQL5 programming forum?
    Next time, post in the correct place. The moderators will likely move this thread there soon.

  2.    for(int Counter = 0; Counter <= OrdersTotal()-1; Counter++)
       {
          if(OrderSelect(Counter,SELECT_BY_POS))
          {

    In the presence of multiple orders (one EA multiple charts, multiple EAs, manual trading), while you are waiting for the current operation (closing, deleting, modifying) to complete, any number of other operations on other orders could have concurrently happened and changed the position indexing and order count:

    1. For non-FIFO (non-US brokers), (or the EA only opens one order per symbol), you can simply count down, in a position loop, and you won't miss orders. Get in the habit of always counting down.
                Loops and Closing or Deleting Orders - MQL4 programming forum

    2. For In First Out (FIFO rules — US brokers), and you (potentially) process multiple orders per symbol, you must find the earliest order (count up), close it, and on a successful operation, reprocess all positions.
                CloseOrders by FIFO Rules - Strategy Tester - MQL4 programming forum - Page 2 #16
                MetaTrader 5 platform beta build 2155: MQL5 scope, global Strategy Tester and built-in Virtual Hosting updates - Best Expert Advisors - General - MQL5 programming forum #1.11

    3. and check OrderSelect in case later positions were deleted.
                What are Function return values ? How do I use them ? - MQL4 programming forum
                Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles

    4. and if you (potentially) process multiple orders, must call RefreshRates() after server calls if you want to use, on the next order / server call, the Predefined Variables (Bid/Ask.) Or instead, be direction independent and just use OrderClosePrice().

  3. You decrement by one on a successful close. That will not work in the presence of EAs on other charts.

  4.             double ClosePrice = MarketInfo(_Symbol,MODE_BID);
                if(OrderType() == OP_SELL) ClosePrice = MarketInfo(_Symbol, MODE_ASK);

    You can use OrderClosePrice() instead of Bid/Ask and be direction independent — no need to check order type to get the close price.

  5. You filter by Magic Number and Symbol, when you test for loosing orders. You do not filter for winning orders.
  6.       for(int order = 0; order <= OrdersTotal() - 1; order++)
       {
         OrderSelect(order,SELECT_BY_TICKET);
    Order is a position index not a ticket number.
Reason: