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.
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 |//+------------------------------------------------------------------+voidOnStart()
{
/* Создадим запрос на сервер и получим ответ с результатом */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.
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.
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!
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 эксперта//+------------------------------------------------------------------+//| Модификация отложенных ордеров |//+------------------------------------------------------------------+voidOnStart()
{
//-- объявление и инициализация запроса и результата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); // нормализованная цена открытия
}
elseif(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); // нормализованная цена открытия
}
elseif(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); // нормализованная цена открытия
}
elseif(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 doesPositionGetDouble(POSITION_PRICE_OPEN) have to do with itif this example is related to pending orders? Maybe, there should be a line like this:
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?
Sasha, you can't think of anythingworse 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...
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.
I knew what they said. Well, I'll just have to learn by trial and error as usual.
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:
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.
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.
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.
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.
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 requestThis is clear. I am followed by an example with this code:
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:
I only find this in the Experts tab: Dear Experts, please help me to understand this example, why it is in the directory, but its code does not work?
Regards, Vladimir.
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.