//+------------------------------------------------------------------+ //| TradingBotHouse.mq5 | //| Copyright 2026, Trading Bot House | //| https://tradingbothouse.com | //| | //| Polls the backend for pending signals and executes them via | //| OrderSend(). Reports results back so the dashboard shows fills. | //| | //| BEFORE ATTACHING: | //| 1. Tools → Options → Expert Advisors | //| 2. Enable 'Allow WebRequest for listed URL' and add: | //| https://tradingbothouse.com | //| 3. Get your secret token from Studio → Settings → MetaTrader | //| 4. Drag this EA onto any chart, paste the token into 'Token'. | //+------------------------------------------------------------------+ #property copyright "2026, Trading Bot House" #property link "https://tradingbothouse.com" #property version "1.55" #property strict #include //--- Inputs input string Token = ""; // Secret token input string ServerURL = "https://tradingbothouse.com"; // Backend URL input int PollSeconds = 5; // Poll interval (seconds) input double DefaultLot = 0.01; // Default lot size input int MagicNumber = 20260703; // EA magic input bool VerboseLog = true; // Print poll results input double FallbackStopPct = 2.0; // Emergency stop %, if a position has none (0 = off) input int ClosedBackfillDays = 30; // v1.52: on first start, report closes this far back input bool ShowcaseCharts = false; // v1.54: open a light chart per open position + PNG shots input int ShowcaseShotSec = 60; // v1.54: how often those PNGs are refreshed #define EA_VERSION "1.55" // reported in every poll; server refuses trades to older EAs // v1.55: a strategy's close flattens ONLY that strategy's ticket(s) (the server // sends by_ticket + close_tickets), never a neighbour on the same symbol. A late // entry (> 20 s after the signal) is skipped when the broker price has moved more // than max_move_bp since the signal minute ("price_moved", shown as SKIPPED). // A netting account is reported at start: there, two strategies on one symbol // share one position. // v1.54: optional showcase mode (off by default). Every open position gets its // own chart in a light theme, entry/SL/TP drawn as plain lines (no prices, no // text), a small "BUY 0.10 lot · +12.30 · DEMO" tag, and a PNG of that chart in // MQL5/Files/showcase/ — the chart only, so the account balance never shows. // v1.53: every poll also carries equity, floating P/L and open positions, so // the site can show a terminal's open result live (not only closed trades). //--- Globals CTrade trade; datetime lastPoll = 0; bool outdatedWarned = false; int pollFailures = 0; //--- Bracket guard state. Retrying a rejected PositionModify every 5s for a //--- whole weekend is pure noise: two journal lines and a pointless OrderSend //--- per tick, for a stop the broker cannot accept until the session opens. //--- So: skip outside trading hours, and back off on genuine rejections. ulong bkTicket[]; // ticket we failed on datetime bkNextTry[]; // when to try it again int bkFails[]; // consecutive failures, drives the backoff string nakedReported = ""; // last set we told the server about //--- v1.52 closed-position reporting. The broker closes positions on its own //--- (SL, TP, stop-out, a hand close) and before 1.52 the server never heard //--- about it. We read the deal history and report every closing deal of //--- ours once; the cursor lives in terminal global variables, so a restart //--- resumes where it stopped (the server de-duplicates by deal ticket too). bool closedDirty = true; // a deal was added (or we just started) datetime closedLastRun = 0; // TimeLocal of the last scan — safety rescan every 60 s #define CLOSED_BATCH 20 struct ClosedDeal { ulong deal; ulong pos; datetime t; double price, vol, profit, comm, swap; long reason, magic, type; string symbol; }; //+------------------------------------------------------------------+ //| Init | //+------------------------------------------------------------------+ int OnInit() { if(StringLen(Token) < 8) { Alert("TradingBotHouse: paste your secret token from Studio → Settings → MetaTrader"); return(INIT_PARAMETERS_INCORRECT); } trade.SetExpertMagicNumber(MagicNumber); trade.SetTypeFillingBySymbol(_Symbol); EventSetTimer(MathMax(2, PollSeconds)); Print("TradingBotHouse EA started · polling ", ServerURL, " every ", PollSeconds, "s"); if((ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE) != ACCOUNT_MARGIN_MODE_RETAIL_HEDGING) Print("WARNING: this is a NETTING account. Two strategies on one symbol share ONE position here, " "so one strategy's exit closes it for both. Use a hedging account for several strategies."); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Deinit | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { EventKillTimer(); } //+------------------------------------------------------------------+ //| v1.52: a deal landed (fill, SL, TP, stop-out, hand close) — scan | //| the history on the next poll instead of waiting for the 60 s pass. | //+------------------------------------------------------------------+ void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result) { if(trans.type == TRADE_TRANSACTION_DEAL_ADD) closedDirty = true; } //+------------------------------------------------------------------+ //| Timer — main poll loop | //+------------------------------------------------------------------+ void OnTimer() { if(TimeCurrent() - lastPoll < PollSeconds) return; lastPoll = TimeCurrent(); // Build poll body: token + broker balance for the dashboard heartbeat. string balance = DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2); string currency = AccountInfoString(ACCOUNT_CURRENCY); // v1.53: the account's live state — equity, floating P/L of everything // open, and how many positions are open (all / ours by magic). string equity = DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY), 2); string floating = DoubleToString(AccountInfoDouble(ACCOUNT_PROFIT), 2); int nAll = PositionsTotal(), nOurs = 0; for(int p = nAll - 1; p >= 0; p--) { if(PositionGetTicket(p) > 0 && PositionGetInteger(POSITION_MAGIC) == MagicNumber) nOurs++; } string body = StringFormat("{\"secret_token\":\"%s\",\"broker_balance\":%s,\"broker_currency\":\"%s\",\"ea_version\":\"%s\"," "\"broker_equity\":%s,\"broker_profit\":%s,\"open_positions\":%d,\"open_positions_ours\":%d}", Token, balance, currency, EA_VERSION, equity, floating, nAll, nOurs); string response; if(!HttpPostJson(ServerURL + "/mt/poll", body, response)) { pollFailures++; if(pollFailures == 3) Print("Poll failing: ", response); return; } pollFailures = 0; if(VerboseLog && StringFind(response, "\"signals\":[]") < 0) Print("Poll: ", response); if(StringFind(response, "\"ea_outdated\":true") >= 0) { if(!outdatedWarned) { Alert("TradingBotHouse EA is outdated — download the new version from Studio → Settings → MetaTrader"); outdatedWarned = true; } return; } // Safety net first: before anything else this poll, make sure every // position we own is carrying a stop. See GuardBrackets(). GuardBrackets(response); if(ShowcaseCharts) Showcase(); // v1.52: tell the server about every position of ours the broker closed // since the last report (its own SL/TP, stop-out, a hand close). ReportClosed(); // Kill switch is honored SERVER-side: when it's on, the server delivers // only 'close' signals (flatten is always allowed). So we keep processing // the signals array — do NOT bail out here, or close signals get lost. // Parse signals[] block. int sigStart = StringFind(response, "\"signals\":["); if(sigStart < 0) return; string sigBlock = StringSubstr(response, sigStart + 11); // skip "signals":[ int sigEnd = StringFind(sigBlock, "]"); if(sigEnd < 0) return; sigBlock = StringSubstr(sigBlock, 0, sigEnd); if(StringLen(sigBlock) < 5) return; // Split on "},{" — good enough for the flat objects we send. string chunks[]; int nchunks = SplitByDelim(sigBlock, "},{", chunks); for(int i = 0; i < nchunks; i++) { string chunk = chunks[i]; // Normalize braces after split if(StringFind(chunk, "{") != 0) chunk = "{" + chunk; if(StringFind(chunk, "}") != StringLen(chunk) - 1) chunk = chunk + "}"; ExecuteSignal(chunk); } } //+------------------------------------------------------------------+ //| v1.54 showcase: one light chart per symbol with an open position. | //| Charts we opened carry the object "tbh_show"; when the symbol has | //| no position left, that chart is closed. The EA's own chart is | //| styled too but never closed. | //+------------------------------------------------------------------+ datetime showLastShot = 0; void StyleLight(long cid) { ChartSetInteger(cid, CHART_MODE, CHART_CANDLES); ChartSetInteger(cid, CHART_COLOR_BACKGROUND, C'255,255,255'); ChartSetInteger(cid, CHART_COLOR_FOREGROUND, C'90,96,105'); ChartSetInteger(cid, CHART_COLOR_GRID, C'240,241,243'); ChartSetInteger(cid, CHART_SHOW_GRID, false); ChartSetInteger(cid, CHART_COLOR_CHART_UP, C'22,128,74'); // bull outline ChartSetInteger(cid, CHART_COLOR_CANDLE_BULL, C'46,189,112'); // bull body ChartSetInteger(cid, CHART_COLOR_CHART_DOWN, C'176,40,36'); // bear outline ChartSetInteger(cid, CHART_COLOR_CANDLE_BEAR, C'239,83,80'); // bear body ChartSetInteger(cid, CHART_COLOR_CHART_LINE, C'90,96,105'); ChartSetInteger(cid, CHART_COLOR_BID, C'200,204,210'); ChartSetInteger(cid, CHART_SHOW_ASK_LINE, false); ChartSetInteger(cid, CHART_SHOW_VOLUMES, CHART_VOLUME_HIDE); ChartSetInteger(cid, CHART_SHOW_OHLC, false); ChartSetInteger(cid, CHART_SHOW_ONE_CLICK, false); ChartSetInteger(cid, CHART_SHOW_TRADE_LEVELS, false); // we draw our own, without text ChartSetInteger(cid, CHART_SHOW_PERIOD_SEP, false); ChartSetInteger(cid, CHART_SHIFT, true); ChartSetInteger(cid, CHART_SCALE, 3); } void ShowLine(long cid, string name, datetime from, double price, color c, int style) { if(price <= 0) { ObjectDelete(cid, name); return; } if(ObjectFind(cid, name) < 0 && !ObjectCreate(cid, name, OBJ_TREND, 0, from, price, from + 3600, price)) Print("showcase: line ", name, " not created, err ", GetLastError()); ObjectSetInteger(cid, name, OBJPROP_TIME, 0, from); ObjectSetDouble(cid, name, OBJPROP_PRICE, 0, price); ObjectSetInteger(cid, name, OBJPROP_TIME, 1, from + 3600); ObjectSetDouble(cid, name, OBJPROP_PRICE, 1, price); ObjectSetInteger(cid, name, OBJPROP_RAY_RIGHT, true); ObjectSetInteger(cid, name, OBJPROP_COLOR, c); ObjectSetInteger(cid, name, OBJPROP_STYLE, style); ObjectSetInteger(cid, name, OBJPROP_WIDTH, 2); ObjectSetInteger(cid, name, OBJPROP_SELECTABLE, false); ObjectSetInteger(cid, name, OBJPROP_HIDDEN, true); ObjectSetString(cid, name, OBJPROP_TOOLTIP, "\n"); } void ShowTag(long cid, string text, color c) { string n = "tbh_tag"; if(ObjectFind(cid, n) < 0) ObjectCreate(cid, n, OBJ_LABEL, 0, 0, 0); ObjectSetInteger(cid, n, OBJPROP_CORNER, CORNER_LEFT_UPPER); ObjectSetInteger(cid, n, OBJPROP_XDISTANCE, 14); ObjectSetInteger(cid, n, OBJPROP_YDISTANCE, 26); ObjectSetInteger(cid, n, OBJPROP_FONTSIZE, 14); ObjectSetString(cid, n, OBJPROP_FONT, "Arial Bold"); ObjectSetInteger(cid, n, OBJPROP_COLOR, c); ObjectSetInteger(cid, n, OBJPROP_SELECTABLE, false); ObjectSetInteger(cid, n, OBJPROP_HIDDEN, true); ObjectSetString(cid, n, OBJPROP_TEXT, text); } long FindChart(string sym) { for(long c = ChartFirst(); c >= 0; c = ChartNext(c)) if(ChartSymbol(c) == sym) return c; return -1; } void Showcase() { string syms[]; int ns = 0; for(int p = PositionsTotal() - 1; p >= 0; p--) { ulong tk = PositionGetTicket(p); if(tk == 0) continue; string sym = PositionGetString(POSITION_SYMBOL); bool seen = false; for(int k = 0; k < ns; k++) if(syms[k] == sym) seen = true; if(seen) continue; // one chart per symbol: the first position found draws it ArrayResize(syms, ns + 1); syms[ns++] = sym; long cid = FindChart(sym); if(cid < 0) { cid = ChartOpen(sym, PERIOD_H1); if(cid <= 0) continue; ObjectCreate(cid, "tbh_show", OBJ_LABEL, 0, 0, 0); ObjectSetString(cid, "tbh_show", OBJPROP_TEXT, " "); ObjectSetInteger(cid, "tbh_show", OBJPROP_HIDDEN, true); } StyleLight(cid); // Anchor the lines inside the visible bars (an old position's open // time can sit far off the left edge, and then nothing is drawn). datetime opened = (datetime)PositionGetInteger(POSITION_TIME); int fv = (int)ChartGetInteger(cid, CHART_FIRST_VISIBLE_BAR); datetime leftT = iTime(sym, ChartPeriod(cid), MathMax(0, fv)); if(leftT > 0 && opened < leftT) opened = leftT; bool buy = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY; ShowLine(cid, "tbh_entry", opened, PositionGetDouble(POSITION_PRICE_OPEN), C'90,96,105', STYLE_DASH); ShowLine(cid, "tbh_sl", opened, PositionGetDouble(POSITION_SL), C'220,53,69', STYLE_SOLID); ShowLine(cid, "tbh_tp", opened, PositionGetDouble(POSITION_TP), C'25,160,90', STYLE_SOLID); double pl = PositionGetDouble(POSITION_PROFIT) + PositionGetDouble(POSITION_SWAP); string tag = StringFormat("%s %s · %s lot · %s%s · DEMO", buy ? "BUY" : "SELL", sym, DoubleToString(PositionGetDouble(POSITION_VOLUME), 2), pl >= 0 ? "+" : "", DoubleToString(pl, 2)); ShowTag(cid, tag, pl >= 0 ? C'22,128,74' : C'176,40,36'); // Keep entry, SL and TP on screen: widen the price scale to cover the // visible bars AND the three levels, with a little air on both sides. int bars = (int)ChartGetInteger(cid, CHART_VISIBLE_BARS); int first = (int)ChartGetInteger(cid, CHART_FIRST_VISIBLE_BAR); double hi = 0, lo = 0; if(bars > 0) { int from = MathMax(0, first - bars + 1); int ih = iHighest(sym, ChartPeriod(cid), MODE_HIGH, bars, from); int il = iLowest(sym, ChartPeriod(cid), MODE_LOW, bars, from); if(ih >= 0) hi = iHigh(sym, ChartPeriod(cid), ih); if(il >= 0) lo = iLow(sym, ChartPeriod(cid), il); } double lv[3]; lv[0] = PositionGetDouble(POSITION_PRICE_OPEN); lv[1] = PositionGetDouble(POSITION_SL); lv[2] = PositionGetDouble(POSITION_TP); for(int q = 0; q < 3; q++) { if(lv[q] <= 0) continue; if(hi <= 0 || lv[q] > hi) hi = lv[q]; if(lo <= 0 || lv[q] < lo) lo = lv[q]; } if(hi > lo) { double pad = (hi - lo) * 0.06; ChartSetInteger(cid, CHART_SCALEFIX, true); ChartSetDouble(cid, CHART_FIXED_MAX, hi + pad * 2); // extra room on top for the tag ChartSetDouble(cid, CHART_FIXED_MIN, lo - pad); } ChartRedraw(cid); } // Close the charts we opened whose symbol has nothing open any more. long c = ChartFirst(); while(c >= 0) { long nxt = ChartNext(c); string sym = ChartSymbol(c); bool open = false; for(int k = 0; k < ns; k++) if(syms[k] == sym) open = true; if(!open && c != ChartID() && ObjectFind(c, "tbh_show") >= 0) ChartClose(c); if(c == ChartID()) StyleLight(c); c = nxt; } if(ns > 0 && TimeLocal() - showLastShot >= MathMax(15, ShowcaseShotSec)) { showLastShot = TimeLocal(); for(int k = 0; k < ns; k++) { long cid = FindChart(syms[k]); if(cid > 0) ChartScreenShot(cid, "showcase\\" + syms[k] + ".png", 1280, 720, ALIGN_RIGHT); } } } //+------------------------------------------------------------------+ //| Bracket guard — runs on EVERY poll, not just after a fill. | //| | //| Setting the stop once at fill time is not enough. The EA restarts | //| and forgets; a Market Execution broker drops the inline stops; a | //| stop gets dragged off the chart by hand. The USDJPY position of | //| 2026-10-15 sat naked for three days for exactly that reason. | //| | //| So the server re-states every open ticket's bracket in each poll | //| response and we re-assert it here. Any position of ours that the | //| server has no memory of still gets FallbackStopPct — "no stop at | //| all" is never an acceptable state for an account we trade. | //+------------------------------------------------------------------+ void GuardBrackets(string response) { string naked = ""; // positions we own and could NOT bracket string block = ""; int b = StringFind(response, "\"brackets\":["); if(b >= 0) { block = StringSubstr(response, b + 12); int e = StringFind(block, "]"); if(e >= 0) block = StringSubstr(block, 0, e); } for(int p = PositionsTotal() - 1; p >= 0; p--) { ulong ticket = PositionGetTicket(p); if(ticket == 0) continue; if(PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue; double curSL = PositionGetDouble(POSITION_SL); double curTP = PositionGetDouble(POSITION_TP); string symbol = PositionGetString(POSITION_SYMBOL); long ptype = PositionGetInteger(POSITION_TYPE); double open = PositionGetDouble(POSITION_PRICE_OPEN); bool isBuy = (ptype == POSITION_TYPE_BUY); double point = SymbolInfoDouble(symbol, SYMBOL_POINT); double wantSL = 0, wantTP = 0; FindBracket(block, (long)ticket, wantSL, wantTP); // No server memory of this ticket (EA restarted before the bracket // was recorded, or the fill predates the feature) — fall back to a // fixed-percent stop off the entry rather than leave it naked. if(wantSL <= 0 && FallbackStopPct > 0) wantSL = isBuy ? open * (1.0 - FallbackStopPct / 100.0) : open * (1.0 + FallbackStopPct / 100.0); // Work out whether anything is actually missing BEFORE deciding the // position is in trouble. A trailing strategy legitimately carries a // stop and no take-profit; calling that "naked" every weekend would // train the user to ignore the alert that matters. // // v1.40: the server's stop now RATCHETS behind the peak, so a stop // that merely exists is no longer the end of it — we also tighten one // the position has outgrown. Tighten only: a stop never moves away // from the position, whatever the server says, so a bad peak reading // or a stale row cannot hand back protection already earned. bool tighter = (wantSL > 0 && curSL > 0 && (isBuy ? wantSL > curSL + point : wantSL < curSL - point)); if(!tighter && (wantSL <= 0 || curSL > 0) && (wantTP <= 0 || curTP > 0)) continue; // Nothing to apply and no stop on the position — we cannot fix this // one ourselves (turn FallbackStopPct on, or set it by hand). if(wantSL <= 0 && curSL <= 0) { AddNaked(naked, ticket, symbol, "no_stop_known"); continue; } // Outside the symbol's trading session the broker rejects every // modify. Don't ask it 17,000 times over a weekend — record the // position as unbracketed and wait for the open. if(!MarketOpen(symbol)) { if(curSL <= 0) AddNaked(naked, ticket, symbol, "market_closed"); continue; } if(!BackoffReady(ticket)) { if(curSL <= 0) AddNaked(naked, ticket, symbol, "modify_rejected"); continue; } // Clamp to the broker's minimum stop distance from the CURRENT price. // If price has already run past the intended stop, we still place one // just outside the spread — a late stop beats no stop. int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS); double minDist = SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL) * point; if(minDist <= 0) minDist = 10 * point; double bid = SymbolInfoDouble(symbol, SYMBOL_BID); double ask = SymbolInfoDouble(symbol, SYMBOL_ASK); double sl = (tighter || curSL <= 0) ? wantSL : curSL; double tp = (curTP > 0) ? curTP : wantTP; if(sl > 0) { if(isBuy && bid - sl < minDist) sl = bid - minDist; if(!isBuy && sl - ask < minDist) sl = ask + minDist; sl = NormalizeDouble(sl, digits); } if(tp > 0) { if(isBuy && tp - ask < minDist) tp = ask + minDist; if(!isBuy && bid - tp < minDist) tp = bid - minDist; tp = NormalizeDouble(tp, digits); } // Last line of defence. The minimum-distance clamp above moves the // level toward current price, which on a tightening pass could in // principle push it back BELOW the stop already on the position. A // stop never loosens — if the clamp would do that, leave it alone. if(curSL > 0 && sl > 0 && (isBuy ? sl < curSL : sl > curSL)) sl = curSL; if(sl == curSL && tp == curTP) continue; if(trade.PositionModify(ticket, sl, tp)) { BackoffClear(ticket); Print(tighter ? "Net stop tightened: #" : "Bracket guard: #", ticket, " ", symbol, " sl=", sl, " tp=", tp); } else { int waited = BackoffFail(ticket); if(curSL <= 0) AddNaked(naked, ticket, symbol, "modify_rejected"); Print("Bracket guard FAILED on #", ticket, " ", symbol, ": ", trade.ResultRetcodeDescription(), " — retrying in ", waited, "s"); } } ReportNaked(naked); } //+------------------------------------------------------------------+ //| Is `symbol` inside a trading session right now (server time)? | //+------------------------------------------------------------------+ bool MarketOpen(string symbol) { if((ENUM_SYMBOL_TRADE_MODE)SymbolInfoInteger(symbol, SYMBOL_TRADE_MODE) == SYMBOL_TRADE_MODE_DISABLED) return false; MqlDateTime t; TimeToStruct(TimeCurrent(), t); int secOfDay = t.hour * 3600 + t.min * 60 + t.sec; datetime from, to; for(int i = 0; i < 8; i++) { if(!SymbolInfoSessionTrade(symbol, (ENUM_DAY_OF_WEEK)t.day_of_week, i, from, to)) break; if(secOfDay >= (int)from && secOfDay <= (int)to) return true; } return false; } //+------------------------------------------------------------------+ //| Per-ticket retry backoff: 1m, 2m, 4m, 8m, then every 15m. | //+------------------------------------------------------------------+ int BackoffFind(ulong ticket) { for(int i = 0; i < ArraySize(bkTicket); i++) if(bkTicket[i] == ticket) return i; return -1; } bool BackoffReady(ulong ticket) { int i = BackoffFind(ticket); return (i < 0 || TimeCurrent() >= bkNextTry[i]); } int BackoffFail(ulong ticket) { int i = BackoffFind(ticket); if(i < 0) { i = ArraySize(bkTicket); ArrayResize(bkTicket, i + 1); ArrayResize(bkNextTry, i + 1); ArrayResize(bkFails, i + 1); bkTicket[i] = ticket; bkFails[i] = 0; } bkFails[i]++; int wait = (int)MathMin(900, 60 * MathPow(2, MathMin(bkFails[i] - 1, 4))); bkNextTry[i] = TimeCurrent() + wait; return wait; } void BackoffClear(ulong ticket) { int i = BackoffFind(ticket); if(i < 0) return; int last = ArraySize(bkTicket) - 1; bkTicket[i] = bkTicket[last]; bkNextTry[i] = bkNextTry[last]; bkFails[i] = bkFails[last]; ArrayResize(bkTicket, last); ArrayResize(bkNextTry, last); ArrayResize(bkFails, last); } //+------------------------------------------------------------------+ //| Tell the server about positions we could not bracket — but ONLY | //| when the set changes. Retrying quietly is how a naked position | //| goes unnoticed for three days; re-sending every 5s is spam. | //+------------------------------------------------------------------+ void AddNaked(string &acc, ulong ticket, string symbol, string reason) { if(StringLen(acc) > 0) acc += ","; acc += StringFormat("{\"ticket\":%I64u,\"symbol\":\"%s\",\"reason\":\"%s\"}", ticket, EscapeJson(symbol), reason); } void ReportNaked(string naked) { if(naked == nakedReported) return; // nothing changed — stay quiet string body = StringFormat("{\"secret_token\":\"%s\",\"positions\":[%s]}", Token, naked); string response; if(!HttpPostJson(ServerURL + "/mt/naked", body, response)) return; nakedReported = naked; if(StringLen(naked) > 0) Print("Reported unbracketed position(s) to the dashboard"); else Print("All positions bracketed again — dashboard cleared"); } //+------------------------------------------------------------------+ //| Pull one ticket's sl/tp out of the brackets[] block. | //+------------------------------------------------------------------+ void FindBracket(string block, long ticket, double &slOut, double &tpOut) { slOut = 0; tpOut = 0; if(StringLen(block) < 5) return; string chunks[]; int n = SplitByDelim(block, "},{", chunks); for(int i = 0; i < n; i++) { string c = chunks[i]; if((long)JsonNumber(c, "ticket") != ticket) continue; slOut = JsonNumber(c, "sl"); tpOut = JsonNumber(c, "tp"); return; } } //+------------------------------------------------------------------+ //| Execute one JSON signal chunk | //+------------------------------------------------------------------+ void ExecuteSignal(string json) { int id = (int)StringToInteger(JsonNumber(json, "id")); string symbol = JsonString(json, "symbol"); string side = JsonString(json, "side"); // 'close' signal: flatten every open position on this symbol that carries // our magic number. Sent when the strategy's exit fires server-side // (trailing/signal exits can't be expressed as a static TP/SL bracket). // v1.50: the server sends a canonical name (US500, NAS100, NVDA) plus the // names other brokers use; find the one THIS broker lists. string aliases = JsonString(json, "aliases"); string brokerSym = ResolveSymbol(symbol, aliases); if(side == "close") { if(brokerSym == "") brokerSym = symbol; int closed = 0; if(JsonNumber(json, "by_ticket") > 0) { // v1.55: only the tickets this strategy opened. An empty list means // its entry never filled (or the broker already closed it). string parts[]; int n = StringSplit(JsonString(json, "close_tickets"), ',', parts); for(int k = 0; k < n; k++) { ulong tk = (ulong)StringToInteger(parts[k]); if(tk == 0 || !PositionSelectByTicket(tk)) continue; if(PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue; if(trade.PositionClose(tk)) closed++; } } else for(int p = PositionsTotal() - 1; p >= 0; p--) { ulong ticket = PositionGetTicket(p); if(ticket == 0) continue; if(PositionGetString(POSITION_SYMBOL) != brokerSym) continue; if(PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue; if(trade.PositionClose(ticket)) closed++; } AckSignal(id, closed > 0, closed, 0, closed > 0 ? "" : "no_matching_position"); Print("Close signal ", symbol, ": closed ", closed, " position(s)"); return; } // Take-profit / stop-loss as a fraction of entry (e.g. 0.02 = 2%). The BROKER // then closes the position at TP/SL — no dependency on a later close signal. double tpPct = JsonNumber(json, "tp_pct"); double slPct = JsonNumber(json, "sl_pct"); if(brokerSym == "") { AckSignal(id, false, 0, 0, "symbol_not_found:" + symbol + (aliases != "" ? " (also tried " + aliases + ")" : "") + " — add it to Market Watch or ask your broker if they offer it"); return; } symbol = brokerSym; trade.SetTypeFillingBySymbol(symbol); ENUM_ORDER_TYPE type = (side == "buy") ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; double price = (type == ORDER_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_ASK) : SymbolInfoDouble(symbol, SYMBOL_BID); // v1.55: a LATE entry is only taken while the price is still close to where // the strategy fired. Reference = this broker's own M1 open at the signal // minute, so a data-feed vs broker price gap can never block a trade. long createdTs = (long)JsonNumber(json, "created_ts"); double maxMoveBp = JsonNumber(json, "max_move_bp"); if(createdTs > 0 && maxMoveBp > 0 && price > 0) { long age = (long)TimeGMT() - createdTs; if(age > 20) { long offset = (long)TimeTradeServer() - (long)TimeGMT(); datetime brokerT = (datetime)(createdTs + offset); int sh = iBarShift(symbol, PERIOD_M1, brokerT, false); double ref = (sh >= 0) ? iOpen(symbol, PERIOD_M1, sh) : 0; if(ref > 0) { double moveBp = MathAbs(price - ref) / ref * 10000.0; if(moveBp > maxMoveBp) { string why = StringFormat("price_moved: %.1f bp since the signal %d s ago (limit %.1f bp = 1/4 of the stop) — skipped, not chased", moveBp, (int)age, maxMoveBp); AckSignal(id, false, 0, 0, why, -1, -1, symbol, "", 0); Print("Skipped late ", side, " ", symbol, ": ", why); return; } } } } // v1.50: size from THIS broker's contract spec. The server sends the // position's value in USD; one lot's value is price / tick size x tick // value, which holds for FX, metals, index and stock CFDs alike. A // server-side contract size is a guess — one broker's US500 is $1 a // point, another's $10 — and a wrong guess is a 10x position. double serverLots = JsonNumber(json, "volume"); double notional = JsonNumber(json, "notional_usd"); string spec = ""; double volume = 0; if(notional > 0) { string why = ""; volume = LotsFromNotional(symbol, notional, price, spec, why); if(volume <= 0 && (why != "" || serverLots <= 0)) { AckSignal(id, false, 0, 0, "cannot_size:" + symbol + " " + why, -1, -1, symbol, spec, 0); Print("Refused ", side, " ", symbol, ": ", why, " [", spec, "]"); return; } } if(volume <= 0) volume = (serverLots > 0) ? serverLots : DefaultLot; volume = NormalizeLots(symbol, volume); if(volume <= 0) { AckSignal(id, false, 0, 0, "invalid_volume:" + symbol, -1, -1, symbol, spec, 0); return; } // Compute SL/TP price levels; respect the broker's minimum stop distance. int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS); double point = SymbolInfoDouble(symbol, SYMBOL_POINT); double minDist = (double)SymbolInfoInteger(symbol, SYMBOL_TRADE_STOPS_LEVEL) * point; double sl = 0, tp = 0; if(type == ORDER_TYPE_BUY) { if(slPct > 0) { sl = price * (1.0 - slPct); if(price - sl < minDist) sl = price - minDist; } if(tpPct > 0) { tp = price * (1.0 + tpPct); if(tp - price < minDist) tp = price + minDist; } } else { if(slPct > 0) { sl = price * (1.0 + slPct); if(sl - price < minDist) sl = price + minDist; } if(tpPct > 0) { tp = price * (1.0 - tpPct); if(price - tp < minDist) tp = price - minDist; } } if(sl > 0) sl = NormalizeDouble(sl, digits); if(tp > 0) tp = NormalizeDouble(tp, digits); bool ok = false; if(type == ORDER_TYPE_BUY) ok = trade.Buy(volume, symbol, price, sl, tp, "TBH"); else ok = trade.Sell(volume, symbol, price, sl, tp, "TBH"); if(ok) { ulong ticket = trade.ResultOrder(); double fill = trade.ResultPrice(); // Market Execution brokers (FxPro, most ECN/STP) silently DROP the // inline SL/TP passed to trade.Buy/Sell — the deal fills but the // position opens NAKED. Enforce the bracket on the open position after // the fill. On Instant Execution brokers, where the inline stops stuck, // this is a no-op. if(sl > 0 || tp > 0) EnsureStops(symbol, sl, tp); // Report what the BROKER shows, not what we asked for: the server // flags the position NAKED if a requested stop isn't there. double gotSL = 0, gotTP = 0; ReadBracket(symbol, gotSL, gotTP); AckSignal(id, true, (long)ticket, fill, "", gotSL, gotTP, symbol, spec, volume); Print("Filled ", side, " ", symbol, " ", volume, " @ ", fill, " ticket=", ticket); } else { string err = trade.ResultRetcodeDescription(); AckSignal(id, false, 0, 0, err, -1, -1, symbol, spec, volume); Print("Order failed ", side, " ", symbol, ": ", err); } } //+------------------------------------------------------------------+ //| v1.50 — find the symbol THIS broker uses for a canonical name. | //| | //| Brokers name the same market differently (US500 / SPX500 / | //| US500.cash, NVDA / NVDA.US / #NVDA). Try the canonical name and | //| every alias exactly, then as a suffixed/prefixed variant. The | //| suffix rule is strict on purpose: 'DX' must not match DXCM, a | //| different stock. Same rule as metaapi_broker.suffix_ok(). | //+------------------------------------------------------------------+ bool SuffixOk(string rest) { if(StringLen(rest) == 0) return true; // v1.51: all digits = a different product (FxPro NDX365/WTI365 are // weekend-only); _Z26-style month code = a dated future that expires. bool digits = true; for(int i = 0; i < StringLen(rest); i++) { ushort d = StringGetCharacter(rest, i); if(d < '0' || d > '9') { digits = false; break; } } if(digits) return false; int L = StringLen(rest); if(L >= 3) { ushort m = StringGetCharacter(rest, L - 3); ushort d1 = StringGetCharacter(rest, L - 2); ushort d2 = StringGetCharacter(rest, L - 1); if(StringFind("FGHJKMNQUVXZ", ShortToString(m)) >= 0 && d1 >= '0' && d1 <= '9' && d2 >= '0' && d2 <= '9') return false; } ushort c = StringGetCharacter(rest, 0); if(c == '.' || c == '-' || c == '_' || c == '#' || c == '+' || c == '!') return true; string low = rest; StringToLower(low); return (StringLen(rest) <= 4 && low == rest); } bool Tradable(string sym) { bool custom = false; if(!SymbolExist(sym, custom)) return false; if(!SymbolSelect(sym, true)) return false; return (ENUM_SYMBOL_TRADE_MODE)SymbolInfoInteger(sym, SYMBOL_TRADE_MODE) != SYMBOL_TRADE_MODE_DISABLED; } string ResolveSymbol(string canonical, string aliasesCsv) { string cands[]; int n = 0; ArrayResize(cands, 1); cands[0] = canonical; n = 1; if(StringLen(aliasesCsv) > 0) { string extra[]; int k = StringSplit(aliasesCsv, ',', extra); for(int i = 0; i < k; i++) if(StringLen(extra[i]) > 0) { ArrayResize(cands, n + 1); cands[n++] = extra[i]; } } // 1. exact names for(int i = 0; i < n; i++) if(Tradable(cands[i])) return cands[i]; // 2. suffixed / '#'-prefixed variants. v1.51: candidates in ORDER (first // one with any match wins), shortest name within it. Shortest across all // of them picked SPX.L (Spirax-Sarco) over #USSPX500 on FxPro. int total = SymbolsTotal(false); for(int i = 0; i < n; i++) { string c = cands[i]; StringToUpper(c); string best = ""; for(int s = 0; s < total; s++) { string name = SymbolName(s, false); string core = (StringGetCharacter(name, 0) == '#') ? StringSubstr(name, 1) : name; string coreUp = core; StringToUpper(coreUp); if(StringFind(coreUp, c) != 0) continue; if(!SuffixOk(StringSubstr(core, StringLen(c)))) continue; if(best == "" || StringLen(name) < StringLen(best)) if(Tradable(name)) best = name; } if(best != "") return best; } return ""; } //+------------------------------------------------------------------+ //| USD → account currency. Tick value is quoted in the account's | //| currency, the server's notional in USD. Returns -1 if no rate. | //+------------------------------------------------------------------+ double UsdToAccount(double usd) { string cur = AccountInfoString(ACCOUNT_CURRENCY); if(cur == "USD" || cur == "") return usd; string direct = ResolveSymbol("USD" + cur, ""); if(direct != "") { double r = SymbolInfoDouble(direct, SYMBOL_BID); if(r > 0) return usd * r; } string inverse = ResolveSymbol(cur + "USD", ""); if(inverse != "") { double r = SymbolInfoDouble(inverse, SYMBOL_BID); if(r > 0) return usd / r; } return -1; } //+------------------------------------------------------------------+ //| USD notional → lots from the broker's own spec for `sym`. | //| Returns 0 with `why` set when it cannot be done safely. | //+------------------------------------------------------------------+ double LotsFromNotional(string sym, double notionalUsd, double price, string &spec, string &why) { double tickSize = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); double tickValue = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); double csize = SymbolInfoDouble(sym, SYMBOL_TRADE_CONTRACT_SIZE); double vmin = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); double vmax = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX); double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); spec = StringFormat("contract=%s tick=%s tick_value=%s %s min=%s step=%s max=%s", DoubleToString(csize, 4), DoubleToString(tickSize, 8), DoubleToString(tickValue, 6), AccountInfoString(ACCOUNT_CURRENCY), DoubleToString(vmin, 4), DoubleToString(step, 4), DoubleToString(vmax, 2)); why = ""; if(tickSize <= 0 || tickValue <= 0 || price <= 0) { why = "broker gave no tick value (market closed?)"; return 0; } double notional = UsdToAccount(notionalUsd); if(notional <= 0) { why = "no USD rate for account currency " + AccountInfoString(ACCOUNT_CURRENCY); return 0; } double lotValue = price / tickSize * tickValue; // one lot, in account currency double raw = notional / lotValue; if(step <= 0) step = 0.01; double lots = MathFloor(raw / step + 1e-9) * step; if(lots < vmin) { // A little over (<=1.5x) is accepted, as the old 0.01 floor did; more // would be a far larger bet than the strategy sized for. if(vmin <= raw * 1.5) lots = vmin; else { why = StringFormat("needs %s lots, broker minimum is %s", DoubleToString(raw, 4), DoubleToString(vmin, 4)); return 0; } } if(vmax > 0 && lots > vmax) { why = StringFormat("needs %s lots, broker maximum is %s", DoubleToString(raw, 2), DoubleToString(vmax, 2)); return 0; } return lots; } //+------------------------------------------------------------------+ //| Snap any volume to the broker's step and limits. | //+------------------------------------------------------------------+ double NormalizeLots(string sym, double lots) { double vmin = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); double vmax = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX); double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); if(step <= 0) step = 0.01; lots = MathFloor(lots / step + 1e-9) * step; if(lots < vmin) lots = vmin; if(vmax > 0 && lots > vmax) return 0; int digits = (int)MathMax(0, MathCeil(-MathLog10(step))); return NormalizeDouble(lots, digits); } //+------------------------------------------------------------------+ //| Enforce SL/TP on a freshly opened position. Market Execution | //| brokers ignore the inline stops on the deal, so set them here via | //| PositionModify. Retries a few times since the position may not be | //| registered on the first tick after the fill. | //+------------------------------------------------------------------+ void EnsureStops(string symbol, double slPrice, double tpPrice) { for(int attempt = 0; attempt < 5; attempt++) { for(int p = PositionsTotal() - 1; p >= 0; p--) { ulong ticket = PositionGetTicket(p); // selects the position too if(ticket == 0) continue; if(PositionGetString(POSITION_SYMBOL) != symbol) continue; if(PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue; double curSL = PositionGetDouble(POSITION_SL); double curTP = PositionGetDouble(POSITION_TP); // Already bracketed (inline stops stuck on an Instant broker). if((slPrice <= 0 || curSL > 0) && (tpPrice <= 0 || curTP > 0)) return; if(trade.PositionModify(ticket, slPrice, tpPrice)) { Print("Stops set on #", ticket, " sl=", slPrice, " tp=", tpPrice); return; } Print("PositionModify failed on #", ticket, ": ", trade.ResultRetcodeDescription()); } Sleep(300); } Print("EnsureStops: could not set SL/TP on ", symbol, " after 5 attempts"); } //+------------------------------------------------------------------+ //| Post ack back to server | //+------------------------------------------------------------------+ void ReadBracket(string symbol, double &slOut, double &tpOut) { for(int p = PositionsTotal() - 1; p >= 0; p--) { ulong t = PositionGetTicket(p); if(t == 0) continue; if(PositionGetString(POSITION_SYMBOL) != symbol) continue; if(PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue; slOut = PositionGetDouble(POSITION_SL); tpOut = PositionGetDouble(POSITION_TP); return; } } void AckSignal(int signalId, bool filled, long ticket, double fillPrice, string err, double fillSL = -1, double fillTP = -1, string brokerSym = "", string spec = "", double lots = 0) { string bracket = ""; if(fillSL >= 0) bracket = StringFormat(",\"fill_sl\":%s,\"fill_tp\":%s", DoubleToString(fillSL, 5), DoubleToString(fillTP, 5)); // v1.50: what the broker actually had — the symbol we resolved, the spec // we sized from and the lots we sent — so the dashboard can show it. if(brokerSym != "") bracket += StringFormat(",\"broker_symbol\":\"%s\"", EscapeJson(brokerSym)); if(spec != "") bracket += StringFormat(",\"broker_spec\":\"%s\"", EscapeJson(spec)); if(lots > 0) bracket += StringFormat(",\"volume\":%s", DoubleToString(lots, 4)); string body = StringFormat( "{\"secret_token\":\"%s\",\"signal_id\":%d,\"filled\":%s,\"ticket\":%I64d,\"fill_price\":%s,\"error_msg\":\"%s\"%s}", Token, signalId, filled ? "true" : "false", ticket, DoubleToString(fillPrice, 5), EscapeJson(err), bracket); string response; HttpPostJson(ServerURL + "/mt/ack", body, response); } //+------------------------------------------------------------------+ //| v1.52 — report positions of ours that were CLOSED | //| | //| Reads the terminal's deal history for closing deals (OUT, OUT_BY, | //| INOUT) since the stored cursor. A position is ours when its | //| opening deal or the closing deal carries our MagicNumber — a | //| broker SL/TP or stop-out deal may not carry the magic itself. Each | //| closing deal is sent once with the open side/time/price, close | //| time/price, DEAL_REASON, profit, commission and swap. Times go out | //| as UTC unix seconds (server time minus the server's GMT offset). | //+------------------------------------------------------------------+ string ClosedReason(long reason, long magic) { if(reason == DEAL_REASON_SL) return "sl"; if(reason == DEAL_REASON_TP) return "tp"; if(reason == DEAL_REASON_SO) return "stop_out"; if(reason == DEAL_REASON_EXPERT) return (magic == MagicNumber) ? "server_close" : "expert"; if(reason == DEAL_REASON_CLIENT || reason == DEAL_REASON_MOBILE || reason == DEAL_REASON_WEB) return "manual"; return "other"; } long ServerGmtOffset() { long off = (long)(TimeTradeServer() - TimeGMT()); // Round to the nearest quarter hour: the two clocks are read a moment // apart, and every real server offset is a multiple of 15 minutes. return (long)MathRound(off / 900.0) * 900; } void ReportClosed() { if(!closedDirty && TimeLocal() - closedLastRun < 60) return; long login = AccountInfoInteger(ACCOUNT_LOGIN); if(login <= 0) return; // not logged in yet closedLastRun = TimeLocal(); closedDirty = false; string gvT = StringFormat("TBH_CT_%I64d_%d", login, MagicNumber); string gvD = StringFormat("TBH_CD_%I64d_%d", login, MagicNumber); datetime curT = 0; ulong curD = 0; if(GlobalVariableCheck(gvT)) curT = (datetime)(long)GlobalVariableGet(gvT); if(GlobalVariableCheck(gvD)) curD = (ulong)GlobalVariableGet(gvD); datetime from = (curT > 0) ? curT : TimeCurrent() - (datetime)((long)MathMax(1, ClosedBackfillDays) * 86400); if(!HistorySelect(from, TimeCurrent() + 86400)) { closedDirty = true; return; } // Pass 1: copy the closing deals out — HistorySelectByPosition() below // replaces the selection, so nothing can be read from it afterwards. ClosedDeal cd[]; int n = 0; int total = HistoryDealsTotal(); for(int i = 0; i < total && n < CLOSED_BATCH * 5; i++) { ulong d = HistoryDealGetTicket(i); if(d == 0) continue; long entry = HistoryDealGetInteger(d, DEAL_ENTRY); if(entry != DEAL_ENTRY_OUT && entry != DEAL_ENTRY_OUT_BY && entry != DEAL_ENTRY_INOUT) continue; long type = HistoryDealGetInteger(d, DEAL_TYPE); if(type != DEAL_TYPE_BUY && type != DEAL_TYPE_SELL) continue; datetime t = (datetime)HistoryDealGetInteger(d, DEAL_TIME); if(t < curT || (t == curT && d <= curD)) continue; ArrayResize(cd, n + 1); cd[n].deal = d; cd[n].pos = (ulong)HistoryDealGetInteger(d, DEAL_POSITION_ID); cd[n].t = t; cd[n].price = HistoryDealGetDouble(d, DEAL_PRICE); cd[n].vol = HistoryDealGetDouble(d, DEAL_VOLUME); cd[n].profit = HistoryDealGetDouble(d, DEAL_PROFIT); cd[n].comm = HistoryDealGetDouble(d, DEAL_COMMISSION); cd[n].swap = HistoryDealGetDouble(d, DEAL_SWAP); cd[n].reason = HistoryDealGetInteger(d, DEAL_REASON); cd[n].magic = HistoryDealGetInteger(d, DEAL_MAGIC); cd[n].type = type; cd[n].symbol = HistoryDealGetString(d, DEAL_SYMBOL); n++; } if(n == 0) return; // Oldest first, so the cursor only ever moves forward over what was sent. for(int i = 1; i < n; i++) { ClosedDeal k = cd[i]; int j = i - 1; while(j >= 0 && (cd[j].t > k.t || (cd[j].t == k.t && cd[j].deal > k.deal))) { cd[j + 1] = cd[j]; j--; } cd[j + 1] = k; } // Pass 2: the opening deal of each position (side, time, price, magic). long off = ServerGmtOffset(); string items = ""; int sent = 0, used = 0; datetime lastT = curT; ulong lastD = curD; for(int i = 0; i < n && sent < CLOSED_BATCH; i++) { used++; lastT = cd[i].t; lastD = cd[i].deal; long inMagic = 0; double openPx = 0, openComm = 0; datetime openT = 0; string side = (cd[i].type == DEAL_TYPE_SELL) ? "buy" : "sell"; // closing a buy is a sell if(cd[i].pos > 0 && HistorySelectByPosition(cd[i].pos)) { int pd = HistoryDealsTotal(); for(int k = 0; k < pd; k++) { ulong d = HistoryDealGetTicket(k); if(d == 0) continue; if(HistoryDealGetInteger(d, DEAL_ENTRY) != DEAL_ENTRY_IN) continue; inMagic = HistoryDealGetInteger(d, DEAL_MAGIC); openPx = HistoryDealGetDouble(d, DEAL_PRICE); openT = (datetime)HistoryDealGetInteger(d, DEAL_TIME); openComm = HistoryDealGetDouble(d, DEAL_COMMISSION); side = (HistoryDealGetInteger(d, DEAL_TYPE) == DEAL_TYPE_BUY) ? "buy" : "sell"; break; } } if(inMagic != MagicNumber && cd[i].magic != MagicNumber) continue; // not ours double remaining = 0; if(cd[i].pos > 0 && PositionSelectByTicket(cd[i].pos)) remaining = PositionGetDouble(POSITION_VOLUME); int digits = (int)SymbolInfoInteger(cd[i].symbol, SYMBOL_DIGITS); if(digits <= 0) digits = 5; if(StringLen(items) > 0) items += ","; items += StringFormat( "{\"position_ticket\":%I64u,\"deal_ticket\":%I64u,\"symbol\":\"%s\",\"side\":\"%s\"," "\"volume\":%s,\"open_time\":%I64d,\"open_price\":%s,\"close_time\":%I64d,\"close_price\":%s," "\"reason\":\"%s\",\"deal_reason\":%I64d,\"profit\":%s,\"commission\":%s," "\"open_commission\":%s,\"swap\":%s,\"remaining\":%s}", cd[i].pos, cd[i].deal, EscapeJson(cd[i].symbol), side, DoubleToString(cd[i].vol, 4), openT > 0 ? (long)openT - off : (long)0, DoubleToString(openPx, digits), (long)cd[i].t - off, DoubleToString(cd[i].price, digits), ClosedReason(cd[i].reason, cd[i].magic), cd[i].reason, DoubleToString(cd[i].profit, 2), DoubleToString(cd[i].comm, 2), DoubleToString(openComm, 2), DoubleToString(cd[i].swap, 2), DoubleToString(remaining, 4)); sent++; } if(sent > 0) { string body = StringFormat("{\"secret_token\":\"%s\",\"ea_version\":\"%s\",\"trades\":[%s]}", Token, EA_VERSION, items); string response; if(!HttpPostJson(ServerURL + "/mt/closed", body, response)) { // Server down or older than 1.52: keep the cursor, retry in 60 s. if(VerboseLog) Print("Closed-trade report not accepted: ", response); return; } Print("Reported ", sent, " closed position deal(s) to the dashboard"); } // Advance past everything examined — sent or not ours — and persist it. GlobalVariableSet(gvT, (double)(long)lastT); GlobalVariableSet(gvD, (double)lastD); GlobalVariablesFlush(); if(used < n) closedDirty = true; // more left: next poll continues } //+------------------------------------------------------------------+ //| HTTP POST JSON | //+------------------------------------------------------------------+ bool HttpPostJson(string url, string body, string &response) { char post[], result[]; string headers = "Content-Type: application/json\r\n"; string resultHeaders = ""; StringToCharArray(body, post, 0, StringLen(body)); int code = WebRequest("POST", url, headers, 8000, post, result, resultHeaders); if(code < 0) { response = "WebRequest err " + IntegerToString(GetLastError()) + " — is " + url + " in Tools → Options → WebRequest allowed URLs?"; return false; } response = CharArrayToString(result); return (code >= 200 && code < 300); } //+------------------------------------------------------------------+ //| Naive JSON helpers — enough for our flat objects | //+------------------------------------------------------------------+ string JsonString(string json, string key) { int p = StringFind(json, "\"" + key + "\":\""); if(p < 0) return ""; p += StringLen(key) + 4; int end = StringFind(json, "\"", p); return (end < 0) ? "" : StringSubstr(json, p, end - p); } double JsonNumber(string json, string key) { int p = StringFind(json, "\"" + key + "\":"); if(p < 0) return 0.0; p += StringLen(key) + 3; string tail = StringSubstr(json, p); // Trim leading whitespace + read until non-numeric int len = StringLen(tail); string num = ""; for(int i = 0; i < len; i++) { ushort c = StringGetCharacter(tail, i); if((c >= '0' && c <= '9') || c == '.' || c == '-') num += ShortToString(c); else if(StringLen(num) > 0) break; } return StringToDouble(num); } int SplitByDelim(string source, string delim, string &parts[]) { ArrayResize(parts, 0); int start = 0; int idx; while((idx = StringFind(source, delim, start)) >= 0) { ArrayResize(parts, ArraySize(parts) + 1); parts[ArraySize(parts) - 1] = StringSubstr(source, start, idx - start); start = idx + StringLen(delim); } ArrayResize(parts, ArraySize(parts) + 1); parts[ArraySize(parts) - 1] = StringSubstr(source, start); return ArraySize(parts); } string EscapeJson(string s) { string r = ""; int n = StringLen(s); for(int i = 0; i < n; i++) { ushort c = StringGetCharacter(s, i); if(c == '"' || c == '\\') { r += "\\"; r += ShortToString(c); } else if(c == '\n') r += "\\n"; else if(c == '\r') r += "\\r"; else r += ShortToString(c); } return r; } //+------------------------------------------------------------------+