the easiest thing to do is to write in the comment box the time when the order should be closed.
You cannot rely on comments. There are brokerage companies that not only change this field (by adding their own data), but also simply erase the information previously entered.
Find the oldest order opened by the Expert Advisor. It has the smallest OrderOpenTime().
Compare how much time has passed from the moment of opening of this order to the current time. If it is equal to or greater than the specified time, close it.
Your variant suited me very well. Thank you.
Renat Akhtyamov:
By time of existence you can choose both the first opened order and the most recent one. In this case, remember the ticket and the number of seconds of existence. For example
Your variant also works. Thank you.
I will leave the first variant to work))
int TicketCL=-1;
datetime TimeOp=D'3000.12.30';
for(i=OrdersTotal()-1;i>=0;i--)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderType()<2 && OrderMagicNumber()==Magic && OrderSymbol()==Symbol()){
if (TicketCL<0||OrderOpenTime()<TimeOp){
TicketCL=OrderTicket();
TimeOp=OrderOpenTime();}
}
if (TimeCurrent()-TimeOp>=MinuteOrdCL*60) CloseOrd(TicketCL);
}//Start END//
void CloseOrd(int ticket){
int close;
double price=0.0;
color cl;
for(i=0;i<OrdersTotal();i++)
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderType()<2 && OrderMagicNumber()==Magic && OrderSymbol()==Symbol()){
if(OrderType()==OP_BUY) {price=NormalizeDouble(Bid,Digits);cl=DeepSkyBlue;}
if(OrderType()==OP_SELL) {price=NormalizeDouble(Ask,Digits);cl=Magenta;}
if(OrderType()<2) {close=OrderClose(ticket,OrderLots(),price,30,cl);}}}
Don't rely on comments. There are DCs who do not just change this field (by adding their own data), but simply erase the information previously entered.
And instead of checking the order type, in this case, it's better to check the close time OrderCloseTime(), just in case, in case it has already closed at stop/stop.
why search for it in a cycle, if you can just select the order on the ticket
and instead of checking the order type, in this case,it would be better to check the closing time OrderCloseTime(), just in case it has already been closed by a stop/stop.
I thought Natalya wanted it that way, because she wanted to search for the ticket, but apparently not all cards have been solved
you risk getting the volume of the order you are going to close. After all, OrderLots() will refer to the selected order, and the ticket - to an absolutely different one. It would be better to do it that way:
Fair points above. Why go through all the orders again if the ticket is already known? Besides, in the function:
you risk getting the volume of the order you are going to close. After all, OrderLots() will refer to the selected order, and the ticket - to an absolutely different one. You'd better do it that way:
//закрытие по тикету, переделайте под свойif(OrderSelect(MyTicketBuy, SELECT_BY_TICKET)==true)
{
close=OrderClose(MyTicketBuy,OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),0,clrRed);
if(close<0){if(Fun_Error(GetLastError())==1)return;}
}
if(OrderSelect(MyTicketSell, SELECT_BY_TICKET)==true)
{
close=OrderClose(MyTicketSell,OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),0,clrBlue);
if(close<0){if(Fun_Error(GetLastError())==1)return;}
}
//+-------------- ФУНКЦИЯ ОБРАБОТКИ ОШИБОК ---------------------------------+int Fun_Error(int Error)
{ switch(Error)
{
case0: return (0);
case1: Print("Попытка изменить уже установленные значения такими же значениями.");return(1);
case2: Print("Общая ошибка. Прекратить все попытки торговых операций до выяснения обстоятельств.");return(0);
case3: Print("В торговую функцию переданы неправильные параметры.");return(1);
case4: Print("Торговый сервер занят.Пробуем ещё раз..");Sleep(3000);return(1);
case5: Print("Старая версия клиентского терминала.");return(0);
case6: Print("Нет связи с торговым сервером.");return(1);
case7: Print("Недостаточно прав.");return(1);
case8: Print("Слишком частые запросы.");return(1);
case9: Print("Недопустимая операция нарушающая функционирование сервера.");return(1);
case64: Print("Счет заблокирован. Необходимо прекратить все попытки торговых операций.");return(0);
case65: Print("Неправильный номер счета.");return(1);
case128: Print("Истек срок ожидания совершения сделки.");return(1);
case129: Print("Неправильная цена bid или ask, возможно, ненормализованная цена.");return(1);
case130: Print("Слишком близкие стопы или неправильно рассчитанные или ненормализованные цены в стопах (или в цене открытия отложенного ордера).");return(1);
case131: Print("Неправильный объем, ошибка в грануляции объема.");return(1);
case132: Print("Рынок закрыт.");return(1);
case133: Print("Торговля запрещена.");return(0);
case134: Print("Недостаточно денег для совершения операции.");return(0);
case135: Print("Цена изменилась. Пробуем ещё раз..");RefreshRates();return(1);
case136: Print("Нет цен. Ждём новый тик..");
while(RefreshRates()==false)// До нового тикаSleep(1);
return(1);
case137: Print("Брокер занят.Пробуем ещё раз..");Sleep(3000);return(1);
case138: Print("Запрошенная цена устарела, либо перепутаны bid и ask.");return(1);
case139: Print("Ордер заблокирован и уже обрабатывается.");return(1);
case140: Print("Разрешена только покупка. Повторять операцию SELL нельзя.");return(1);
case141: Print("Слишком много запросов.");return(1);
case142: Print("Ордер поставлен в очередь.");return(1);
case143: Print("Ордер принят дилером к исполнению.");return(1);
case144: Print("Ордер аннулирован самим клиентом при ручном подтверждении сделки.");return(1);
case145: Print("Модификация запрещена, так как ордер слишком близок к рынку и заблокирован из-за возможного скорого исполнения.");return(1);
case146: Print("Подсистема торговли занята.Пробуем ещё..");Sleep(500);return(1);
case147: Print("Использование даты истечения ордера запрещено брокером.");return(1);
case148: Print("Количество открытых и отложенных ордеров достигло предела, установленного брокером.");return(1);
case149: Print("Попытка открыть противоположную позицию к уже существующей в случае, если хеджирование запрещено.");return(1);
case4000: return (0);
case4001: Print("Неправильный указатель функции.");return(1);
case4002: Print("Индекс массива - вне диапазона.");return(1);
case4003: Print("Нет памяти для стека функций.");return(1);
case4004: Print("Переполнение стека после рекурсивного вызова.");return(1);
case4005: Print("На стеке нет памяти для передачи параметров.");return(1);
case4006: Print("Нет памяти для строкового параметра.");return(1);
case4007: Print("Нет памяти для временной строки.");return(1);
case4008: Print("Неинициализированная строка.");return(1);
case4009: Print("Неинициализированная строка в массиве.");return(1);
case4010: Print("Нет памяти для строкового массива.");return(1);
case4011: Print("Слишком длинная строка.");return(1);
case4012: Print("Остаток от деления на ноль.");return(1);
case4013: Print("Деление на ноль.");return(1);
case4014: Print("Неизвестная команда.");return(1);
case4015: Print("Неправильный переход.");return(1);
case4016: Print("Неинициализированный массив.");return(1);
case4017: Print("Вызовы DLL не разрешены.");return(1);
case4018: Print("Невозможно загрузить библиотеку.");return(1);
case4019: Print("Невозможно вызвать функцию.");return(1);
case4020: Print("Вызовы внешних библиотечных функций не разрешены.");return(1);
case4021: Print("Недостаточно памяти для строки, возвращаемой из функции.");return(1);
case4022: Print("Система занята.");return(1);
case4050: Print("Неправильное количество параметров функции.");return(1);
case4051: Print("Недопустимое значение параметра функции.");return(1);
case4052: Print("Внутренняя ошибка строковой функции.");return(1);
case4053: Print("Ошибка массива.");return(1);
case4054: Print("Неправильное использование массива-таймсерии.");return(1);
case4055: Print("Ошибка пользовательского индикатора.");return(1);
case4056: Print("Массивы несовместимы.");return(1);
case4057: Print("Ошибка обработки глобальныех переменных.");return(1);
case4058: Print("Глобальная переменная не обнаружена.");return(1);
case4059: Print("Функция не разрешена в тестовом режиме.");return(1);
case4060: Print("Функция не подтверждена.");return(1);
case4061: Print("Ошибка отправки почты.");return(1);
case4062: Print("Ожидается параметр типа string.");return(1);
case4063: Print("Ожидается параметр типа integer.");return(1);
case4064: Print("Ожидается параметр типа double.");return(1);
case4065: Print("В качестве параметра ожидается массив.");return(1);
case4066: Print("Запрошенные исторические данные в состоянии обновления.");return(1);
case4067: Print("Ошибка при выполнении торговой операции.");return(1);
case4099: Print("Конец файла.");return(1);
case4100: Print("Ошибка при работе с файлом.");return(1);
case4101: Print("Неправильное имя файла.");return(1);
case4102: Print("Слишком много открытых файлов.");return(1);
case4103: Print("Невозможно открыть файл.");return(1);
case4104: Print("Несовместимый режим доступа к файлу.");return(1);
case4105: Print("Ни один ордер не выбран.");return(1);
case4106: Print("Неизвестный символ.");return(1);
case4107: Print("Неправильный параметр цены для торговой функции.");return(1);
case4108: Print("Неверный номер тикета.");return(1);
case4109: Print("Торговля не разрешена. Необходимо включить опцию Разрешить советнику торговать в свойствах эксперта.");return(1);
case4110: Print("Длинные позиции не разрешены. Необходимо проверить свойства эксперта.");return(1);
case4111: Print("Короткие позиции не разрешены. Необходимо проверить свойства эксперта.");return(1);
case4200: Print("Объект уже существует.");return(1);
case4201: Print("Запрошено неизвестное свойство объекта.");return(1);
case4202: Print("Объект не существует.");return(1);
case4203: Print("Неизвестный тип объекта.");return(1);
case4204: Print("Нет имени объекта.");return(1);
case4205: Print("Ошибка координат объекта.");return(1);
case4206: Print("Не найдено указанное подокно.");return(1);
case4207: Print("Ошибка при работе с объектом.");return(1);
return(0);
}
return(0);
}
the easiest thing to do is to write in the comment box the time when the order should be closed.
You cannot rely on comments. There are brokerage companies that not only change this field (by adding their own data), but also simply erase the information previously entered.
What's the problem?
Your variant suited me very well. Thank you.
By time of existence you can choose both the first opened order and the most recent one. In this case, remember the ticket and the number of seconds of existence. For example
Your variant also works. Thank you.
I will leave the first variant to work))
Thank you all for your help, good luck))
Don't rely on comments. There are DCs who do not just change this field (by adding their own data), but simply erase the information previously entered.
To be clear, please provide a list of these DCs
Not to be unsubstantiated - please give me a list of these VCs
Your option was great for me. Thank you.
Your way works, too. Thank you.
I'll keep the first option for work))
Thank you all for your help, profits to you))
Only one question: If you know the ticket
Why do we need to search for it in the loop, if we can simply select the order of the ticket
And instead of checking the order type, in this case, it's better to check the close time OrderCloseTime(), just in case, in case it has already closed at stop/stop.
Just one question: If you know the ticket
why search for it in a cycle, if you can just select the order on the ticket
and instead of checking the order type, in this case,it would be better to check the closing time OrderCloseTime(), just in case it has already been closed by a stop/stop.
I thought Natalya wanted it that way, because she wanted to search for the ticket, but apparently not all cards have been solved
)
Your option was great for me. Thank you.
Your way works, too. Thank you.
I'll keep the first option for work))
Thank you all for your help, profits to you))
Fair comments above. Why would I go through all orders once again if the ticket is already known? Besides, in the function:
you risk getting the volume of the order you are going to close. After all, OrderLots() will refer to the selected order, and the ticket - to an absolutely different one. It would be better to do it that way:
Fair points above. Why go through all the orders again if the ticket is already known? Besides, in the function:
you risk getting the volume of the order you are going to close. After all, OrderLots() will refer to the selected order, and the ticket - to an absolutely different one. You'd better do it that way:
This does not close at all.
It doesn't close at all.
I beg your pardon. The line:
should be rewritten as follows: