//+------------------------------------------------------------------+ //| OfdSync.mq5: sends this terminal's account to openfxdata. | //| | //| Read-only: it reads the account, its history and open positions | //| and posts them over HTTPS (WebRequest, no DLL). It never sends, | //| changes, closes or deletes an order or a position. | //| 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." #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) 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() { if(!g_stopped && TimeLocal() >= g_nextPushAt && OfdLoggedIn()) Push(); Comment("OfdSync ", OFDSYNC_VERSION, ": ", g_status); } //--- A deal happened: push now unless backing off or stopped. void OnTrade() { OfdPushSoon(); } void Push() { string trades = "", ops = ""; long scannedTicket = 0, 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, scannedTicket, scannedTime, more); if(trades != "" || ops != "") OfdAwait(scannedTicket, 0, more); } string body = "{\"v\":1,\"platform\":\"mt5\"" + ",\"login\":" + OfdJsonLong(OfdLogin()) + ",\"server\":" + OfdJsonString(AccountInfoString(ACCOUNT_SERVER)) + ",\"server_time\":" + OfdJsonLong((long)TimeTradeServer()) + ",\"account\":" + OfdAccountJson() + ",\"terminal\":" + OfdTerminalJson() + ",\"trades\":[" + trades + "]" + ",\"balance_ops\":[" + ops + "]" + ",\"positions\":[" + Positions() + "]" + ",\"scanned\":{\"ticket\":" + OfdJsonLong(scannedTicket) + ",\"time\":" + OfdJsonLong(scannedTime) + "}" + ",\"more\":" + OfdJsonBool(more) + "}"; OfdPost(InpEndpoint, InpSecret, body); } string Positions() { string out = ""; int total = PositionsTotal(); for(int i = 0; i < total && i < OFDSYNC_PAGE; i++) { ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; long type = PositionGetInteger(POSITION_TYPE); if(out != "") out += ","; out += "{\"ticket\":" + OfdJsonLong((long)ticket) + ",\"symbol\":" + OfdJsonString(PositionGetString(POSITION_SYMBOL)) + ",\"side\":" + (type == POSITION_TYPE_BUY ? "\"buy\"" : "\"sell\"") + ",\"volume\":" + OfdJsonAmount(PositionGetDouble(POSITION_VOLUME)) + ",\"open_time\":" + OfdJsonLong(PositionGetInteger(POSITION_TIME)) + ",\"open_price\":" + OfdJsonAmount(PositionGetDouble(POSITION_PRICE_OPEN)) + ",\"sl\":" + OfdJsonAmount(PositionGetDouble(POSITION_SL)) + ",\"tp\":" + OfdJsonAmount(PositionGetDouble(POSITION_TP)) + ",\"profit\":" + OfdJsonAmount(PositionGetDouble(POSITION_PROFIT)) + ",\"swap\":" + OfdJsonAmount(PositionGetDouble(POSITION_SWAP)) + "}"; } return out; } //--- Balance-type deals: everything that is neither a buy nor a sell. string BalanceType(const long dealType) { if(dealType == DEAL_TYPE_BALANCE) return "balance"; if(dealType == DEAL_TYPE_CREDIT) return "credit"; return "other"; } //+------------------------------------------------------------------+ //| One page of history after the server's cursor (deal tickets). | //| A closed position is sent once, aggregated, at its last closing | //| deal; a position still open (even partly closed) waits. | //+------------------------------------------------------------------+ void History(string &trades, string &ops, long &scannedTicket, long &scannedTime, bool &more) { datetime from = g_cursorTime > 86400 ? (datetime)(g_cursorTime - 86400) : 0; if(!HistorySelect(from, TimeCurrent() + 86400)) return; //--- Deals after the cursor, oldest ticket first. int total = HistoryDealsTotal(); ulong tickets[]; ArrayResize(tickets, 0, total); for(int i = 0; i < total; i++) { ulong deal = HistoryDealGetTicket(i); if(deal > (ulong)g_cursorTicket) { int n = ArraySize(tickets); ArrayResize(tickets, n + 1, total); tickets[n] = deal; } } ArraySort(tickets); //--- Walk the page: balance rows at once, closing deals as candidates. ulong candidateDeal[]; ulong candidatePosition[]; int rows = 0, opCount = 0; int count = ArraySize(tickets); int i = 0; for(; i < count; i++) { if(rows >= OFDSYNC_PAGE || opCount >= OFDSYNC_PAGE) break; ulong deal = tickets[i]; long type = HistoryDealGetInteger(deal, DEAL_TYPE); long time = HistoryDealGetInteger(deal, DEAL_TIME); scannedTicket = (long)deal; scannedTime = time; if(type != DEAL_TYPE_BUY && type != DEAL_TYPE_SELL) { if(ops != "") ops += ","; ops += "{\"ticket\":" + OfdJsonLong((long)deal) + ",\"time\":" + OfdJsonLong(time) + ",\"type\":\"" + BalanceType(type) + "\"" + ",\"amount\":" + OfdJsonAmount(HistoryDealGetDouble(deal, DEAL_PROFIT)) + ",\"comment\":" + OfdJsonString(HistoryDealGetString(deal, DEAL_COMMENT)) + "}"; opCount++; continue; } long entry = HistoryDealGetInteger(deal, DEAL_ENTRY); if(entry == DEAL_ENTRY_OUT || entry == DEAL_ENTRY_OUT_BY || entry == DEAL_ENTRY_INOUT) { int n = ArraySize(candidateDeal); ArrayResize(candidateDeal, n + 1); ArrayResize(candidatePosition, n + 1); candidateDeal[n] = deal; candidatePosition[n] = (ulong)HistoryDealGetInteger(deal, DEAL_POSITION_ID); rows++; } } more = i < count; //--- Aggregate each candidate position (this replaces the history selection, so it comes last). for(int c = 0; c < ArraySize(candidateDeal); c++) { string row; ulong lastOut; if(!Aggregate(candidatePosition[c], row, lastOut)) continue; // Sent at its last closing deal only: an earlier partial close of a closed position adds nothing. if(lastOut != candidateDeal[c]) continue; if(trades != "") trades += ","; trades += row; } } //--- The position's row, or false while it is still open. Open or closed is read from the deals themselves (in volume //--- against out volume), not from the open-position list: some brokers close and re-open a position to charge swap, //--- which changes its ticket but not its identifier. bool Aggregate(const ulong positionId, string &row, ulong &lastOut) { if(!HistorySelectByPosition(positionId)) return false; double inVolume = 0, inValue = 0, outVolume = 0, outValue = 0; double profit = 0, commission = 0, swap = 0, sl = 0, tp = 0; long openTime = 0, closeTime = 0, magic = 0; string side = "", symbol = "", comment = ""; lastOut = 0; int total = HistoryDealsTotal(); for(int i = 0; i < total; i++) { ulong deal = HistoryDealGetTicket(i); long type = HistoryDealGetInteger(deal, DEAL_TYPE); if(type != DEAL_TYPE_BUY && type != DEAL_TYPE_SELL) continue; long entry = HistoryDealGetInteger(deal, DEAL_ENTRY); double volume = HistoryDealGetDouble(deal, DEAL_VOLUME); double price = HistoryDealGetDouble(deal, DEAL_PRICE); long time = HistoryDealGetInteger(deal, DEAL_TIME); profit += HistoryDealGetDouble(deal, DEAL_PROFIT); commission += HistoryDealGetDouble(deal, DEAL_COMMISSION) + HistoryDealGetDouble(deal, DEAL_FEE); swap += HistoryDealGetDouble(deal, DEAL_SWAP); if(entry == DEAL_ENTRY_INOUT) { // A netting reversal: the part that closes what was open is an exit; the rest opens again (the position stays // open until a later exit closes it, and its row is sent then). double closing = MathMin(volume, inVolume - outVolume); outVolume += closing; outValue += closing * price; inVolume += volume - closing; inValue += (volume - closing) * price; if(deal > lastOut) { lastOut = deal; closeTime = time; } continue; } if(entry == DEAL_ENTRY_IN) { if(side == "") { side = type == DEAL_TYPE_BUY ? "buy" : "sell"; symbol = HistoryDealGetString(deal, DEAL_SYMBOL); openTime = time; magic = HistoryDealGetInteger(deal, DEAL_MAGIC); comment = HistoryDealGetString(deal, DEAL_COMMENT); } inVolume += volume; inValue += volume * price; } else { outVolume += volume; outValue += volume * price; if(deal > lastOut) { lastOut = deal; closeTime = time; sl = HistoryDealGetDouble(deal, DEAL_SL); tp = HistoryDealGetDouble(deal, DEAL_TP); } } } if(side == "" || lastOut == 0 || outVolume <= 0 || inVolume <= 0) return false; if(inVolume - outVolume > 1e-8) return false; // still open (partly closed): sent once fully closed row = "{\"ticket\":" + OfdJsonLong((long)positionId) + ",\"position_id\":" + OfdJsonLong((long)positionId) + ",\"deal\":" + OfdJsonLong((long)lastOut) + ",\"symbol\":" + OfdJsonString(symbol) + ",\"side\":\"" + side + "\"" + ",\"volume\":" + OfdJsonAmount(outVolume) + ",\"open_time\":" + OfdJsonLong(openTime) + ",\"open_price\":" + OfdJsonAmount(inValue / inVolume) + ",\"close_time\":" + OfdJsonLong(closeTime) + ",\"close_price\":" + OfdJsonAmount(outValue / outVolume) + ",\"sl\":" + OfdJsonAmount(sl) + ",\"tp\":" + OfdJsonAmount(tp) + ",\"profit\":" + OfdJsonAmount(profit) + ",\"commission\":" + OfdJsonAmount(commission) + ",\"swap\":" + OfdJsonAmount(swap) + ",\"comment\":" + OfdJsonString(comment) + ",\"magic\":" + OfdJsonLong(magic) + "}"; return true; }