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

 
artmedia70:

I don't get it:

if open on the first bar, are we looking from zero to zero?


This is a little reassurance in case the opening price of the order is already much higher than Low at the moment of opening. I.e., we don't use the opening bar for searching. That is what PERIOD_M1 is for.
 
Sepulca:
This is a small hedge in case the opening price of the order is already much higher than Low at the time of opening. I.e. we do not use the opening bar for searching. That is what PERIOD_M1 is for.

I would do it in a different way. In general, I would start searching only when the position has lasted for more than one bar. After all, the best price may be right on the opening bar, and we'll waste it.
 
artmedia70:
I'd do it differently. In general, I would only start searching when the position has lasted for more than one bar. After all, the best price may be just on the opening bar, and we'll waste it...

I agree. It would probably be more efficient to remember the minimum (or maximum) price for each open order in the array on each tick, and close the orders when the condition is reached, than to re-search the minimum from the moment the order was opened, so to speak:

 ShortOrderTicket[i]=OrderSend(Symbol(),OP_SELL,......
 if(ShortOrderTicket[i]>=0) min[i]=Bid;
 //.....................................................
 //На каждом тике обновляем минимумы для каждого открытого ордера
 for(i=0;i<N;i++){
  if(ShortOrderTicket[i]>=0){
   min[i]=MathMin(min[i],Ask);
  }
// Если достигнуто условие, закрываем ордер
  if(Ask>min[i]+Delta) if(OrderClose(ShortOrderTicket[i],.....))ShortOrderTicket[i]=-1;
 }
And in case of troubles like loss of connection, restarting of advisor, etc. we should modify stoploss at orders from time to time.
 
artmedia70:
I argued that the array must be passed here by reference. Otherwise, the function will have to work with only one strictly defined array. Even if you have it defined globally.


Hmm. It depends on which array is passed to the calling function. If it's a specific array, then the called function will work with it... Because that's...

If, for example,

void FindOrders(int massive[])
{
   int oType;
   ArrayInitialize(massive, 0);
   for (int i=OrdersTotal() - 1; i>=0; i--)
   {
      if (!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != i_magic) continue;
      
      oType = OrderType();
      massive[oType] = massive[oType] + 1;
   }
}

By calling it in this way:

FindOrders(OrdersMassive)

It works with the OrdersMassive array.

And so:

FindOrders(massiveOfOrders)

With the massiveOfOrders array.

 
Can you tell me how to find out the spread at the time of opening a trade, or better yet, how to get it displayed in the log?
 
Forexman77:
Can you tell me how to find out the size of spread, at the moment of opening a trade, or, better, how to display it in the log?

If (spread) == some value, then... do something... (For example, open an order or print its value in the journal). Or vice versa, if it is not equal to or greater than (less than) some value, then we display it in the journal and do something. You can do whatever you like.
 

I will repeat the question I asked yesterday. I don't want to post it in a separate thread. If anything is not clear, I will answer all questions.

I'm still having a hard time closing the required positions. The situation is as follows:

1. The closing of positions is being tracked.

2. As soon as the last position has closed at the take line... ...all open and pending positions should be closed at once. Everything is closed sorted by lots, i.e. large lots at once, and then smaller. This is intended only for gaining experience with orders.

The implementation is as follows:

In start() on every tick:

 for (int ord=OrdersTotal()-1; ord>=0; ord--)
   {
      if (!OrderSelect(ord,SELECT_BY_POS)) continue;
      if (OrderMagicNumber() != i_magic) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderType() == 6) continue;
        
      g_ticket = OrderTicket();
      g_type = OrderType();
              
      // Блок модификации ордеров       
      if (i_sl != 0 || i_tp != 0)
      {
         if (OrderStopLoss() == 0 && OrderTakeProfit() == 0)
         {
            OrdersModifyer(g_ticket);
         }
      }
      // Закрытие всех ордеров, если последний ордер закрыт
      if (isCloseByTakeLastOpenPos(2))
      {
         // if (g_type < 2)
          {
              ClosePosBySortLots();
          }
          //else
          if (g_type > 1)
          {
              DeletePendingOrders(g_ticket);
          }
      }
   }

We are interested in closing market orders since the pending one is deleted as required. Here is what we have:

//+-------------------------------------------------------------------------------------+
//| Получаем состояние последней позиции (Открыта или закрыта)                          |
//+-------------------------------------------------------------------------------------+
bool isCloseByTakeLastOpenPos(int delta)
{
   datetime lastOrderCloseTime = -1,               // Время закрытия последнего открытого ордера
            lastOOTHist = -1;                     // Время открытия последнего открытого ордера из истории
   int j = -1;
   pr ("Запустилась функция isCloseByTakeLastOpenPos");
   
   for (int i=OrdersHistoryTotal()-1; i>=0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
      if (OrderMagicNumber() != i_magic) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderType() > 1) continue;               // Все удалённые отложки нас не интересуют..
  
      if (lastOrderCloseTime < OrderCloseTime())   // Находим время закрытия..
      {
         lastOrderCloseTime = OrderCloseTime();   // ..последней закрытой позиции в истории
         j = i;
         pr ("j = " + j + "   " + TimeToStr(TimeCurrent()));
      }
   }
  if (OrderSelect(j, SELECT_BY_POS, MODE_HISTORY))
   {
      if (OrderProfit() + OrderCommission() + OrderSwap() <= 0) return (false);
//      pr ("OTP() = " + OrderTakeProfit() + "; OCP() " + OrderClosePrice() + "   " + TimeToStr(TimeCurrent()));
  //    pr ("OOP() = " + OrderOpenPrice() + "; OCP() " + OrderClosePrice() + "   " + TimeToStr(TimeCurrent()));
      if (MathAbs(OrderTakeProfit() - OrderClosePrice()) > delta * pt) return (false);
      else
      {
         lastOOTHist = OrderOpenTime();
         Comment("\n", "FUNC isCloseByTakeLastOpenPos: ",
                 "\n", "j = ", j,
                 "\n", "lastOOTHist = ", TimeToStr(lastOOTHist, TIME_SECONDS));
      }
   }
   else
   {
      Comment("\n", "FUNC isCloseByTakeLastOpenPos: ",
              "\n", "j = ", j,
              "\n", "не удалось выбрать ордер в истории");
      return(false);
   }
  
   for(int h=OrdersTotal()-1; h>=0; h--)
   {
      if (OrderSelect(h, SELECT_BY_POS, MODE_TRADES))
      {
         if (OrderMagicNumber() != i_magic)   continue;
         if (OrderSymbol() != Symbol())       continue;
         if (OrderType() > 1)                 continue;
         if (lastOOTHist < OrderOpenTime()) return(false);  // Выбранная рыночная позиция открыта позже закрытой по тейку
      }
      else {Print("FUNC isCloseByTakeLastOpenPos : не удалось выбрать рыночный ордер");return(false);}
   }
   
   return (true);
}

//+-------------------------------------------------------------------------------------+
//| Закрытие ордеров, отсортированных по размеру лотов                                  |
//+-------------------------------------------------------------------------------------+
void ClosePosBySortLots()
{
   double a[][2];
   int p = 0;
   
   for (int i=OrdersTotal()-1; i>=0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
      if (OrderMagicNumber() != i_magic) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderType() < 2)
      {
         p++;
         ArrayResize(a, p);
         a[p-1][0] = OrderLots();
         a[p-1][1] = OrderTicket();
      }
   }
   pr ("ClosePosBySortLots(): " + "p = " + p);
   if (p > 0)
   {
      ArraySort(a, WHOLE_ARRAY, 0, MODE_DESCEND);
      for(i=0; i<p; i++)
      {
         if (OrderSelect(a[i][1], SELECT_BY_TICKET, MODE_TRADES))
         {
             if (OrderCloseTime() == 0) ClosePosBySelect();
         }
      }
   }
}
//+-------------------------------------------------------------------------------------+
//| Закрытие одного, предварительно выбранного ордера                                   |
//+-------------------------------------------------------------------------------------+
void ClosePosBySelect()
{
   bool   fc;
   color  clClose, clCloseBuy = Blue, clCloseSell = Red;
   double ll, pa, pb, pp;
   int    err, it, NumberOfTry = 3;

   if (OrderType() == OP_BUY || OrderType() == OP_SELL)
   {
       for (it=1; it<=NumberOfTry; it++)
       {
           while (!IsTradeAllowed()) Sleep(5000);
           RefreshRates();
           pa = MarketInfo(OrderSymbol(), MODE_ASK);
           pb = MarketInfo(OrderSymbol(), MODE_BID);
           if (OrderType() == OP_BUY)
           {
               pp = pb; clClose = clCloseBuy;
           }
           else
           {
               pp = pa; clClose = clCloseSell;
           }
           ll = OrderLots();
           fc = OrderClose(OrderTicket(), ll, pp, 30, clClose);
           if (fc)
           {
              break;
           }
           else
           {
               err = GetLastError();
           }
       }
   }
   else Print("Некорректная торговая операция. Close ");
}

For some reason some of the orders are not being closed. I print some segments when I see them, I don't understand anything. Here is an example:

The comment shows that lastOOTHist = 01:30:00, though this is not actually correct. If we check lastOOTHist in the results window, we will see that

their closing times are different...

What is wrong here?

 
hoz:


Hmm. It depends on which array is passed to the calling function. If it's a specific array, then the called function will work with it... Because that's...

If, for example,

By calling it in this way:

It works with the OrdersMassive array.

And so:

With array massiveOfOrders.


When you pass a variable (array) to a function by value, a local variable is created inside the function and you declare it in the header: myFunct(int my_var). This way, changes of this variable cannot be seen outside the function. And in the case of an array, the compiler will remind you of this.

If you want the changes in the variable's value to be visible outside (outside the function), pass the variables by reference : myFunct(int & my_var)

 
hoz:


It depends upon which array is passed to the calling function. If there's a certain array, then the called function will work with it... It's like this...

If, for example,

By calling it like this:

It works with the OrdersMassive array

And this way:

With array massiveOfOrders

Exactly. That's what I'm saying - why would you want a specific array to be hard-coded in the function itself, if you can pass any array of the same size and type into it.
 
hoz:

I will repeat the question I asked yesterday. I don't want to post it in a separate thread. If anything is not clear, I will answer all questions.

I'm still having a hard time closing the required positions. The situation is as follows:

1. The closing of positions is being tracked.

2. As soon as the last position has closed at the take line... ...all open and pending positions should be closed at once. Everything is closed sorted by lots, i.e. large lots at once, and then smaller. This is intended only for gaining experience with orders.

The implementation is as follows:

In start() on every tick:

We are interested in closing market orders since the pending one is deleted as required. Here is what we have:

For some reason some of the orders are not being closed. I print some segments when I see them, I don't understand anything. Here is an example:

The comment shows that lastOOTHist = 01:30:00, though this is not actually correct. If we check lastOOTHist in the results window, we will see that

their closing times are different...

What is wrong here?

You got it all mixed up...

right here:

for(i=0; i<p; i++)
      {
         if (OrderSelect(a[i][1], SELECT_BY_TICKET, MODE_TRADES)) // выделенное красным лишнее, тут pool не имеет значения
         {
             if (OrderCloseTime() == 0) ClosePosBySelect();
         }
      }

Unprint the values of all the cells in the array before the loop - maybe that's where the dog is digging in.