//+------------------------------------------------------------------+
//| OnTimer_Sample.mq5 |
//| Copyright 2018, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "Example of using the timer for calculating the trading server time"
#property description "It is recommended to run the EA at the end of a trading week before the weekend"
//+------------------------------------------------------------------+
//| EA交易初始化函数 |
//+------------------------------------------------------------------+
int OnInit()
{
//--- 创建一个1秒周期的计时器
EventSetTimer(1);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| EA交易去初始化函数 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- 完成工作后销毁计时器
EventKillTimer();
}
//+------------------------------------------------------------------+
//| EA报价函数 |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
//+------------------------------------------------------------------+
//| Timer函数 |
//+------------------------------------------------------------------+
void OnTimer()
{
//--- OnTimer()首次调用的时间
static datetime start_time=TimeCurrent();
//--- 第一次调用OnTimer()期间交易服务器的时间
static datetime start_tradeserver_time=0;
//--- 计算交易服务器时间
static datetime calculated_server_time=0;
//--- 本地PC时间
datetime local_time=TimeLocal();
//--- 目前估计的交易服务器时间
datetime trade_server_time=TimeTradeServer();
//--- 如果由于某种原因而未知服务器时间,则提前退出
if(trade_server_time==0)
return;
//--- 如果尚未设置初始交易服务器的值
if(start_tradeserver_time==0)
{
start_tradeserver_time=trade_server_time;
//--- 设置交易服务器的计算值
Print(trade_server_time);
calculated_server_time=trade_server_time;
}
else
{
//--- 增加OnTimer()第一次调用的时间
if(start_tradeserver_time!=0)
calculated_server_time=calculated_server_time+1;;
}
//---
string com=StringFormat(" Start time: %s\r\n",TimeToString(start_time,TIME_MINUTES|TIME_SECONDS));
com=com+StringFormat(" Local time: %s\r\n",TimeToString(local_time,TIME_MINUTES|TIME_SECONDS));
com=com+StringFormat("TimeTradeServer time: %s\r\n",TimeToString(trade_server_time,TIME_MINUTES|TIME_SECONDS));
com=com+StringFormat(" EstimatedServer time: %s\r\n",TimeToString(calculated_server_time,TIME_MINUTES|TIME_SECONDS));
//--- 显示图表上所有计数器的值
Comment(com);
}
|