//+------------------------------------------------------------------+ //| OfdSyncCommon.mqh: signing, JSON and transport for OfdSync | //| (MQL4 and MQL5). | //| | //| READ-ONLY BY CONSTRUCTION. Nothing in OfdSync sends, changes, | //| closes or deletes an order or a position, and nothing imports a | //| DLL; a check on every build refuses any source that would. | //+------------------------------------------------------------------+ #ifndef OFDSYNC_COMMON_MQH #define OFDSYNC_COMMON_MQH #define OFDSYNC_VERSION "1.1.0" #define OFDSYNC_TIMEOUT_MS 15000 #define OFDSYNC_BACKOFF_MIN 5 #define OFDSYNC_BACKOFF_MAX 300 #define OFDSYNC_PAGE 1000 //--- State shared by both platforms. long g_cursorTicket = 0; // from the last answer: never from what was sent long g_cursorTime = 0; datetime g_nextPushAt = 0; // local clock (TimeLocal), set by next_seconds or the backoff int g_backoff = 0; // seconds of the current backoff, 0 when healthy bool g_stopped = false; // a refusal the user must fix (key revoked, wrong secret, other account) datetime g_holdUntil = 0; // after a 429: no push before this, not even on a trade long g_awaitTicket = 0; // a history page was sent up to here (MT5 deal ticket) ... long g_awaitTime = 0; // ... or here (MT4 close time) and is not stored yet datetime g_awaitSince = 0; // when that page was sent; 0 when nothing is awaited bool g_awaitMore = false; // that page's "more", repeated by the heartbeats while it is awaited string g_status = "starting"; //+------------------------------------------------------------------+ //| JSON helpers | //+------------------------------------------------------------------+ string OfdJsonString(const string value) { string out = "\""; int n = StringLen(value); for(int i = 0; i < n; i++) { ushort c = StringGetCharacter(value, i); if(c == '"') out += "\\\""; else if(c == '\\') out += "\\\\"; else if(c < 0x20) out += " "; else out += ShortToString(c); } return out + "\""; } //--- Amounts travel as decimal strings: no float formatting, no exponent. string OfdJsonAmount(const double value) { string s = DoubleToString(value, 8); if(StringFind(s, ".") >= 0) { int len = StringLen(s); while(len > 0 && StringGetCharacter(s, len - 1) == '0') len--; if(len > 0 && StringGetCharacter(s, len - 1) == '.') len--; s = StringSubstr(s, 0, len); } if(s == "-0" || s == "") s = "0"; return "\"" + s + "\""; } string OfdJsonLong(const long value) { return IntegerToString(value); } string OfdJsonBool(const bool value) { return value ? "true" : "false"; } //--- The integer after "key": in a flat JSON answer, or fallback when absent. long OfdJsonReadLong(const string json, const string key, const long fallback) { int at = StringFind(json, "\"" + key + "\":"); if(at < 0) return fallback; at += StringLen(key) + 3; string digits = ""; int n = StringLen(json); for(int i = at; i < n; i++) { ushort c = StringGetCharacter(json, i); if((c >= '0' && c <= '9') || (c == '-' && digits == "")) digits += ShortToString(c); else if(c == ' ' && digits == "") continue; else break; } return digits == "" ? fallback : StringToInteger(digits); } int OfdHexDigit(const ushort c) { if(c >= '0' && c <= '9') return c - '0'; if(c >= 'a' && c <= 'f') return c - 'a' + 10; if(c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } //--- The string after "key": in a flat JSON answer, JSON escapes decoded (\" \\ \/ \b \f \n \r \t \uXXXX), or "" when //--- absent or unterminated. A \u pair for a character beyond the BMP stays a surrogate pair, which is how MQL strings hold it. string OfdJsonReadString(const string json, const string key) { int at = StringFind(json, "\"" + key + "\":\""); if(at < 0) return ""; at += StringLen(key) + 4; string out = ""; int n = StringLen(json); for(int i = at; i < n; i++) { ushort c = StringGetCharacter(json, i); if(c == '"') return out; if(c != '\\') { out += ShortToString(c); continue; } i++; if(i >= n) break; c = StringGetCharacter(json, i); if(c == 'n') out += "\n"; else if(c == 't') out += "\t"; else if(c == 'r' || c == 'b' || c == 'f') out += " "; else if(c == 'u') { int code = 0; bool valid = i + 4 < n; for(int k = 1; valid && k <= 4; k++) { int digit = OfdHexDigit(StringGetCharacter(json, i + k)); if(digit < 0) valid = false; else code = code * 16 + digit; } if(!valid) { out += "?"; continue; } i += 4; out += code < 0x20 ? " " : ShortToString((ushort)code); } else out += ShortToString(c); // \" \\ \/ (and any other escaped character, as itself) } return ""; } //+------------------------------------------------------------------+ //| HMAC-SHA256 (RFC 2104). The key is the secret's 64 hex characters | //| as ASCII bytes: exactly one SHA-256 block, so no key hashing. | //+------------------------------------------------------------------+ bool OfdSha256(const uchar &data[], uchar &digest[]) { uchar none[]; return CryptEncode(CRYPT_HASH_SHA256, data, none, digest) == 32; } string OfdHex(const uchar &bytes[]) { string hex = ""; int n = ArraySize(bytes); for(int i = 0; i < n; i++) hex += StringFormat("%02x", bytes[i]); return hex; } //--- UTF-8 bytes of a string, without the terminating zero StringToCharArray appends. int OfdUtf8(const string text, uchar &bytes[]) { int n = StringToCharArray(text, bytes, 0, WHOLE_ARRAY, CP_UTF8); if(n > 0 && bytes[n - 1] == 0) n--; ArrayResize(bytes, n); return n; } //--- The same bytes as char[], which WebRequest takes. int OfdUtf8Chars(const string text, char &bytes[]) { int n = StringToCharArray(text, bytes, 0, WHOLE_ARRAY, CP_UTF8); if(n > 0 && bytes[n - 1] == 0) n--; ArrayResize(bytes, n); return n; } string OfdHmacSha256Hex(const string secret, const uchar &message[]) { uchar key[]; OfdUtf8(secret, key); if(ArraySize(key) > 64) return ""; ArrayResize(key, 64); // zero-padded to the block size int msgLen = ArraySize(message); uchar inner[]; ArrayResize(inner, 64 + msgLen); for(int i = 0; i < 64; i++) inner[i] = (uchar)(key[i] ^ 0x36); for(int i = 0; i < msgLen; i++) inner[64 + i] = message[i]; uchar innerDigest[]; if(!OfdSha256(inner, innerDigest)) return ""; uchar outer[]; ArrayResize(outer, 96); for(int i = 0; i < 64; i++) outer[i] = (uchar)(key[i] ^ 0x5c); for(int i = 0; i < 32; i++) outer[64 + i] = innerDigest[i]; uchar digest[]; if(!OfdSha256(outer, digest)) return ""; return OfdHex(digest); } //+------------------------------------------------------------------+ //| Transport | //+------------------------------------------------------------------+ void OfdBackoff(const string why) { g_backoff = g_backoff == 0 ? OFDSYNC_BACKOFF_MIN : (int)MathMin(g_backoff * 2, OFDSYNC_BACKOFF_MAX); g_nextPushAt = TimeLocal() + g_backoff; g_status = why + "; retrying in " + IntegerToString(g_backoff) + " s"; Print("OfdSync: ", g_status); } void OfdStop(const string why) { g_stopped = true; g_status = "stopped: " + why; Print("OfdSync: ", g_status); Alert("OfdSync stopped: ", why); } //--- The account number, 0 while the terminal is not logged in to a trading account. long OfdLogin() { #ifdef __MQL4__ return (long)AccountNumber(); #else return AccountInfoInteger(ACCOUNT_LOGIN); #endif } //--- Not logged in: the server refuses login 0, so nothing is built or sent. Called on every timer tick, so the first //--- push goes out on the tick after the login, with no backoff to wait out. bool OfdLoggedIn() { if(OfdLogin() > 0) return true; const string waiting = "not logged in to a trading account; waiting"; if(g_status != waiting) { g_status = waiting; Print("OfdSync: ", g_status); } return false; } //--- Signs and posts one payload; applies the answer to the cursor, the cadence and the state. void OfdPost(const string endpoint, const string secret, const string body) { char payload[]; OfdUtf8Chars(body, payload); string timestamp = IntegerToString((long)TimeGMT()); uchar signedBytes[]; OfdUtf8(timestamp + "." + body, signedBytes); string signature = OfdHmacSha256Hex(secret, signedBytes); if(signature == "") { OfdStop("the secret input is not a connection-key secret"); return; } string headers = "Content-Type: application/json\r\n" + "X-OFD-Timestamp: " + timestamp + "\r\n" + "X-OFD-Signature: " + signature + "\r\n"; char answer[]; string answerHeaders; ResetLastError(); int status = WebRequest("POST", endpoint, headers, OFDSYNC_TIMEOUT_MS, payload, answer, answerHeaders); if(status == -1) { int err = GetLastError(); if(err == 4060 || err == 4014) OfdBackoff("WebRequest is not allowed for this URL: add it in Tools > Options > Expert Advisors"); else OfdBackoff("network error " + IntegerToString(err)); return; } string json = CharArrayToString(answer, 0, WHOLE_ARRAY, CP_UTF8); string error = OfdJsonReadString(json, "error"); if(status >= 200 && status < 300) { g_backoff = 0; // The server's cursor, always, never the EA's own: it may be behind what was sent (a batch still queued) or // back at zero (a new key), and history after it is sent again either way. g_cursorTicket = OfdJsonReadLong(json, "ticket", g_cursorTicket); g_cursorTime = OfdJsonReadLong(json, "time", g_cursorTime); if(g_awaitSince > 0 && (g_awaitTicket > 0 ? g_cursorTicket >= g_awaitTicket : g_cursorTime >= g_awaitTime)) g_awaitSince = 0; // the page sent last is stored: the next one may go long next = OfdJsonReadLong(json, "next_seconds", 60); g_nextPushAt = TimeLocal() + (int)(next < 1 ? 1 : next); g_status = "connected, last push " + TimeToString(TimeLocal(), TIME_DATE | TIME_SECONDS); return; } if(status == 429) { long retry = OfdJsonReadLong(json, "next_seconds", 60); g_nextPushAt = TimeLocal() + (int)(retry < 1 ? 1 : retry); g_holdUntil = g_nextPushAt; g_status = "rate limited"; return; } if(status == 401 && error == "stale_timestamp") { OfdBackoff("the computer clock is more than 5 minutes off; correct it"); return; } if(status == 401 || (status == 409 && error != "busy")) { OfdStop(error + ": " + OfdJsonReadString(json, "message")); return; } if(status == 400 || status == 413 || status == 422) { // A payload the server cannot take will not get better by itself: report and slow down at once. g_backoff = OFDSYNC_BACKOFF_MAX; g_nextPushAt = TimeLocal() + OFDSYNC_BACKOFF_MAX; g_status = "refused (" + error + "): " + OfdJsonReadString(json, "message") + "; retrying in " + IntegerToString(OFDSYNC_BACKOFF_MAX) + " s"; Print("OfdSync: ", g_status); return; } OfdBackoff("server answered " + IntegerToString(status)); } //--- Shared parts of every payload. string OfdAccountJson() { long mode = AccountInfoInteger(ACCOUNT_TRADE_MODE); string isDemo = mode == ACCOUNT_TRADE_MODE_REAL ? "false" : "true"; return "{\"currency\":" + OfdJsonString(AccountInfoString(ACCOUNT_CURRENCY)) + ",\"leverage\":" + OfdJsonLong(AccountInfoInteger(ACCOUNT_LEVERAGE)) + ",\"is_demo\":" + isDemo + ",\"balance\":" + OfdJsonAmount(AccountInfoDouble(ACCOUNT_BALANCE)) + ",\"equity\":" + OfdJsonAmount(AccountInfoDouble(ACCOUNT_EQUITY)) + ",\"margin\":" + OfdJsonAmount(AccountInfoDouble(ACCOUNT_MARGIN)) + ",\"credit\":" + OfdJsonAmount(AccountInfoDouble(ACCOUNT_CREDIT)) + "}"; } string OfdTerminalJson() { return "{\"connected\":" + OfdJsonBool(TerminalInfoInteger(TERMINAL_CONNECTED) != 0) + ",\"trade_allowed\":" + OfdJsonBool(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) != 0) + ",\"expert_trade_allowed\":" + OfdJsonBool(MQLInfoInteger(MQL_TRADE_ALLOWED) != 0) + ",\"dlls_allowed\":" + OfdJsonBool(TerminalInfoInteger(TERMINAL_DLLS_ALLOWED) != 0) + ",\"build\":" + OfdJsonLong(TerminalInfoInteger(TERMINAL_BUILD)) + "}"; } //--- A reload with new inputs (a new preset after a rotation or a refusal) keeps an EA's globals: start clean. void OfdResetState() { g_cursorTicket = 0; g_cursorTime = 0; g_nextPushAt = 0; g_backoff = 0; g_stopped = false; g_holdUntil = 0; g_awaitSince = 0; g_status = "starting"; } //--- A trade happened: push now, unless stopped, backing off, or held by a 429. void OfdPushSoon() { if(!g_stopped && g_backoff == 0 && TimeLocal() >= g_holdUntil) g_nextPushAt = 0; } //--- A history page is sent and not stored yet. The 202 carries the cursor from before the worker wrote it, so the //--- next pushes send no history (with that page's "more") until the cursor reaches the page, instead of the same //--- 1,000 rows every few seconds. After 60 s without progress the page goes again: a lost batch costs a resend. bool OfdAwaitingStore() { if(g_awaitSince == 0) return false; if(TimeLocal() - g_awaitSince > 60) { g_awaitSince = 0; return false; } return true; } void OfdAwait(const long ticket, const long time, const bool more) { g_awaitMore = more; g_awaitTicket = ticket; g_awaitTime = time; g_awaitSince = TimeLocal(); } bool OfdInputsValid(const string endpoint, const string keyId, const string secret) { // Plain HTTP only to this machine: "http://localhost.example.net" is another host, and would get the account in clear. if(StringFind(endpoint, "https://") != 0 && StringFind(endpoint, "http://localhost:") != 0 && StringFind(endpoint, "http://localhost/") != 0) { Alert("OfdSync: InpEndpoint must be the https:// URL from your preset."); return false; } if(StringFind(endpoint, keyId) < 0 || StringLen(keyId) != 25) { Alert("OfdSync: InpKeyId does not match the endpoint. Load the preset again."); return false; } if(StringLen(secret) != 64) { Alert("OfdSync: InpSecret must be the 64-character secret from your preset."); return false; } return true; } #endif