Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1481

 
Alexey Viktorov #:

It will appear if you write this

Hi Alexey, one clarification. Is it necessary to use PositionSelect() instead of a loop, or did I misunderstand something again?

Regards, Vladimir.

 
MrBrooklin #:

Hi Alexey, one clarification. Is it necessary to use PositionSelect() instead of a loop or did I misunderstand something again?

Regards, Vladimir.

You can write it any way you want, the main thing is to write a non-existent character to get an error...

 
Alexey Viktorov #:

You can write it any way you want, the main thing is to write a non-existent character to get an error....

But don't throw slippers at me!!! I can't get the error code. ((((

void OnStart()
  {
   ResetLastError(); // установим значение предопределенной переменной _LastError в ноль
   string symb = "BrooklinUSDrfd";
   PositionSelect(symb);
   PrintFormat("Не удалось выбрать позицию по символу %s. Ошибка = ", symb, GetLastError());
  }

Regards, Vladimir.

 
MrBrooklin #:
Error = "
The %lu specifier should be there
 
Artyom Trishkin #:
There should be a specifier there

Thank you Artem, it worked!!! Thank you all very much!

Regards, Vladimir.

 

In short, solved the problem described here in a different way:

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   ResetLastError(); // установим значение предопределенной переменной _LastError в ноль
   if(!PositionSelect(_Symbol))
      PrintFormat("Не удалось выбрать позицию по символу %s. Ошибка = %lu", _Symbol, GetLastError());
   int pos_total = PositionsTotal(); // объявим переменную для хранения количества открытых позиций
   if(pos_total > 0) // если есть открытые позиции
     {
      for(int i=0; i<pos_total; i++) // запустим цикл и переберём все открытые позиции
        {
         if(PositionGetSymbol(i) == _Symbol) // выберем все открытые позиции по текущему символу
           {
            ulong  pos_id = PositionGetInteger(POSITION_IDENTIFIER);
            double pos_price = PositionGetDouble(POSITION_PRICE_OPEN);
            double pos_tp = PositionGetDouble(POSITION_TP);
            double pos_sl = PositionGetDouble(POSITION_SL);
            PrintFormat("Позиция #%d цена = %G тейк-профит = %G стоп-лосс = %G", pos_id, pos_price, pos_tp, pos_sl);
           }
        }
     }
  }
//+------------------------------------------------------------------+

Regards, Vladimir.

 

Good evening everyone!

I am trying to create a function that opens an additional position (without stop and take) to an existing open position. I have written the code:

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Open_Add_Pos_Buyl()
  {
   for(int i=pos_total-1; i<pos_total; i++) // ищем последнюю по списку открытую позицию
     {
      PositionGetTicket(i); // получим тикет позиции по индексу в списке открытых позиций
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && // если совпадает символ открытой позиции
         PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && // если совпадает тип открытой позиции
         PositionGetInteger(POSITION_MAGIC) == Magic_Number) // и если совпадет мэджик
        {
         double pos_price_open=PositionGetDouble(POSITION_PRICE_OPEN); // объявим и инициализируем переменную для цены открытой позиции
         if(// тут задано условие для открытия позиции)
           {
            double new_price_pos=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
            trade.Sell(0.01,_Symbol,new_price_pos,0,0);
           }
        } 
     }
  }

but for some reason it doesn't see the open position. I tried to find the problem with the debugger, but after starting the loop it immediately leaves the function without seeing what is written inside it. I put the breakpoint at PositionGetTicket(i). Could you please tell me where I have a bug in my code again?

Regards, Vladimir.

 
MrBrooklin open position. I have written the code:

but for some reason it doesn't see the open position. I tried to find the problem with the debugger, but after starting the loop it immediately leaves the function without seeing what is written inside it. I put the breakpoint on PositionGetTicket(i). Could you please tell me where I have a bug in my code again?

Regards, Vladimir.

What is pos_total?

 
Alexey Viktorov #:

What is pos_total equal to?

Hi Alexey, the variable pos_total=PositionsTotal(), but it was set at the global level. Now I have moved it inside the function and it turned out that this was the problem. Everything worked. What's the problem? I didn't understand the trick at all!!!

Now, for the sake of experiment, I moved pos_total to the global level again and it stopped working again, but when I put it inside the function, it works as it should! Just some miracles, well, at least for me!!!! )))

It turns out that a variable at the global level cannot be initialised by a function? Is it so?

Regards, Vladimir.

 
MrBrooklin #:

Hi Alexey, the variable pos_total=PositionsTotal(), it was just set at the global level. Now I have moved it inside the function and it turned out that this was the problem. Everything worked. What's the problem? I don't understand the joke at all!!!

Now, for the sake of experiment, I moved pos_total to the global level again and it stopped working again, but when I put it inside the function, it works as it should! Just some miracles, well, at least for me!!!! )))

It turns out that a variable at the global level cannot be initialised by a function? Is that right?

Regards, Vladimir.

Sometimes you can, but not every variable. In this case, when you run the EA, it does not see open positions yet and the variable is equal to zero....

Actually, yesterday I experimented with position sampling and came to the conclusion that PositionsTotal() is needed only to determine the number of positions. And this number is needed only to limit the loop.

Here is such a loop

  int i = 0;
  while(bool(posTicket = PositionGetTicket(i)) && !IsStopped())
   {
    string posSymbol = PositionGetString(POSITION_SYMBOL);
    double posPrice = PositionGetDouble(POSITION_PRICE_OPEN),
           pos_tp = PositionGetDouble(POSITION_TP),
           pos_sl = PositionGetDouble(POSITION_SL);
    printf("%s Ticket %d цена = %g тейк-профит = %g стоп-лосс = %g", posSymbol, posTicket, posPrice, pos_tp, pos_sl);
    i++;
   }


works even if you get a list of orders or deals from the history before it. One of these days I will check whether the selection of pending orders will interfere with it.


And in your case it's easier to write without a loop

      PositionGetTicket(PositionsTotal()-1); // получим тикет позиции

if you need the last position...

Reason: