Watch how to download trading robots for free
Find us on Twitter!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Views:
646
Rating:
(30)
Published:
2025.04.03 11:16
\MQL5\Include\fxsaber\Calendar\
String.mqh (1.77 KB) view
Event.mqh (20.88 KB) view
Calendar.mqh (30.15 KB) view
DST.mqh (11.46 KB) view
\MQL5\Experts\
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

MetaTrader5 has an updated volumetric history of fundamental calendar events, any data of which can be accessed programmatically.


This library allows you to conveniently work with this data. In particular, to use them in the Tester and in real trading.


Working with the library is shown in the form of comments of the source code of the examples.


Obtaining historical data.

// The script outputs historical data.

#include <fxsaber\Calendar\Calendar.mqh> // Calendar - fundamental analysis on history and real-time.

void OnStart()
{
  CALENDAR Calendar;
  
  // Took events for all (NULL) currencies starting with the lowest (NONE) importance.
  const int Size = Calendar.Set(NULL, CALENDAR_IMPORTANCE_NONE, D'2020.12.07', D'2020.12.08');
  
  // Printed them out.
  for (int i = 0; i < Size; i++)
    Print(Calendar[i].ToString());
}


Result.

2020.12.07 AllDay EUR 0 День Конституции(constitution-day), Испания(ES) |  |  |  | 
2020.12.07 00:00 AUD 3 Выступление председателя Резервного Банка Австралии Лоу(rba-governor-lowe-speech), Австралия(AU) |  |  |  | 
2020.12.07 01:50 JPY 1 Международные резервы(jp-foreign-reserves), Япония(JP) | $1384.6 B |  | $1384.4 B | 
2020.12.07 02:30 AUD 1 Количество объявлений о вакансиях от ANZ м/м(anz-job-advertisements-mm), Австралия(AU) | 13.9% | 0.8% | 9.4% | 
2020.12.0705:00 CNY 1 Объем импорта USD г/г(imports-usd-yy), Китай(CN) | 4.5% | 4.4% | 4.7% | 
2020.12.0705:00 CNY 1 Объем экспорта USD г/г(exports-usd-yy), Китай(CN) | 21.1% | 3.6% | 11.4% | 
2020.12.0705:00 CNY 2 Торговый баланс(trade-balance), Китай(CN) | ¥507.1 B | ¥271.31 B | ¥401.75 B | 
2020.12.0705:00 CNY 2 Торговый баланс USD(trade-balance-usd), Китай(CN) | $75.42 B | $52.55 B | $58.44 B | 
2020.12.0705:00 CNY 1 Объем импорта г/г(imports-yy), Китай(CN) | -0.8% | -0.6% | 0.9% | 
2020.12.0705:00 CNY 1 Объем экспорта г/г(exports-yy), Китай(CN) | 14.9% | 2.2% | 7.6% | 
2020.12.07 07:00 JPY 1 Индекс совпадающих индикаторов(coincident-index), Япония(JP) | 89.7 | 81.8 | 81.1 | 84.8
2020.12.07 07:00 JPY 1 Индекс ведущих экономических индикаторов(leading-index), Япония(JP) | 93.8 | 92.7 | 92.5 | 93.3
2020.12.07 07:00 JPY 1 Индекс совпадающих индикаторов Японии м/м(coincident-index-mm), Япония(JP) | 4.9% |  | 1.7% | 2.4%
2020.12.07 07:00 JPY 1 Индекс ведущих экономических индикаторов м/м(leading-index-mm), Япония(JP) | 0.5% |  | 4.0% | 4.2%
2020.12.07 08:00 ZAR 1 Валовые международные резервы(gross-international-reserves), Южно-Африканская Республика(ZA) | $53.76 B | $54.129 B | $53.658 B | 
2020.12.07 08:00 ZAR 1 Чистые международные резервы(net-international-reserves), Южно-Африканская Республика(ZA) | $51.257 B | $52.719 B | $51.364 B | 
2020.12.07 09:00 EUR 2 Промышленное производство г/г(industrial-production-yy), Германия(DE) | -3.0% | -11.4% | -7.3% | -6.7%
2020.12.07 09:00 EUR 2 Промышленное производство м/м(industrial-production-mm), Германия(DE) | 3.2% | 7.7% | 1.6% | 2.3%
2020.12.07 09:00 NOK 1 Производство в обрабатывающей промышленности м/м(manufacturing-production-mm), Норвегия(NO) | 0.6% | 0.1% | -0.5% | 
2020.12.07 09:00 NOK 1 Производство в обрабатывающей промышленности г/г(manufacturing-production-yy), Норвегия(NO) | -2.7% | -3.3% | -3.4% | 
2020.12.07 09:00 NOK 1 Промышленное производство м/м(industrial-production-mm), Норвегия(NO) | -3.5% | 0.0% | -1.7% | -1.6%
2020.12.07 09:00 NOK 1 Промышленное производство г/г(industrial-production-yy), Норвегия(NO) | 0.0% | 6.9% | 6.3% | 

    You can compare it with the MT5-Terminal itself.


    Getting upcoming events.

    // The script displays upcoming events.
    
    #include <fxsaber\Calendar\Calendar.mqh> // Calendar - fundamental analysis on history and real-time.
    
    void OnStart()
    {
      CALENDAR Calendar;
      
      string Currencies[2];
      
      // Get the currencies of the current character.
      Currencies[0] = ::SymbolInfoString(_Symbol, SYMBOL_CURRENCY_BASE);
      Currencies[1] = ::SymbolInfoString(_Symbol, SYMBOL_CURRENCY_PROFIT);
        
      // Took upcoming important events by symbol currencies.
      Calendar.Set(Currencies);
      
      Print(Calendar.ToString()); // Printed them out.
    }

    Such embedding in information systems allows to inform about important upcoming calendar events in Expert Advisors/indicators.


    Backtest on fundamental data.


    Below is an Expert Advisor that trades NonFarm Payrolls by comparing current and forecast values.

    // Expert Advisor for trading in MT4/5-Tester on the history of fundamental data.
    
    #define  CALENDAR_FILENAME "Calendar.bin" // File name for reading/writing the Calendar.
    #property tester_file CALENDAR_FILENAME  // Specifies that MT5-Tester picks up this file.
    
    #include <fxsaber\Calendar\Calendar.mqh> // Calendar - fundamental analysis on history and real-time.
    
    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; // Object with calendar data.
    
    int OnInit()
    {      
      bool Res = false;
      
      if (MQLInfoInteger(MQL_TESTER)) // If working in Tester
      {
        Res = Calendar.Load(CALENDAR_FILENAME) &&      // Loaded the events from the file.
              Calendar.FilterByCurrency(inCurrency) && // Applied a currency filter.
              Calendar.FilterByName(inFilterName);     // Applied a filter on the event name.
        
        if (!Res)                                      // If there are problems with the loaded data,
          Print("Run the EA in the MT5-Terminal!");    // reported that you need to get them by running the EA in MT5-Terminal.
      }
    #ifdef __MQL5__
      // Working in the Terminal.
      else if (Calendar.Set(NULL, CALENDAR_IMPORTANCE_NONE, 0, 0) && // Loaded absolutely all events (history + future) from MT5-Terminal.
               Calendar.Save(CALENDAR_FILENAME))                     // Save them to a file.
        MessageBox("You can run the EA in the MT4/5-Tester.");       // Reported that we can now work in MT4/5-Tester.
    #endif // #ifdef __MQL5__
    
      return(!Res);
    }
    
    void OnTick()
    {
      static int Pos = Calendar.GetPosAfter(TimeCurrent()); // Get the event position in the Calendar, which is right after the current time.
      
      if ((Pos < Calendar.GetAmount()) &&       // If you haven't gone beyond the Calendar
          (Calendar[Pos].time < TimeCurrent())) // and the current time has passed the event.
      {        
        const EVENT Event = Calendar[Pos];      // Received the corresponding event.
        
        if ((Event.Actual != LONG_MIN) && (Event.Forecast != LONG_MIN)) // If the current and forecast values of the event are set
        {
          Print(Event.ToString()); // Print this event in its entirety.
    
          if (Event.Actual > Event.Forecast)                                                                          // If the current value is greater than the forecast value,
            PositionOpen(inReverse, "Act.(" + Event.ActualToString() + ")>(" + Event.ForecastToString() + ")For.");   // open a position of one direction.
          else
            PositionOpen(!inReverse, "Act.(" + Event.ActualToString() + ")<=(" + Event.ForecastToString() + ")For."); // Otherwise, another direction.
        }
                
        Pos = Calendar.GetPosAfter(TimeCurrent(), Pos); // Get the event position in the Calendar, which is right after the current time.
      }
    }
    
    #include <MT4Orders.mqh> // https://www.mql5.com/en/code/16006
    
    #define  Bid SymbolInfoDouble(_Symbol, SYMBOL_BID)
    #define  Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)
    
    // Opens a position with the specified comment.
    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));
    }

    Run it once in MT5-Terminal to save all historical data (~60 Mb). After that they will be available in the Tester.


    Result (for six years at H1 opening prices).


    Features.

    • Does not use DLLs, can run in the Marketplace.
    • Cross-platform operation: in MT4 get data from file.

    Translated from Russian by MetaQuotes Ltd.
    Original code: https://www.mql5.com/ru/code/32430

    SingleTesterCache SingleTesterCache

    Tester's single pass data.

    PSAR Zigzag (Non lagging) PSAR Zigzag (Non lagging)

    A zigzag based on the trend change of the parabolic sar

    Detecting the start of a new bar or candle Detecting the start of a new bar or candle

    Detecting the start of a new bar or candle in an Expert Advisor's OnTick() event handler.

    New Candle or Bar formation. New Candle or Bar formation.

    This Bot detects the open of a new candle on any set timeframe, thereby making it easier to run a one-time code, place trades and call other functions. The code is written in the OnTick() function.