//+------------------------------------------------------------------+
//| ShowTimeDiff.mq5 |
//| 显示 TimeTradeServer 与本地时差 |
//+------------------------------------------------------------------+
#property copyright "Your Name"
#property link "https://www.example.com"
#property version "1.00"
#property script_show_inputs
//+------------------------------------------------------------------+
//| 脚本主函数 |
//+------------------------------------------------------------------+
void OnStart()
{
string labelName = "TimeDiffLabel";
int chartId = ChartID();
// --- 1. 获取时间并计算时差 ---
datetime serverTime = TimeTradeServer(); // 交易服务器估计当前时间
datetime localTime = TimeLocal(); // 本地计算机时间
int diffSeconds = (int)(serverTime - localTime);
int diffHours = diffSeconds / 3600;
int diffMinutes = (diffSeconds % 3600) / 60;
// --- 2. 格式化显示文本 ---
string displayText;
if(diffHours >= 0)
displayText = StringFormat("服务器快 %02d 小时 %02d 分钟", diffHours, diffMinutes);
else
displayText = StringFormat("服务器慢 %02d 小时 %02d 分钟", -diffHours, -diffMinutes);
// --- 3. 删除旧标签(如果存在)---
ObjectDelete(chartId, labelName);
// --- 4. 创建新标签 ---
if(!ObjectCreate(chartId, labelName, OBJ_LABEL, 0, 0, 0))
{
Print("创建标签失败,错误代码: ", GetLastError());
return;
}
// --- 5. 设置标签属性 ---
// 锚定到图表右上角
ObjectSetInteger(chartId, labelName, OBJPROP_XDISTANCE, 10); // 距右边缘10像素
ObjectSetInteger(chartId, labelName, OBJPROP_YDISTANCE, 10); // 距上边缘10像素
ObjectSetInteger(chartId, labelName, OBJPROP_CORNER, CORNER_RIGHT_UPPER);
// 文字样式
ObjectSetString(chartId, labelName, OBJPROP_TEXT, displayText);
ObjectSetString(chartId, labelName, OBJPROP_FONT, "Arial");
ObjectSetInteger(chartId, labelName, OBJPROP_FONTSIZE, 12);
ObjectSetInteger(chartId, labelName, OBJPROP_COLOR, clrYellow);
ObjectSetInteger(chartId, labelName, OBJPROP_BACK, false);
ObjectSetInteger(chartId, labelName, OBJPROP_SELECTABLE, false);
ObjectSetInteger(chartId, labelName, OBJPROP_HIDDEN, false);
// 设置Z序,确保显示在最上层
ObjectSetInteger(chartId, labelName, OBJPROP_ZORDER, 0);
// --- 6. 刷新图表 ---
ChartRedraw(chartId);
Print("时差显示已更新: ", displayText);
Print("服务器时间: ", TimeToString(serverTime));
Print("本地时间: ", TimeToString(localTime));
} |