Libraries: Calendar - page 14

 
mbjen #:

Hello. Is there any possibility to move the calendar to a certain time?

Forum on trading, automated trading systems and testing trading strategies.

Libraries: Calendar

fxsaber, 2023.04.13 11:46 am.

This is solved with one line.

Calendar += 3600.


I don't remember all the functionality. ALT+M helps.

 
fxsaber # :


I don't remember all the functionality. ALT+M helps.

I have a nice suggestion:
On Save():
Subtract Calendar -= Server_GMT_Offset;
This will store calendar times in UTC time.

On Load():
Add Calendar += Server_GMT_Offset;
This allows using re-use saved file from one terminal in another terminal with a different broker's gmt_offset (EA testing on different terminals).

I suggest to add this functionality to the Save() and Load() methods of the class. Also, adding a user option (class property) to allow correcting calendar times on save/load would be also useful.


 
amrali #:
I suggest to add this functionality to the Save() and Load() methods of the class. Also, adding a user option (class property) to allow correcting calendar times on save/load would be also useful.

This is reasonable. Unfortunately, I am not ready to do it yet.

 
Hi - I just used your example Calendar EA and it seems to not be downloading the calendar data. It was working great before the 5.0 build 5200 release. Any ideas what is wrong, or fixes? Thanks
 
v88 #:
Hello - I just used your Calendar EA example and it doesn't seem to be loading the calendar data. Prior to version 5.0 build 5200 it was working fine. Any idea what is wrong or any fixes? Thanks

Checked - it is working.


These files store a single calendar for all terminals.

...\AppData\Roaming\MetaQuotes\Terminal\Community\Calendar\*.dat
 
fxsaber #:

Checked - it is working.


These files store a single calendar for all terminals.

It's definitely not working here with your test EA, with 2 different terminals. One directly from metaquotes and one through my broker. See below, both show code 1 error:



I see 3 files at \AppData\Roaming\MetaQuotes\Terminal\Community\Calendar, events, countries and descriptions. 


The lines in your test EA, show that the calendar.bin file should be saved as "Calendar.bin" in the "Roaming\MetaQuotes\Terminal\<identifier>\MQL5\Files" folder, but it's not there. Before build 5200, they would be placed there correctly. Any ideas what could be wrong?


#define FAKE // Уберите эту строку, чтобы советник заработал. Нужно для прохождения автоматической проверки КБ.

#ifndef FAKE

// Советник для торговли в MT4/5-Тестере на истории фундаментальных данных.

#define CALENDAR_FILENAME "Calendar.bin" // Название файла для чтения/записи Календаря.
#property tester_file CALENDAR_FILENAME  // Указание, чтобы MT5-Тестер подхватывал данный файл.

#include <fxsaber\Calendar\Calendar.mqh> // Календарь - фундаментальный анализ на истории и в реал-тайме.

input group "Calendar"
input string inCurrency = "USD";        // Currency
input string inFilterName = "payrolls"; // FilterName

input group "EA"
input int inTP = 1000; // TakeProfit
input int inSL = 1000; // StopLoss
input bool inReverse = true; // Trade direction

CALENDAR Calendar; // Объект с данными календаря.

int OnInit()
{
  bool Res = false;

  if (MQLInfoInteger(MQL_TESTER)) // Если работаем в Тестере
  {
    Res = Calendar.Load(CALENDAR_FILENAME) &&      // Загрузили события из файла.
          Calendar.FilterByCurrency(inCurrency) && // Применили фильтр по валюте.
          Calendar.FilterByName(inFilterName);     // Применили фильтр по названию события.

    if (!Res)                                      // Если проблемы с загруженными данными,
      Print("Run the EA in the MT5-Terminal!");    // сообщили, что нужно их получить запуском советника в MT5-Терминале.
  }
#ifdef __MQL5__
  // Работаем в Терминале.
  else if (Calendar.Set(NULL, CALENDAR_IMPORTANCE_NONE, 0, 0) && // Загрузили абсолютно все события (история + будущее) из MT5-Терминала.
           Calendar.AutoDST() &&                                 // Синхронизировали календарь с котировками.
           Calendar.Save(CALENDAR_FILENAME))                     // Сохранили их в файл.
    MessageBox("You can run the EA in the MT4/5-Tester.");       // Сообщили, что можем теперь работать в MT4/5-Тестере.
#endif // #ifdef __MQL5__

  return(!Res);
}

void OnTick()
{
  static int Pos = Calendar.GetPosAfter(TimeCurrent()); // Получили позицию события в Календаре, которая стоит сразу за текущим временем.

  if ((Pos < Calendar.GetAmount()) &&       // Если не вышли за границы Календаря
      (Calendar[Pos].time < TimeCurrent())) // и текущее время перешагнуло событие.
  {
    const EVENT Event = Calendar[Pos];      // Получили соответствующее событие.

    if ((Event.Actual != LONG_MIN) && (Event.Forecast != LONG_MIN)) // Если текущее и прогнозное значения события заданы
    {
      Print(Event.ToString()); // Распечатываем полностью это событие.

      if (Event.Actual > Event.Forecast)                                                                          // Если текущее значение больше прогнозного,
        PositionOpen(inReverse, "Act.(" + Event.ActualToString() + ")>(" + Event.ForecastToString() + ")For.");   // открываем позицию одного направления.
      else
        PositionOpen(!inReverse, "Act.(" + Event.ActualToString() + ")<=(" + Event.ForecastToString() + ")For."); // Иначе - другого направления.
    }

    Pos = Calendar.GetPosAfter(TimeCurrent(), Pos); // Получили позицию события в Календаре, которая стоит сразу за текущим временем.
  }
}

#include <MT4Orders.mqh> // https://www.mql5.com/ru/code/16006

#define Bid SymbolInfoDouble(_Symbol, SYMBOL_BID)
#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)

// Открывает позицию с заданным комментарием.
TICKET_TYPE PositionOpen( const int Type, const string comment )
{
  return(Type ? OrderSend(_Symbol, OP_SELL, 1, Bid, 0, Bid + inSL * _Point, Bid - inTP * _Point, comment)
              : OrderSend(_Symbol, OP_BUY, 1, Ask, 0, Ask - inSL * _Point, Ask + inTP * _Point, comment));
}

#else // #ifndef FAKE
  int OnInit() { return(INIT_FAILED); }
#endif // #ifndef FAKE #else
 
v88 #:

It's definitely not working here with your test EA, with 2 different terminals. One directly from metaquotes and one through my broker. See below, both show code 1 error:



I see 3 files at \AppData\Roaming\MetaQuotes\Terminal\Community\Calendar, events, countries and descriptions. 


The lines in your test EA, show that the calendar.bin file should be saved as "Calendar.bin" in the "Roaming\MetaQuotes\Terminal\<identifier>\MQL5\Files" folder, but it's not there. Before build 5200, they would be placed there correctly. Any ideas what could be wrong?


To ensure this isn't my setup, I installed a windows VM outside of my own network, everything clean. Downloaded the terminal, installed the Include Files plus the Calendar_Example EA. Still the same issue, error code 1, calendar.bin not being downloaded:


 
v88 #:

Any ideas what could be wrong?

Until the changes in MQL5 are fixed, I don't see the point in looking into it. Try the build below.

Новая версия платформы MetaTrader 5 build 5200: расширение OpenBLAS и усиление контроля в MQL5 - Проверил логин во вкладке Сообщество в MetaEditor
Новая версия платформы MetaTrader 5 build 5200: расширение OpenBLAS и усиление контроля в MQL5 - Проверил логин во вкладке Сообщество в MetaEditor
  • 2025.08.04
  • www.mql5.com
----------------- Открываю Метатрейдер, который давно вообще не открывал. Иду в MetaEditor - там не подключено к Git - ----------------- Проверил логин во вкладке Сообщество. То есть - пока я глядел на вкладку Сообщество в MetaEditor е - этот MetaEditor сам все сделал
 

I recently noticed that saving the entire calendar to a file for working with it in the tester started to time out after about 50 seconds.

Calendar.Set(NULL, CALENDAR_IMPORTANCE_NONE, 0, 0); // <-- тут падает на 5401 - ERR_CALENDAR_TIMEOUT (превышен лимит времени запроса),

Previously, everything worked fine and the entire calendar was downloaded to a file without any problems. I suspect that with one of the terminal releases, the timeout for CalendarValueHistory was reduced.

I checked on different terminals and different servers, although the terminal is b5327 everywhere. I also tried reducing the period. So, for a year, there is also a timeout. But for a few days, it downloads normally.

Are there any workarounds to avoid splitting calls into short periods?

 
Denis Kislicyn #:

I recently noticed that saving the entire calendar to a file for working with it in the tester started to time out after about 50 seconds.

Previously, everything worked fine and the entire calendar was downloaded to a file without any problems. I suspect that with one of the terminal releases, the timeout for CalendarValueHistory was reduced.

I checked on different terminals and different servers, although the terminal is b5327 everywhere. I also tried reducing the period. So, for a year, there is also a timeout. But for a few days, it downloads normally.

Are there any workarounds to avoid splitting calls into short periods?

I did a little research. If you pass a period longer than a month to CalendarValueHistory, the function starts to hang for about 50 seconds and then crashes due to a timeout. However, the same call, but for only one day shorter, executes in <70ms and perfectly saves about 5,000 calendar events. Something has definitely changed in it.

Auto-translation applied by moderator. If you want to post in Russian, please do so in the Russian forum, and not in the English forum. This is a multi-lingual topic, so please post in the correct forum, or else the auto-translation will not work correctly.