Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1918

 
Sergey Gridnev #:
You need 2 cycles: you find out the minimum volume in the first one and close it in the second one. And note that when you close the orders are shifted by 1 position, so you have to do the cycle from the maximum position to 0.

no. From the earliest to the latest.

 

I knew what they said. Well, I'll just have to learn by trial and error as usual.

 
Rustam Bikbulatov #:

I knew what they said. Well, I'll just have to learn by trial and error as usual.

//+------------------------------------------------------------------+
//|                                                       Око_01.mq4 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#include <GrosBuch.mqh>
#property script_show_inputs

//input double Max_loss=0; //
extern int N=6;           // Количество ордеров
input int SLpips=0;      // Количество пунктов
//Вычисляем возможное оставшееся количество лотов при N лоссов от оставшихся свободных средств
// Buch bi;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   double PipValue = MarketInfo(NULL, MODE_TICKVALUE),
          min_lot = MarketInfo(NULL, MODE_MINLOT),
          lot_step = MarketInfo(NULL, MODE_LOTSTEP),
          Margin = MarketInfo(Symbol(), MODE_MARGINREQUIRED),
          Max_loss=N*SLpips*PipValue*min_lot,                 //Вычисляем сумму совокупного возможного лосса
          M_m=DBL_MIN;
   double remains= AccountFreeMargin()-Max_loss;  //Значение свободных средств для открыти ордера Margin*Lots;
   while(remains>Margin*min_lot&&!IsStopped())   //если они больше,чем необходимо для открытия 1 лота
     {
      min_lot=NormalizeDouble(min_lot+lot_step,2);  //добавим минлот
      M_m=Margin*min_lot;                           //получим значени св средств при вычисленном лоте и размере стопа
      // Lots*=min_lot;
      Print("remains = ",remains," Margin =",Margin," PipValue =",PipValue," N =",N,"min_lot =",min_lot," Max_loss =",Max_loss," M-m =",M_m);
     }
  }
//+------------------------------------------------------------------+
 

Good evening, dear experts!

Please help me understand one thing. I am writing the beginning of a function and have decided to check some part of its code with a script:

//+------------------------------------------------------------------+
//|                                                            3.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   /* Создадим запрос на сервер и получим ответ с результатом */
   MqlTradeRequest request= {};
   MqlTradeResult result= {0};
   /* запустим цикл для перебора всех установленных отложенных ордеров */
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      /* определим параметры установленного ордера */
      string symbol=OrderGetString(ORDER_SYMBOL);                        // символ ордера
      int    digits=(int)SymbolInfoInteger(symbol,SYMBOL_DIGITS);        // количество знаков после запятой
      double point=SymbolInfoDouble(symbol,SYMBOL_POINT);                // значение одного пункта
      ulong  ticket=OrderGetTicket(i);                                   // тикет ордера
      ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); // тип ордера
      double volume=OrderGetDouble(ORDER_VOLUME_INITIAL);                // объём ордера
      ulong  magic=OrderGetInteger(ORDER_MAGIC);                         // MagicNumber ордера
      double price_current=OrderGetDouble(ORDER_PRICE_CURRENT);          // текущая цена по символу ордера
      double price_order_open=OrderGetDouble(ORDER_PRICE_OPEN);          // цена открытия указанная в ордере
      double sl=OrderGetDouble(ORDER_SL);                                // стоп лосс ордера
      double tp=OrderGetDouble(ORDER_TP);                                // тейк профит ордера
      /* выведем информацию об установленных отложенных ордерах */
      PrintFormat("#%I64u %s  %s  %.2f price_current: %.5f price_order_open: %.5f sl: %.5f tp: %.5f magic: %d",
                  ticket,symbol,EnumToString(type),volume,price_current,price_order_open,sl,tp,magic);
     }
  }
//+------------------------------------------------------------------+


But the result is printed in the Experts tab is a bit puzzling. The pending order ORDER_TYPE_BUY_STOP has the symbol, but the ORDER_TYPE_SELL_STOP does not have it for some reason.

What can it be connected with? Regards, Vladimir.



 
MrBrooklin #:

Good evening, dear experts!

Please help me understand one thing. I am writing the beginning of a function and have decided to check some part of its code with a script:


However, the result is printed in the Experts tab is a bit puzzling. The pending order ORDER_TYPE_BUY_STOP has the symbol, but the ORDER_TYPE_SELL_STOP does not have it for some reason.

What can it be connected with? Regards, Vladimir.



This is because you have not selected a ticket, but are trying to get its characteristics.
 
Sergey Gridnev #:
It has to do with the fact that you have not selected a ticket, but are trying to get its characteristics.

Thank you, Sergey, for your response! Your reply left me even more puzzled. How could it be? When I run the script, all set pending orders are interrogated. As we can see in the image, there are two of them on the chart, and at the same time, one ticket is selected and the other one is not? It is not quite clear.

Can you explain it in more details?

I'm asking this question not out of idle curiosity, but in order to continue the self-study.

Regards, Vladimir.

 
MrBrooklin #:

Thank you, Sergey, for your response! Your reply left me even more puzzled. How could it be? When I run the script, all set pending orders are interrogated. As we can see in the image, there are two of them on the chart, and at the same time, one ticket is selected and the other one is not? It is not quite clear.

Can you explain it in more details?

I'm asking this question not out of idle curiosity, but in order to continue the self-study.

Regards, Vladimir.

Here, you have a loop where you change iterator i from the maximum index to 0. What happens inside? Well, here's what happens: The first command you try to get the ORDER_SYMBOL parameter. But which order are you trying to get it from, because the order will be selected three lines below!
 
Sergey Gridnev #:
So, you have a loop where you change the iterator i from the maximum index to 0. What is going on inside it? Well, here's what happens: the first command you try to get the ORDER_SYMBOL parameter. But, which order are you trying to get it from, because the order will be selected three lines below!

Thank you, Sergey, for the very detailed and understandable explanation! I put the line with the pending order ticket right after the cycle start and everything has worked out fine.

Yes ... Pay attention and pay attention once again. That's what I'm really lacking. Thanks again!

Sincerely, Vladimir.

 

Good morning, esteemed experts!

Today I have faced two more issues I do not understand, but in a code entirely taken from the MQL5 Reference. This time I didn't write anything myself, but just took a ready-made example.

I open MQL5 Reference / Constants, Enumerations and Structures / Data Structures / Structure of a Trade Request. I find it there:

Structure of the trade request
Modify Pending Order
Торговый приказ на модификацию уровней цен отложенного ордера. Требуется указание 7 полей:
    action
    order
    price
    sl
    tp
    type_time
    expiration
 Пример торговой операции TRADE_ACTION_MODIFY для модификации уровней цен отложенного ордера:

This is clear. I am followed by an example with this code:

#define  EXPERT_MAGIC 123456  // MagicNumber эксперта
//+------------------------------------------------------------------+
//| Модификация отложенных ордеров                                   |
//+------------------------------------------------------------------+
void OnStart()
  {
//-- объявление и инициализация запроса и результата
   MqlTradeRequest request={};
   MqlTradeResult  result={};
   int total=OrdersTotal(); // количество установленных отложенных ордеров
//--- перебор всех установленных отложенных ордеров
   for(int i=0; i<total; i++)
     {
      //--- параметры ордера
      ulong  order_ticket=OrderGetTicket(i);                             // тикет ордера
      string order_symbol=Symbol();                                      // символ
      int    digits=(int)SymbolInfoInteger(order_symbol,SYMBOL_DIGITS);  // количество знаков после запятой
      ulong  magic=OrderGetInteger(ORDER_MAGIC);                         // MagicNumber ордера
      double volume=OrderGetDouble(ORDER_VOLUME_CURRENT);                // текущий объем ордера
      double sl=OrderGetDouble(ORDER_SL);                                // текущий Stop Loss ордера
      double tp=OrderGetDouble(ORDER_TP);                                // текущий Take Profit ордера
      ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); // тип ордера
      int offset = 50;                                                   // отступ от текущей цены для установки ордера, в пунктах
      double price;                                                      // цена срабатывания ордера
      double point=SymbolInfoDouble(order_symbol,SYMBOL_POINT);          // размер пункта
      //--- вывод информации об ордере
      PrintFormat("#%I64u %s  %s  %.2f  %s  sl: %s  tp: %s  [%I64d]",
                  order_ticket,
                  order_symbol,
                  EnumToString(type),
                  volume,
                  DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),digits),
                  DoubleToString(sl,digits),
                  DoubleToString(tp,digits),
                  magic);
      //--- если MagicNumber совпадает, Stop Loss и Take Profit не заданы
      if(magic==EXPERT_MAGIC && sl==0 && tp==0)
        {
         request.action=TRADE_ACTION_MODIFY;                           // тип торговой операции
         request.order = OrderGetTicket(i);                            // тикет ордера
         request.symbol   =Symbol();                                   // символ
         request.deviation=5;                                          // допустимое отклонение от цены
        //--- установка уровня цены, тейк-профит и стоп-лосс ордера в зависимости от его типа
         if(type==ORDER_TYPE_BUY_LIMIT)
           {
            price = SymbolInfoDouble(Symbol(),SYMBOL_ASK)-offset*point; 
            request.tp = NormalizeDouble(price+offset*point,digits);
            request.sl = NormalizeDouble(price-offset*point,digits);
            request.price    =NormalizeDouble(price,digits);                // нормализованная цена открытия
           }
         else if(type==ORDER_TYPE_SELL_LIMIT)
           {
           price = SymbolInfoDouble(Symbol(),SYMBOL_BID)+offset*point; 
            request.tp = NormalizeDouble(price-offset*point,digits);
            request.sl = NormalizeDouble(price+offset*point,digits);
            request.price    =NormalizeDouble(price,digits);                 // нормализованная цена открытия
           }
         else if(type==ORDER_TYPE_BUY_STOP)
           {
           price = SymbolInfoDouble(Symbol(),SYMBOL_ASK)+offset*point; 
            request.tp = NormalizeDouble(price+offset*point,digits);
            request.sl = NormalizeDouble(price-offset*point,digits);
            request.price    =NormalizeDouble(price,digits);                 // нормализованная цена открытия
           }
         else if(type==ORDER_TYPE_SELL_STOP)
           {
           price = SymbolInfoDouble(Symbol(),SYMBOL_BID)-offset*point; 
            request.tp = NormalizeDouble(price-offset*point,digits);
            request.sl = NormalizeDouble(price+offset*point,digits);
            request.price    =NormalizeDouble(price,digits);                 // нормализованная цена открытия
           }
         //--- отправка запроса
         if(!OrderSend(request,result))
            PrintFormat("OrderSend error %d",GetLastError());  // если отправить запрос не удалось, вывести код ошибки
         //--- информация об операции   
         PrintFormat("retcode=%u  deal=%I64u  order=%I64u",result.retcode,result.deal,result.order);
         //--- обнуление значений запроса и результата
         ZeroMemory(request);
         ZeroMemory(result);
        }
     }
  }
//+------------------------------------------------------------------+

I'm trying to understand the line highlighted in yellow. Right away I have a question: what does PositionGetDouble(POSITION_PRICE_OPEN) have to do with itif this example is related to pending orders? Maybe, there should be a line like this:

DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN),digits)
This is the first point. The second issue comes up when I try to run this script on a chart with a BUY_STOP pending order I have set (though everything similar happens to other types of pending orders). So, what happens? Nothing happens! I do not see any modification of a pending order. Maybe, I do not understand something?

I only find this in the Experts tab:
2022.02.25 08:41:38.491 4 (EURUSD,M1)   #4727791  EURUSD  ORDER_TYPE_BUY_STOP  0.10  0.00000  sl: 0.00000  tp: 0.00000  [0]
Dear Experts, please help me to understand this example, why it is in the directory, but its code does not work?

Regards, Vladimir.
 
MrBrooklin #:
...
Dear experts please help me to understand this example, why is it in the reference book, but its code does not work?

Sincerely, Vladimir.

I wrote about it a few pages ago.

This is the forum for trading, automated trading systems and strategy testing.

Any questions from newbies on MQL4 and MQL5, help and discussion of algorithms and codes

Alexey Viktorov, 2022.02.20 10:24

Sasha, you can't think of anything worse than using examples from documentation or tumblr examples. And you've also lost the flag of forced termination of while loop somewhere. All in all ... no words.
I doubt that examples written into the documentation and even into the standard library are checked thoroughly. There are plenty of such errors. The examples, in my opinion, can only be used as samples...
Reason: