//+------------------------------------------------------------------+ //| OfdSync.mq4: sends this terminal's account to openfxdata. | //| | //| Read-only: it reads the account, its history and open orders and | //| posts them over HTTPS (WebRequest, no DLL). It never sends, | //| changes, closes or deletes an order. | //| Source and checksums: https://openfxdata.com/downloads/ofdsync/ | //+------------------------------------------------------------------+ #property copyright "openfxdata" #property link "https://openfxdata.com" #property version "1.10" #property description "Sends this account's statistics to openfxdata. Read-only: never places, changes or closes a trade." #property strict #include "OfdSyncCommon.mqh" input string InpEndpoint = ""; // Endpoint (from your preset) input string InpKeyId = ""; // Key id (from your preset) input string InpSecret = ""; // Secret (from your preset) //--- MT4 order types the history holds besides trades (no named constants in MQL4). #define OFD_MT4_BALANCE 6 #define OFD_MT4_CREDIT 7 int g_lastHistoryTotal = -1; int g_lastOpenTotal = -1; //--- MT4 has no TimeTradeServer(): TimeCurrent() is the last tick's time and stands still over a weekend or a lost //--- connection. It is sent as the broker clock only while ticks are fresh, else null (the server keeps its offset). datetime g_lastTick = 0; datetime g_lastTickSeenAt = 0; int OnInit() { if(!OfdInputsValid(InpEndpoint, InpKeyId, InpSecret)) return INIT_PARAMETERS_INCORRECT; OfdResetState(); EventSetTimer(1); return INIT_SUCCEEDED; } void OnDeinit(const int reason) { EventKillTimer(); Comment(""); } void OnTimer() { // MQL4 has no OnTrade: a change in the order counts is a trade, and is pushed at once. int historyTotal = OrdersHistoryTotal(); int openTotal = OrdersTotal(); if((historyTotal != g_lastHistoryTotal || openTotal != g_lastOpenTotal) && g_backoff == 0) OfdPushSoon(); g_lastHistoryTotal = historyTotal; g_lastOpenTotal = openTotal; if(TimeCurrent() != g_lastTick) { g_lastTick = TimeCurrent(); g_lastTickSeenAt = TimeLocal(); } if(!g_stopped && TimeLocal() >= g_nextPushAt && OfdLoggedIn()) Push(); Comment("OfdSync ", OFDSYNC_VERSION, ": ", g_status); } void Push() { string trades = "", ops = ""; long scannedTime = 0; bool more = false; if(OfdAwaitingStore()) more = g_awaitMore; // the last page is not stored yet: a heartbeat that keeps its "more" else { History(trades, ops, scannedTime, more); if(trades != "" || ops != "") OfdAwait(0, scannedTime, more); } string body = "{\"v\":1,\"platform\":\"mt4\"" + ",\"login\":" + OfdJsonLong(OfdLogin()) + ",\"server\":" + OfdJsonString(AccountInfoString(ACCOUNT_SERVER)) + ",\"server_time\":" + (TimeLocal() - g_lastTickSeenAt <= 60 && g_lastTick > 0 ? OfdJsonLong((long)TimeCurrent()) : "null") + ",\"account\":" + OfdAccountJson() + ",\"terminal\":" + OfdTerminalJson() + ",\"trades\":[" + trades + "]" + ",\"balance_ops\":[" + ops + "]" + ",\"positions\":[" + Positions() + "]" + ",\"scanned\":{\"ticket\":0,\"time\":" + OfdJsonLong(scannedTime) + "}" + ",\"more\":" + OfdJsonBool(more) + "}"; OfdPost(InpEndpoint, InpSecret, body); } string Positions() { string out = ""; int total = OrdersTotal(); int sent = 0; for(int i = 0; i < total && sent < OFDSYNC_PAGE; i++) { if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue; int type = OrderType(); if(type != OP_BUY && type != OP_SELL) continue; // pending orders are not positions if(out != "") out += ","; out += "{\"ticket\":" + OfdJsonLong(OrderTicket()) + ",\"symbol\":" + OfdJsonString(OrderSymbol()) + ",\"side\":" + (type == OP_BUY ? "\"buy\"" : "\"sell\"") + ",\"volume\":" + OfdJsonAmount(OrderLots()) + ",\"open_time\":" + OfdJsonLong((long)OrderOpenTime()) + ",\"open_price\":" + OfdJsonAmount(OrderOpenPrice()) + ",\"sl\":" + OfdJsonAmount(OrderStopLoss()) + ",\"tp\":" + OfdJsonAmount(OrderTakeProfit()) + ",\"profit\":" + OfdJsonAmount(OrderProfit()) + ",\"swap\":" + OfdJsonAmount(OrderSwap()) + ",\"commission\":" + OfdJsonAmount(OrderCommission()) + "}"; sent++; } return out; } //+------------------------------------------------------------------+ //| One page of history with a close time at or after the server's | //| cursor time, oldest first. The boundary second is sent again; | //| rows upsert by ticket, so that is harmless. | //+------------------------------------------------------------------+ void History(string &trades, string &ops, long &scannedTime, bool &more) { //--- [close time, history index] pairs after the cursor, sorted by the first column (oldest close first). int total = OrdersHistoryTotal(); long rowsAfter[][2]; ArrayResize(rowsAfter, 0, total); for(int i = 0; i < total; i++) { if(!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue; int type = OrderType(); if(type != OP_BUY && type != OP_SELL && type != OFD_MT4_BALANCE && type != OFD_MT4_CREDIT) continue; // deleted pending orders long closed = (long)OrderCloseTime(); if(closed < g_cursorTime) continue; int n = ArrayRange(rowsAfter, 0); ArrayResize(rowsAfter, n + 1, total); rowsAfter[n][0] = closed; rowsAfter[n][1] = i; } int count = ArrayRange(rowsAfter, 0); if(count > 1) ArraySort(rowsAfter); int rows = 0, opCount = 0; int k = 0; for(; k < count; k++) { if(rows >= OFDSYNC_PAGE || opCount >= OFDSYNC_PAGE) break; if(!OrderSelect((int)rowsAfter[k][1], SELECT_BY_POS, MODE_HISTORY)) continue; int type = OrderType(); scannedTime = rowsAfter[k][0]; if(type == OFD_MT4_BALANCE || type == OFD_MT4_CREDIT) { if(ops != "") ops += ","; ops += "{\"ticket\":" + OfdJsonLong(OrderTicket()) + ",\"time\":" + OfdJsonLong((long)OrderCloseTime()) + ",\"type\":" + (type == OFD_MT4_CREDIT ? "\"credit\"" : "\"balance\"") + ",\"amount\":" + OfdJsonAmount(OrderProfit()) + ",\"comment\":" + OfdJsonString(OrderComment()) + "}"; opCount++; continue; } if(trades != "") trades += ","; trades += "{\"ticket\":" + OfdJsonLong(OrderTicket()) + ",\"symbol\":" + OfdJsonString(OrderSymbol()) + ",\"side\":" + (type == OP_BUY ? "\"buy\"" : "\"sell\"") + ",\"volume\":" + OfdJsonAmount(OrderLots()) + ",\"open_time\":" + OfdJsonLong((long)OrderOpenTime()) + ",\"open_price\":" + OfdJsonAmount(OrderOpenPrice()) + ",\"close_time\":" + OfdJsonLong((long)OrderCloseTime()) + ",\"close_price\":" + OfdJsonAmount(OrderClosePrice()) + ",\"sl\":" + OfdJsonAmount(OrderStopLoss()) + ",\"tp\":" + OfdJsonAmount(OrderTakeProfit()) + ",\"profit\":" + OfdJsonAmount(OrderProfit()) + ",\"commission\":" + OfdJsonAmount(OrderCommission()) + ",\"swap\":" + OfdJsonAmount(OrderSwap()) + ",\"comment\":" + OfdJsonString(OrderComment()) + ",\"magic\":" + OfdJsonLong(OrderMagicNumber()) + "}"; rows++; } more = k < count; }