Je vous propose ici un indicateur qui affiche les horaires locales de différentes villes (New york, Londres, Paris, Sydney, Shanghai, Tokyo).
La principale différence avec les autres indicateurs est qu'il ne se base pas sur un décalage horaire empirique plus ou moins configurable et qui ne tient pas compte de tous les paramètres et notamment de l'heure d'été/hiver.
L'heure précise de chaque ville est donc téléchargée directement sur le Net à l'initialisation pour calculer le décalage exact par rapport à l'heure du broker. Chaque horloge est ensuite mise à jour en fonction de ce décalage.
Une synchro est faite au premier tick de chaque heure.
De plus, chaque ville est mise en surbrillance lorsque le marché boursier y est ouvert et change de couleur 15mn avant sa fermeture.
Have fun !
La principale différence avec les autres indicateurs est qu'il ne se base pas sur un décalage horaire empirique plus ou moins configurable et qui ne tient pas compte de tous les paramètres et notamment de l'heure d'été/hiver.
L'heure précise de chaque ville est donc téléchargée directement sur le Net à l'initialisation pour calculer le décalage exact par rapport à l'heure du broker. Chaque horloge est ensuite mise à jour en fonction de ce décalage.
Une synchro est faite au premier tick de chaque heure.
De plus, chaque ville est mise en surbrillance lorsque le marché boursier y est ouvert et change de couleur 15mn avant sa fermeture.
Code
//+------------------------------------------------------------------+
//| WorldClock.mq4 |
//| Copyright 2012, Nicolas Tuffier |
//| http://www.furyweb.fr/forex/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, Nicolas Tuffier"
#property link "http://www.furyweb.fr/forex/"
#property indicator_chart_window
#define N_CITIES 6
#define OPEN_MASK 1
#define ENDING_MASK 2
extern int corner = 1;
extern color textCol = Silver;
int hour;
bool bWinInetDebug = false;
bool EnableLogging = false;
int logHandle;
int cityId[N_CITIES] = {136, 179, 195, 240, 237, 248};
string cityName[N_CITIES] = {"London", "New york", "Paris", "Sydney", "Shanghai", "Tokyo"};
string openHours[N_CITIES] = {"08:00-16:30", "09:30-16:00", "09:00-17:30", "10:00-16:00", "09:30-11:30,13:00-15:00", "09:00-11:00,12:30-15:00"};
datetime delta[N_CITIES];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init() {
string webData;
string date;
string name;
int i, x, y, pos = 0;
hour = TimeHour(TimeCurrent());
x = 5;
y = 5;
name = "GMT_label";
ObjectCreate(name, OBJ_LABEL, 0, 0, 0.0);
ObjectSet(name, OBJPROP_CORNER, corner);
ObjectSetText(name, "GMT", 9, "Cambria", textCol);
switch (corner) {
case 0:
case 2: ObjectSet(name, OBJPROP_XDISTANCE, x); break;
case 1:
case 3: ObjectSet(name, OBJPROP_XDISTANCE, x + 40); break;
}
ObjectSet(name, OBJPROP_YDISTANCE, y);
name = "GMT_hour";
ObjectCreate(name, OBJ_LABEL, 0, 0, 0.0);
ObjectSet(name, OBJPROP_CORNER, corner);
ObjectSetText(name, TimeToStr(TimeGMT(), TIME_MINUTES), 8, "Lucida Console", textCol);
switch (corner) {
case 0:
case 2: ObjectSet(name, OBJPROP_XDISTANCE, x + 60); break;
case 1:
case 3: ObjectSet(name, OBJPROP_XDISTANCE, x); break;
}
ObjectSet(name, OBJPROP_YDISTANCE, y + 2);
for (i = 0; i < N_CITIES; i++) {
webData = "";
GrabWeb(StringConcatenate("http://free.timeanddate.com/clock/i3aibqez/n", cityId[i], "/tluk/tt0/tw0/tm3/td2/th1/tb2"), webData);
date = GetTextAfter(webData, "span id=t1", pos); pos = 0;
delta[i] = StrToTime(StringConcatenate(StringSubstr(date, 6, 4), ".", StringSubstr(date, 3, 2), ".", StringSubstr(date, 0, 2), StringSubstr(date, 10))) - TimeGMT();
// delta[i] -= MathMod(delta[i], 60);
y += 12;
name = StringConcatenate(cityName[i], "_label");
ObjectCreate(name, OBJ_LABEL, 0, 0, 0.0);
ObjectSet(name, OBJPROP_CORNER, corner);
ObjectSetText(name, cityName[i], 9, "Cambria", textCol);
switch (corner) {
case 0:
case 2: ObjectSet(name, OBJPROP_XDISTANCE, x); break;
case 1:
case 3: ObjectSet(name, OBJPROP_XDISTANCE, x + 40); break;
}
ObjectSet(name, OBJPROP_YDISTANCE, y);
name = StringConcatenate(cityName[i], "_hour");
ObjectCreate(name, OBJ_LABEL, 0, 0, 0.0);
ObjectSet(name, OBJPROP_CORNER, corner);
ObjectSetText(name, TimeToStr(TimeGMT() + delta[i], TIME_MINUTES), 8, "Lucida Console", textCol);
switch (corner) {
case 0:
case 2: ObjectSet(name, OBJPROP_XDISTANCE, x + 60); break;
case 1:
case 3: ObjectSet(name, OBJPROP_XDISTANCE, x); break;
}
ObjectSet(name, OBJPROP_YDISTANCE, y + 2);
}
return(0);
}
string GetTextAfter(string data, string key, int &start, string prevCar=">", string afterCar="<") {
string s;
int p = StringFind(data, key, start);
// Print("key ", key, " found at ", p);
if (p == -1)
return("");
p = StringFind(data, prevCar, p) + 1;
// Print(prevCar, " found at ", p);
if (p == -1)
return("");
start = StringFind(data, afterCar, p);
if (start == p) {
start++;
// Print("Empty");
return("");
}
// Print(afterCar, " found at ", start);
s = StringSubstr(data, p, start - p);
if (s != " ") {
p = StringFind(s, " ");
while (p != -1) {
if (p > 0)
s = StringConcatenate(StringSubstr(s, 0, p), " ", StringSubstr(s, p + 6));
else
s = StringSubstr(s, 6);
p = StringFind(s, " ");
}
} //*/
// Print("Debug:", s, " ", start);
return(s);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
for (int i = 0; i < N_CITIES; i++)
ObjectDelete(StringConcatenate(cityName[i], "_hour"));
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start() {
//----
int n, i, pos, status;
string hours[2], name, log = "";
datetime open, close, GMT = TimeGMT();
if (hour != TimeHour(TimeCurrent())) {
deinit();
init();
return(0);
}
for (i = 0; i < N_CITIES; i++) {
status = 0;
name = StringConcatenate(cityName[i], "_hour");
ObjectSetText(name, TimeToStr(TimeGMT() + delta[i], TIME_MINUTES), 8, "Lucida Console", textCol);
pos = StringFind(openHours[i], ",");
hours[0] = StringSubstr(openHours[i], 0, pos);
hours[1] = StringSubstr(openHours[i], pos);
for (n = 0; n < 2; n++) {
pos = StringFind(openHours[i], "-");
open = StrToTime(StringSubstr(hours[n], 0, pos)) - delta[i];
close = StrToTime(StringSubstr(hours[n], pos)) - delta[i];
if (GMT > open && GMT < close)
status |= OPEN_MASK;
if (GMT > close - 900 && GMT < close)
status |= ENDING_MASK;
}
if (status & OPEN_MASK == OPEN_MASK)
if (status & ENDING_MASK == ENDING_MASK)
ObjectSet(name, OBJPROP_COLOR, Orange);
else
ObjectSet(name, OBJPROP_COLOR, LimeGreen);
else
ObjectSet(name, OBJPROP_COLOR, FireBrick);
}
//----
return(0);
}
//=================================================================================================
//= GrabWeb Functions =
//=================================================================================================
// Main Webscraping function
// ~~~~~~~~~~~~~~~~~~~~~~~~~
// bool GrabWeb(string strUrl, string& strWebPage)
// returns the text of any webpage. Returns false on timeout or other error
//
// Parsing functions
// ~~~~~~~~~~~~~~~~~
// string GetData(string strWebPage, int nStart, string strLeftTag, string strRightTag, int& nPos)
// obtains the text between two tags found after nStart, and sets nPos to the end of the second tag
//
// void Goto(string strWebPage, int nStart, string strTag, int& nPos)
// Sets nPos to the end of the first tag found after nStart
int hSession_IEType;
int hSession_Direct;
int Internet_Open_Type_Preconfig = 0;
int Internet_Open_Type_Direct = 1;
int Internet_Open_Type_Proxy = 3;
int Buffer_LEN = 13;
#import "wininet.dll"
#define INTERNET_FLAG_PRAGMA_NOCACHE 0x00000100 // Forces the request to be resolved by the origin server, even if a cached copy exists on the proxy.
#define INTERNET_FLAG_NO_CACHE_WRITE 0x04000000 // Does not add the returned entity to the cache.
#define INTERNET_FLAG_RELOAD 0x80000000 // Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
int InternetOpenA(
string sAgent,
int lAccessType,
string sProxyName="",
string sProxyBypass="",
int lFlags=0
);
int InternetOpenUrlA(
int hInternetSession,
string sUrl,
string sHeaders="",
int lHeadersLength=0,
int lFlags=0,
int lContext=0
);
int InternetReadFile(
int hFile,
string sBuffer,
int lNumBytesToRead,
int& lNumberOfBytesRead[]
);
int InternetCloseHandle(
int hInet
);
#import
int hSession(bool Direct)
{
string InternetAgent;
if (hSession_IEType == 0)
{
InternetAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461)";
hSession_IEType = InternetOpenA(InternetAgent, Internet_Open_Type_Preconfig, "0", "0", 0);
hSession_Direct = InternetOpenA(InternetAgent, Internet_Open_Type_Direct, "0", "0", 0);
}
if (Direct)
{
return(hSession_Direct);
}
else
{
return(hSession_IEType);
}
}
bool GrabWeb(string strUrl, string& strWebPage)
{
int hInternet;
int iResult;
int lReturn[]={1};
string sBuffer="x";
int bytes;
hInternet = InternetOpenUrlA(hSession(FALSE), strUrl, "0", 0,
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_RELOAD, 0);
if (bWinInetDebug)
Log("hInternet: " + hInternet);
if (hInternet == 0)
return(false);
iResult = InternetReadFile(hInternet, sBuffer, Buffer_LEN, lReturn);
if (bWinInetDebug)
Log("iResult: " + iResult);
if (bWinInetDebug)
Log("lReturn: " + lReturn[0]);
if (bWinInetDebug)
Log("iResult: " + iResult);
if (bWinInetDebug)
Log("sBuffer: " + sBuffer);
if (iResult == 0)
return(false);
bytes = lReturn[0];
strWebPage = StringSubstr(sBuffer, 0, lReturn[0]);
// If there's more data then keep reading it into the buffer
while (lReturn[0] != 0)
{
iResult = InternetReadFile(hInternet, sBuffer, Buffer_LEN, lReturn);
if (lReturn[0]==0)
break;
bytes = bytes + lReturn[0];
strWebPage = strWebPage + StringSubstr(sBuffer, 0, lReturn[0]);
}
iResult = InternetCloseHandle(hInternet);
if (iResult == 0)
return(false);
if (bWinInetDebug)
{
Log("iResult: " + iResult);
int handle = FileOpen("Grabweb.htm",FILE_BIN|FILE_READ|FILE_WRITE);
FileWriteString(handle,strWebPage,StringLen(strWebPage));
FileClose(handle);
}
return(true);
}
//=================================================================================================
//= LogUtils Functions =
//=================================================================================================
void OpenLog(string strName)
{
if (!EnableLogging)
return;
if (logHandle <= 0)
{
string strMonthPad = "";
string strDayPad = "";
if (Month() < 10)
strMonthPad = "0";
if (Day() < 10)
strDayPad = "0";
string strFilename = StringConcatenate(strName, "_", Year(), strMonthPad, Month(), strDayPad, Day(), "_log.txt");
logHandle = FileOpen(strFilename,FILE_CSV|FILE_READ|FILE_WRITE);
Print("logHandle =================================== ", logHandle);
}
if (logHandle > 0)
{
FileFlush(logHandle);
FileSeek(logHandle, 0, SEEK_END);
}
}
void Log(string msg)
{
if (!EnableLogging)
return;
if (logHandle <= 0)
return;
msg = TimeToStr(TimeCurrent(),TIME_DATE|TIME_MINUTES|TIME_SECONDS) + " " + msg;
FileWrite(logHandle,msg);
}
//=================================================================================================
//= Timezone Functions =
//=================================================================================================
#import "kernel32.dll"
int GetTimeZoneInformation(int& TZInfoArray[]);
#import
#define TIME_ZONE_ID_UNKNOWN 0
#define TIME_ZONE_ID_STANDARD 1
#define TIME_ZONE_ID_DAYLIGHT 2
// Local timezone in hours, adjusting for daylight saving
double TimeZoneLocal()
{
int TZInfoArray[43];
switch(GetTimeZoneInformation(TZInfoArray))
{
case TIME_ZONE_ID_UNKNOWN:
Print("Error obtaining PC timezone from GetTimeZoneInformation in kernel32.dll. Returning 0");
return(0);
case TIME_ZONE_ID_STANDARD:
return(TZInfoArray[0]/(-60.0));
case TIME_ZONE_ID_DAYLIGHT:
return((TZInfoArray[0]+TZInfoArray[42])/(-60.0));
default:
Print("Unkown return value from GetTimeZoneInformation in kernel32.dll. Returning 0");
return(0);
}
}
// Server timezone in hours
double TimeZoneServer()
{
int ServerToLocalDiffMinutes = (TimeCurrent()-TimeLocal())/60;
// round to nearest 30 minutes to allow for inaccurate PC clock
int nHalfHourDiff = MathRound(ServerToLocalDiffMinutes/30.0);
ServerToLocalDiffMinutes = nHalfHourDiff*30;
return(TimeZoneLocal() + ServerToLocalDiffMinutes/60.0);
}
// Uses local PC time, local PC timezone, and server time to calculate GMT time at arrival of last tick
datetime TimeGMT()
{
// two ways of calculating
// 1. From PC time, which may not be accurate
// 2. From server time. Most accurate except when server is down on weekend
datetime dtGmtFromLocal = TimeLocal() - TimeZoneLocal()*3600;
datetime dtGmtFromServer = TimeCurrent() - TimeZoneServer()*3600;
// return local-derived value if server value is out by more than 5 minutes, eg during weekend
if (dtGmtFromLocal > dtGmtFromServer + 300)
{
return(dtGmtFromLocal);
}
else
{
return(dtGmtFromServer);
}
}
//+------------------------------------------------------------------+
Have fun !