Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 711

 
7Konstantin7:

Hi all.

I am trying to update a simple trawl EA by Kim to delete pending orders after closing all market orders, it fails(

I have added function to delete pending orders:

I faced another problem which I should not be able to solve because I'm not too good at coding.

I guess I should write a condition such as:

This is just an example from another EA.


Please help me out.

Kostya, start a loop calculating the number of orders of the required types and then delete it as you want.
 
_new-rena:
Kostya, make a loop to calculate the number of orders for the required types, then delete as you wish, don't get wise.

I'm a code nerd) I added more pauses there, maybe it will help)

  if (OrderType()==OP_BUY || OrderType()==OP_SELL || OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP) {
 
7Konstantin7:

I'm a code nerd) I've added some more pauses to it, maybe it'll help.)

The highlighted isn't the problem. The problem is that before you add the pauses you should have thought, "What's in it for you?" It won't do anything... ...and is there any point in adding it?

I did not understand the rest, I'm drunk and do not respect Kim's codes... sorry...

 
AlexeyVik:

The highlighted is not the trouble. The trouble is that before you add the pending orders you should have thought "What will it do???" It's not gonna do anything... and is there any point in adding it???

And the rest I did not understand, I'm drunk and Kim's codes do not respect ... sorry ...

Nothing) I thought so, I have to write a condition and now I'm thinking.

Yes, the codes are not for reals in it) at least for free, about paid I do not know.

 
7Konstantin7:

It didn't do anything) I thought so, I need to write a condition, I'm thinking.

I don't know how to do this, but I've got a different code for real ones.

For the real ones, each brokerage house has its own code, so there's no universal one.

 

Problem solved) thought long and hard) thank you all.

   if (gdProfit>BEGIN_PROFIT) {
    ClosePosFirstProfit();
    if (DeleteOrders) DeleteOrders();
  }
 

Hi all!

I am facing a problem with closing counter orders on a five marker. The point is, I need to close, say, 20 buy orders and 33 sell orders when the total profit is reached. And I want to close 20 buy orders and 20 sell orders using function OrderCloseBy(), and close the remaining 13 sell orders using function OrderClose().

If we have a fixed spread at 4 digits, we will not have any problems with closing the spread and we also save the spread when using the function OrderCloseBy(). If we have a 5-digit spread, the spread is floating and that is why, I think, orders are not closed when total profit is reached and the log says OrderCloseBy(). At the same time, if we run it in the tester, all is closed normally.

Orders in one direction, when the total profit is achieved, are closed without any problems.

Who has encountered such a problem, and what are the options for solving it?

Here is the function to close orders.

  //-----------------------------------------------------------------------
  // функция подсчета открытых ордеров
  //-----------------------------------------------------------------------

  void OrderOpen()
   {
     Orders_BUY=0; Orders_SELL=0;
     for(int a=0; a<=OrdersTotal(); a++)
     {
      if(OrderSelect(a,SELECT_BY_POS,MODE_TRADES) == true && OrderType()==OP_BUY && OrderMagicNumber() == Magic) Orders_BUY=Orders_BUY+1;
      if(OrderSelect(a,SELECT_BY_POS,MODE_TRADES) == true && OrderType()==OP_SELL && OrderMagicNumber() == Magic) Orders_SELL=Orders_SELL+1;

      //if(OrderSelect(a,SELECT_BY_POS,MODE_TRADES) && OrderType()==OP_BUY) Orders_BUY=Orders_BUY+1;
      //if(OrderSelect(a,SELECT_BY_POS,MODE_TRADES) && OrderType()==OP_SELL) Orders_SELL=Orders_SELL+1;
      ProfitAll=ProfitAll+OrderProfit()+OrderSwap()+OrderCommission();
     }
   }
  
  //-----------------------------------------------------------------------
  // функция закрытия ордеров сначала разнонаправленных
  //-----------------------------------------------------------------------
  void ClosePos()
   {
   int ticket_1=0, ticket_2=0;
    
     for (int a=0; a<=OrdersTotal(); a++)
       {
         if(OrderSelect(a,SELECT_BY_POS,MODE_TRADES) == true) 
            {
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic) // проверка по символу и магику
               {
                if(OrderType() == OP_BUY) ticket_1 = OrderTicket();
                if(OrderType() == OP_SELL) ticket_2= OrderTicket();   
               } 
            }
        }    
      if(ticket_1 != 0 && ticket_2 != 0) {          // если найдены разнонаправленные ордера
      res = OrderCloseBy(ticket_1,ticket_2,clrRed); }   // закроем их
       
      if(ticket_1 == 0 && ticket_2 != 0) {  CloseOrder_by_type(OP_SELL,Symbol());  }
      if(ticket_1 != 0 && ticket_2 == 0) {  CloseOrder_by_type(OP_BUY,Symbol());  }
    
    }

//---- Закрытие ордера по типу и комментарию ----//
void CloseOrder_by_type(int type, string sym)
{
   for(int k= OrdersTotal()-1;k>=0;k--)
   {
    
      if(OrderSelect(k,SELECT_BY_POS,MODE_TRADES)==true)
       {
           
      if(type == OrderType() && sym==OrderSymbol()&& OrderMagicNumber()==Magic)
         if(OrderType()<=1){ res = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),350);}
         else { res = OrderDelete(OrderTicket());}
         if(!res)
               Print("Ошибка закрытия ордера. Код ошибки=",GetLastError());
            else
               Print("ордер успешно закрыт.");   
           
       }
   }
}  
 

Please advise how to close orders in the order they were opened.

I want to redo this function:

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие позиций по рыночной цене сначала прибыльных           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//+----------------------------------------------------------------------------+
void ClosePosFirstProfit(string sy="", int op=-1, int mn=-1) {
  int i, k=OrdersTotal();
  if (sy=="0") sy=Symbol();

  // Сначала закрываем прибыльные позиции
  for (i=k-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) {
            if (OrderProfit()+OrderSwap()>0) ClosePosBySelect();
          }
        }
      }
    }
  }
  // Потом все остальные
  k=OrdersTotal();
  for (i=k-1; i>=0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if ((OrderSymbol()==sy || sy=="") && (op<0 || OrderType()==op)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (mn<0 || OrderMagicNumber()==mn) ClosePosBySelect();
        }
      }
    }
  }
}
 
7Konstantin7:

Please advise how to close orders in the order they were opened.

I want to redo this function:

The answer is obvious. Sort open positions by time of their opening. And then close them in the list from the sorted array.
 
artmedia70:
The answer should be given by itself. Sort open positions by time of their opening. And then close them by the list from the sorted array.

Complicated for me, will think) there is a codeto close orders in the order they were opened.

//+------------------------------------------------------------------+
//|                 Закрыть все ордера                               |
//+------------------------------------------------------------------+


double ClossAllOrders ()

{
  for(int i=0; i<OrdersTotal(); )
  {
    if ( !OrderSelect(i, SELECT_BY_POS) )
      break;
    
    int type   = OrderType();

    bool result = false;
    
    switch(type)
    {
      //Close opened long positions
      case OP_BUY       : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 3, Lime );
                          break;
      
      //Close opened short positions
      case OP_SELL      : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 3, Lime );
                          break;

      //Close pending orders
      case OP_BUYLIMIT  :
      case OP_BUYSTOP   :
      case OP_SELLLIMIT :
      case OP_SELLSTOP  : result = OrderDelete( OrderTicket() );
    }
    
    if(result == false)
    {
      Print("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
      i++;
      Sleep(500);
    }  
  }
}

// End

Here as I understand the sorting goes at the expenseof OrderTicket

how to put it in the code)