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

 
geratdc:

Hello,


Looking for the following information:

1. regarding the implementation of SMS-notifications when processing key events in the work of the EA.

About realization of opening and closing of trade from 12-00 PST till 18-00 PST (with sms-notification of course :) about the beginning and end of a weekly trading session ).

About implementing an email notification after completion of trade (18-00 PTN) - sending report on the work of the advisor for a weekly trading session, in the tester, with a graph and indication of dates of opening, closing dates, prices, profits/losses after closing positions. Or will the reports be in txt format ?


Please advise which functions or scripts will implement it ? How can I do it? May be there is a topic about it - SMS and e-mail notifications and reports.

https://www.mql5.com/ru/articles/1454

Here's something like this, but to make it simpler)))


https://www.mql5.com/ru/forum/53920

The algorithm of sms notifications is not bad, our EA sends us email, and the email operator sends us the text of the letter. All brilliantly simple. All we need is to register our mobile phone. It's easier now.

I'll go read, I found a similar function - SendMail().I wonder how complicated it is?

All such a long time ago has all such a standard. Use push messages instead of sms, SendMail() has already found it.
 

Good afternoon everyone!

Made this code - delete all orders at once.

//===================================================================
void delete_all_orders()
{
bool err;
int ot;
for(int iss=OrdersTotal()-1; iss>=0; iss--)
   {
    if(OrderSelect(iss, SELECT_BY_POS, MODE_TRADES))
      {
       if(OrderSymbol()==Symbol())
         {
          if(OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP)
           {
            ot=OrderTicket();
            Print("Удаляем ордер тикет - ",OrderTicket());
            err=OrderDelete(OrderTicket(),clrNONE);
            if(err==false) error(GetLastError());
            Print("Удален ордер тикет - ",ot);
           }
          if(OrderType()==OP_BUY)
           {
            ot=OrderTicket();
            Print("Удаляем ордер тикет - ",OrderTicket());
            err=OrderClose(OrderTicket(),OrderLots(),Bid,10,clrNONE);
            if(err==false) error(GetLastError());
            Print("Удален ордер тикет - ",ot);
           }
          if(OrderType()==OP_SELL)
           {
            ot=OrderTicket();
            Print("Удаляем ордер тикет - ",OrderTicket());
            err=OrderClose(OrderTicket(),OrderLots(),Ask,10,clrNONE);
            if(err==false) error(GetLastError());
            Print("Удален ордер тикет - ",ot);
           }
         }
      }
   }
return;
}

The problem is that almost all orders are closed. But we still have 1-2 orders that are not deleted.

And no matter how many times I access this function, this function does not close the remaining orders.

I get an error showing wrong price.

I thought it was requotes but if we request this function 500000 times already, what requotes may be?

What cannot be the wrong price?

I have never had such a nonsense with other EAs.

 
Valerius:

Good afternoon everyone!

Made this code - delete all orders at once.

The problem is that almost all orders are closed. But we still have 1-2 orders that are not deleted.

And no matter how many times I access this function, this function does not close the remaining orders.

I get an error showing wrong price.

I thought it was requotes but if we request this function 500000 times already, what requotes may be?

What cannot be the wrong price?

I have never had such a nonsense with other EAs.

If there are a lot of orders, the price has time to get out of date. Add RefreshRates() and it should be ok.
RefreshRates - Доступ к таймсериям и индикаторам - Справочник MQL4
RefreshRates - Доступ к таймсериям и индикаторам - Справочник MQL4
  • docs.mql4.com
RefreshRates - Доступ к таймсериям и индикаторам - Справочник MQL4
 
Alexey Viktorov:
If there are a lot of orders, the price has time to become out of date. Add RefreshRates() and it should be fine.

That's the thing: one or two orders are left.

I have made a cycle of calls to this function until all orders are deleted.

In idea, if the order is for buy, it should be closed by Bid, and it does not matter what price it is now.

It should close by Bid at any price.

And if we have addressed this function many thousands of times, the price should close anyway.

Or maybe I do not understand something?

 
Valerius:

That's the thing: one or two orders are left.

I have made a cycle of calls to this function until all orders are deleted.

In idea, if the order is for buy, it should be closed by Bid, and it does not matter what price it is now.

It should close by Bid at any price.

And if we have addressed this function many thousands of times, the price should close anyway.

Or is there something I do not understand?

Are there errors in the log when deleting?

The price can go far enough during the cycle. Ask and Bid are constants that are updated either forcibly (when calling RefreshRates()) or when processing a new tick. So, after each loop turn, call RefreshRates() and see what happens.

 
Thanks, I'll give it a try.
 
Valerius:
That's the thing, there's one or two orders left.
I have made a loop of calls to this function until all the orders are deleted.
In theory, if the order is for buy, it should be closed by Bid and it does not matter what price it is at that moment.
It should close by Bid at any price.
And if we have addressed this function many thousands of times, the price should close anyway.
Or maybe I do not understand something?

Try 1) replace Print with Alert to see the result on the screen immediately - it's faster 2) You get the error code there. Print it and see 3) Get and print the error code of the OrderSelect function and immediately OrderSymbol(), OpderType(), OrderTicket()

if (! OrderSelect(.......))
{
  Alert(GetLastError());
  continue;
}
Alert("OrderSymbol = ",OrderSymbol(), "   OpderType = ", OpderType(), "   OrderTicket = ", OrderTicket());
 
STARIJ:

Try 1) replace Print with Alert to see the result on the screen immediately - it's faster 2) You get the error code there. Print it and see 3) Get and print the error code of the OrderSelect function and immediately OrderSymbol(), OpderType(), OrderTicket().


Tried RefreshRates() as well. Nothing has changed. Alert - same as print, gives out - wrong parameters.

Error 3.

I got up in the morning and saw that the EA had triggered and was showing the function to delete all the orders the whole night.

The counter of requests shows several millions of requests. This means that orders are not deleted.

This EA also checks if all orders are deleted, it is like an insurance. If there are orders, we will call the

The function of deletion is called for. The program gets stuck. This means, the loop will not stop until all orders are deleted.

Such troubles occur on 2 currency pairs. I have already lost my mind. What to do?

 
Valerius:


I have tried RefreshRates(). Nothing has changed. Alert - same as print, it says - wrong parameters.

Error 3.

Woke up this morning and saw that the EA had triggered and was showing a call to delete all orders all night.

The counter of requests showed several millions of requests. It means that orders are not deleted.

This EA also checks if all orders are deleted, it is like an insurance. If there are orders, we will call the

The function of deletion is called for. The program gets stuck. This means, the loop will not stop until all orders are deleted.

Such troubles occur on 2 currency pairs. I have already lost my mind. What to do?

And what is the error() function?

            if(err==false) error(GetLastError());
            Print("Удален ордер тикет - ",ot);

It may be the problem.

 
Alexey Viktorov:

What is the error() function?

It is possible that this is the problem.


The error() function just displays an error code. There is no problem with this function, I have it in many EAs and I never change it.

So it's definitely not the case.

The function itself is right here:

//====================================================================
int error(int errr)
{
string descr;
switch(errr)
  {
  // Коды ошибок, возвращаемые торговым сервером или клиентским терминалом:
  case 0:    descr= ""; return(0);
  case 1:    descr= "Нет ошибки, но результат не известен"; break;
  case 2:    descr= "Общая ошибка"; break;
  case 3:    descr= "Неправильные параметры"; break;
  case 4:    descr= "Торговый сервер занят"; break;
  case 5:    descr= "Старая версия клиентского терминала"; break;
  case 6:    descr= "Нет связи с торговым сервером"; break;
  case 7:    descr= "Недостаточно прав"; break;
  case 8:    descr= "Слишком частые запросы"; break;
  case 9:    descr= "Недопустимая операция нарушающая функционирование сервера"; break;
  case 64:   descr= "Счет заблокирован"; break;
  case 65:   descr= "Неправильный номер счета"; break;
  case 128:  descr= "Истек срок ожидания совершения сделки"; break;
  case 129:  descr= "Неправильная цена"; break;
  case 130:  descr= "Неправильные стопы"; break;
  case 131:  descr= "Неправильный объем"; break;
  case 132:  descr= "Рынок закрыт"; break;
  case 133:  descr= "Торговля запрещена"; break;
  case 134:  descr= "Недостаточно денег для совершения операции"; break;
  case 135:  descr= "Цена изменилась"; break;
  case 136:  descr= "Нет цен"; break;
  case 137:  descr= "Брокер занят"; break;
  case 138:  descr= "Новые цены"; break;
  case 139:  descr= "Ордер заблокирован и уже обрабатывается"; break;
  case 140:  descr= "Разрешена только покупка"; break;
  case 141:  descr= "Слишком много запросов"; break;
  case 145:  descr= "Модификация запрещена, так как ордер слишком близок к рынку"; break;
  case 146:  descr= "Подсистема торговли занята"; break;
  case 147:  descr= "Использование даты истечения ордера запрещено брокером"; break;
  case 148:  descr= "Количество открытых и отложенных ордеров достигло предела, установленного брокером"; break;
  case 149:  descr= "Попытка открыть противоположную позицию к уже существующей, если хеджирование запрещено"; break;
  case 150:  descr= "Попытка закрыть позицию по инструменту в противоречии с правилом FIFO"; break;
  case 4000: /*descr= "Нет ошибки";*/ return(0);
  case 4001: descr= "Неправильный указатель функции"; break;
  case 4002: descr= "Индекс массива - вне диапазона"; break;
  case 4003: descr= "Нет памяти для стека функций"; break;
  case 4004: descr= "Переполнение стека после рекурсивного вызова"; break;
  case 4005: descr= "На стеке нет памяти для передачи параметров"; break;
  case 4006: descr= "Нет памяти для строкового параметра"; break;
  case 4007: descr= "Нет памяти для временной строки"; break;
  case 4008: descr= "Неинициализированная строка"; break;
  case 4009: descr= "Неинициализированная строка в массиве"; break;
  case 4010: descr= "Нет памяти для строкового массива"; break;
  case 4011: descr= "Слишком длинная строка"; break;
  case 4012: descr= "Остаток от деления на ноль"; break;
  case 4013: descr= "Деление на ноль"; break;
  case 4014: descr= "Неизвестная команда"; break;
  case 4015: descr= "Неправильный переход"; break;
  case 4016: descr= "Неинициализированный массив"; break;
  case 4017: descr= "Вызовы DLL не разрешены"; break;
  case 4018: descr= "Невозможно загрузить библиотеку"; break;
  case 4019: descr= "Невозможно вызвать функцию"; break;
  case 4020: descr= "Вызовы внешних библиотечных функций не разрешены"; break;
  case 4021: descr= "Недостаточно памяти для строки, возвращаемой из функции"; break;
  case 4022: descr= "Система занята"; break;
  case 4050: descr= "Неправильное количество параметров функции"; break;
  case 4051: descr= "Недопустимое значение параметра функции"; break;
  case 4052: descr= "Внутренняя ошибка строковой функции"; break;
  case 4053: descr= "Ошибка массива"; break;
  case 4054: descr= "Неправильное использование массива-таймсерии"; break;
  case 4055: descr= "Ошибка пользовательского индикатора"; break;
  case 4056: descr= "Массивы несовместимы"; break;
  case 4057: descr= "Ошибка обработки глобальныех переменных"; break;
  case 4058: descr= "Глобальная переменная не обнаружена"; break;
  case 4059: descr= "Функция не разрешена в тестовом режиме"; break;
  case 4060: descr= "Функция не подтверждена"; break;
  case 4061: descr= "Ошибка отправки почты"; break;
  case 4062: descr= "Ожидается параметр типа string"; break;
  case 4063: descr= "Ожидается параметр типа integer"; break;
  case 4064: descr= "Ожидается параметр типа double"; break;
  case 4065: descr= "В качестве параметра ожидается массив"; break;
  case 4066: descr= "Запрошенные исторические данные в состоянии обновления"; break;
  case 4099: descr= "Конец файла"; break;
  case 4100: descr= "Ошибка при работе с файлом"; break;
  case 4101: descr= "Неправильное имя файла"; break;
  case 4102: descr= "Слишком много открытых файлов"; break;
  case 4103: descr= "Невозможно открыть файл"; break;
  case 4104: descr= "Несовместимый режим доступа к файлу"; break;
  case 4105: descr= "Ни один ордер не выбран"; break;
  case 4106: descr= "Неизвестный символ"; break;
  case 4107: descr= "Неправильный параметр цены для торговой функции"; break;
  case 4108: descr= "Неверный номер тикета"; break;
  case 4109: descr= "Торговля не разрешена"; break;
  case 4110: descr= "Длинные позиции не разрешены"; break;
  case 4111: descr= "Короткие позиции не разрешены"; break;
  case 4200: descr= "Объект уже существует"; break;
  case 4201: descr= "Запрошено неизвестное свойство объекта"; break;
  case 4202: descr= "Объект не существует"; break;
  case 4203: descr= "Неизвестный тип объекта"; break;
  case 4204: descr= "Нет имени объекта"; break;
  case 4205: descr= "Ошибка координат объекта"; break;
  case 4206: descr= "Не найдено указанное подокно"; break;
  case 4207: descr= "Ошибка при работе с объектом"; break;
  }
Comment("Ошибка!  ",descr); 
Print("Ошибка!  ",descr);
return(errr);
}     
Reason: