| #ifndef AI_GATEWAY_MQH
|
| #define AI_GATEWAY_MQH
|
|
|
| // ---------------------------------------------------------------------------
|
| // AIGateway.mqh — Unified AI Gateway for profitgtx
|
| // Routes EA requests through n8n → OpenRouter → Claude Sonnet
|
| // Actions: validate_trade, get_briefing, get_session, get_news_bias,
|
| // report_trade, watchlist_status, ping
|
| //
|
| // URL routing is handled by AutoDetectDeployment() which sets g_gw_url.
|
| // ---------------------------------------------------------------------------
|
|
|
| string GW_LastError = "";
|
|
|
| // ─── v7.34: Strategy Tester HTTP (WinINet) ─────────────────────────────────────
|
| // MT5 blocks WebRequest() inside the Strategy Tester (error 4014). Local tester agents may call DLLs, so backtests
|
| // reach the gateway through Windows' WinINet instead and the EA trades with its real AI gate. Live charts never use
|
| // this path: they keep WebRequest(). Handles are 64-bit pointers (long).
|
| #import "wininet.dll"
|
| long InternetOpenW(string agent, int accessType, string proxy, string bypass, int flags);
|
| long InternetConnectW(long hInternet, string server, int port, string user, string password, int service, int flags, long context);
|
| long HttpOpenRequestW(long hConnect, string verb, string object, string version, string referrer, long acceptTypes, int flags, long context);
|
| int HttpSendRequestW(long hRequest, string headers, int headersLength, uchar &optional[], int optionalLength);
|
| int HttpQueryInfoW(long hRequest, int infoLevel, int &buffer[], int &bufferLength, int &index);
|
| int InternetReadFile(long hFile, uchar &buffer[], int toRead, int &bytesRead);
|
| int InternetSetOptionW(long hInternet, int option, int &buffer[], int bufferLength);
|
| int InternetCloseHandle(long hInternet);
|
| #import
|
|
|
| bool GWIsTester() { return (bool)MQLInfoInteger(MQL_TESTER); }
|
|
|
| // POST json to an http:// URL with WinINet. Returns the HTTP status (0 on transport failure).
|
| int GWHttpPostWinInet(const string url, const string headers, const string body, const int timeout_ms, string &response)
|
| {
|
| response = "";
|
| string rest = url;
|
| if(StringFind(rest, "http://") == 0) rest = StringSubstr(rest, 7);
|
| int slash = StringFind(rest, "/");
|
| string hostport = (slash >= 0) ? StringSubstr(rest, 0, slash) : rest;
|
| string path = (slash >= 0) ? StringSubstr(rest, slash) : "/";
|
| int colon = StringFind(hostport, ":");
|
| string host = (colon >= 0) ? StringSubstr(hostport, 0, colon) : hostport;
|
| int port = (colon >= 0) ? (int)StringToInteger(StringSubstr(hostport, colon + 1)) : 80;
|
|
|
| long hNet = InternetOpenW("profitgtx-tester", 1, "", "", 0);
|
| if(hNet == 0) return 0;
|
| int to[1]; to[0] = timeout_ms;
|
| InternetSetOptionW(hNet, 2, to, 4); // INTERNET_OPTION_CONNECT_TIMEOUT
|
| InternetSetOptionW(hNet, 5, to, 4); // INTERNET_OPTION_SEND_TIMEOUT
|
| InternetSetOptionW(hNet, 6, to, 4); // INTERNET_OPTION_RECEIVE_TIMEOUT
|
| long hConn = InternetConnectW(hNet, host, port, "", "", 3, 0, 0); // INTERNET_SERVICE_HTTP
|
| long hReq = (hConn != 0) ? HttpOpenRequestW(hConn, "POST", path, "HTTP/1.1", "", 0, (int)0x84000000, 0) : 0; // RELOAD | NO_CACHE_WRITE
|
| int status = 0;
|
| if(hReq != 0)
|
| {
|
| uchar data[];
|
| int n = StringToCharArray(body, data, 0, WHOLE_ARRAY, CP_UTF8);
|
| if(n > 0 && data[n - 1] == 0) n--; // drop the terminating zero
|
| if(HttpSendRequestW(hReq, headers, StringLen(headers), data, n) != 0)
|
| {
|
| int code[1]; int len = 4; int idx = 0;
|
| if(HttpQueryInfoW(hReq, 19 | 0x20000000, code, len, idx) != 0) status = code[0]; // STATUS_CODE | FLAG_NUMBER
|
| uchar buf[8192]; int got = 0; uchar all[]; int total = 0;
|
| while(InternetReadFile(hReq, buf, 8192, got) != 0 && got > 0)
|
| {
|
| ArrayResize(all, total + got);
|
| ArrayCopy(all, buf, total, 0, got);
|
| total += got;
|
| }
|
| if(total > 0) response = CharArrayToString(all, 0, total, CP_UTF8);
|
| }
|
| InternetCloseHandle(hReq);
|
| }
|
| if(hConn != 0) InternetCloseHandle(hConn);
|
| InternetCloseHandle(hNet);
|
| return status;
|
| }
|
|
|
| // ─── JSON helpers ────────────────────────────────────────────────────────────
|
|
|
| string GWJsonEscape(const string s)
|
| {
|
| string x = s;
|
| StringReplace(x, "\\", "\\\\");
|
| StringReplace(x, "\"", "\\\"");
|
| StringReplace(x, "\n", " ");
|
| StringReplace(x, "\r", " ");
|
| return x;
|
| }
|
|
|
| bool GWExtractString(const string &json, const string &key, string &out)
|
| {
|
| int k = StringFind(json, "\"" + key + "\"");
|
| if(k < 0) return false;
|
| int colon = StringFind(json, ":", k);
|
| if(colon < 0) return false;
|
| int q1 = StringFind(json, "\"", colon + 1);
|
| if(q1 < 0) return false;
|
| int q2 = StringFind(json, "\"", q1 + 1);
|
| if(q2 < 0) return false;
|
| out = StringSubstr(json, q1 + 1, q2 - q1 - 1);
|
| return true;
|
| }
|
|
|
| bool GWExtractNumber(const string &json, const string &key, double &out)
|
| {
|
| int k = StringFind(json, "\"" + key + "\"");
|
| if(k < 0) return false;
|
| int colon = StringFind(json, ":", k);
|
| if(colon < 0) return false;
|
| int endComma = StringFind(json, ",", colon);
|
| int endBrace = StringFind(json, "}", colon);
|
| int end = endComma;
|
| if(end < 0 || (endBrace >= 0 && endBrace < end)) end = endBrace;
|
| if(end < 0) return false;
|
| string val = StringSubstr(json, colon + 1, end - (colon + 1));
|
| StringTrimLeft(val);
|
| StringTrimRight(val);
|
| out = StringToDouble(val);
|
| return true;
|
| }
|
|
|
| bool GWExtractBool(const string &json, const string &key, bool &out)
|
| {
|
| int k = StringFind(json, "\"" + key + "\"");
|
| if(k < 0) return false;
|
| int colon = StringFind(json, ":", k);
|
| if(colon < 0) return false;
|
| string rest = StringSubstr(json, colon + 1, 10);
|
| StringTrimLeft(rest);
|
| StringToLower(rest);
|
| out = (StringFind(rest, "true") == 0);
|
| return true;
|
| }
|
|
|
| // ─── Deployment auto-detection ────────────────────────────────────────────────
|
| //
|
| // Probes the internal NN endpoint with a 1.5 s timeout.
|
| // If it responds (any HTTP code) → container socat bridges are up → use internal URLs.
|
| // Otherwise → laptop / VPN → use public HTTPS URLs.
|
| // DeploymentProfile input overrides AUTO behaviour.
|
|
|
| void AutoDetectDeployment()
|
| {
|
| if(DeploymentProfile == "CONTAINER")
|
| {
|
| g_nn_url = NN_URL_Internal;
|
| g_gw_url = GW_URL_Internal;
|
| g_is_container = true;
|
| Print("Deploy: CONTAINER (manual) | NN=", g_nn_url, " | GW=", g_gw_url);
|
| return;
|
| }
|
|
|
| if(DeploymentProfile == "LAPTOP")
|
| {
|
| g_nn_url = NN_URL_Laptop;
|
| g_gw_url = GW_URL_Laptop;
|
| g_is_container = false;
|
| Print("Deploy: LAPTOP (manual) | NN=", g_nn_url, " | GW=", g_gw_url);
|
| return;
|
| }
|
|
|
| // v7.34: Strategy Tester -> the backtest clone of the gateway (WebRequest is blocked in the tester).
|
| if(GWIsTester())
|
| {
|
| g_nn_url = NN_URL_Internal;
|
| g_gw_url = GW_URL_Backtest;
|
| g_is_container = true;
|
| Print("Deploy: TESTER -> backtest gateway via WinINet | GW=", g_gw_url, " | dlls_allowed=", (int)MQLInfoInteger(MQL_DLLS_ALLOWED));
|
| return;
|
| }
|
|
|
| // AUTO — probe internal NN endpoint
|
| // 2026-11-10: probe n8n's /healthz on the internal gateway host. It used to probe the NN
|
| // server, which no longer runs (the model is ONNX in the EA).
|
| string probe_url = GW_URL_Internal;
|
| int scheme_end = StringFind(probe_url, "://");
|
| int path_start = (scheme_end >= 0) ? StringFind(probe_url, "/", scheme_end + 3) : -1;
|
| if(path_start > 0) probe_url = StringSubstr(probe_url, 0, path_start);
|
| probe_url += "/healthz";
|
| char probe_data[], probe_result[];
|
| string probe_resp_headers;
|
|
|
| ResetLastError();
|
| int code = WebRequest("GET", probe_url, "", 1500,
|
| probe_data, probe_result, probe_resp_headers);
|
|
|
| if(code > 0) // any server response means the internal host is reachable
|
| {
|
| g_nn_url = NN_URL_Internal;
|
| g_gw_url = GW_URL_Internal;
|
| g_is_container = true;
|
| Print("Deploy: AUTO → CONTAINER (internal n8n responded HTTP ", code, ")");
|
| }
|
| else
|
| {
|
| g_nn_url = NN_URL_Laptop;
|
| g_gw_url = GW_URL_Laptop;
|
| g_is_container = false;
|
| Print("Deploy: AUTO → LAPTOP (internal n8n unreachable, err=", GetLastError(), ") — using HTTPS");
|
| }
|
|
|
| Print(" NN URL: ", g_nn_url);
|
| Print(" GW URL: ", g_gw_url);
|
| }
|
|
|
| // ─── Core HTTP POST ───────────────────────────────────────────────────────────
|
|
|
| bool GatewayRequest(const string action, const string json_payload, string &response)
|
| {
|
| if(AI_Mode == "off")
|
| return false;
|
|
|
| if(StringLen(g_gw_url) < 10)
|
| {
|
| GW_LastError = "Gateway URL not resolved (AutoDetectDeployment not called?)";
|
| return false;
|
| }
|
|
|
| string headers = "Content-Type: application/json\r\n";
|
| if(StringLen(AI_Gateway_Token) > 0)
|
| headers += "X-Gateway-Token: " + AI_Gateway_Token + "\r\n";
|
|
|
| char post_data[], result_data[];
|
| string result_headers;
|
| StringToCharArray(json_payload, post_data, 0, StringLen(json_payload), CP_UTF8);
|
|
|
| ResetLastError();
|
| int timeout = AI_TimeoutMs; // v7.28: per-action timeouts
|
| if(action == "validate_trade") timeout = MathMax(AI_TimeoutMs, AI_Validate_TimeoutMs);
|
| else if(action == "report_trade") timeout = MathMax(AI_TimeoutMs, AI_Report_TimeoutMs);
|
| else if(action == "ping") timeout = MathMax(AI_TimeoutMs, 10000); // v7.33: a slow ping marked the gateway offline and (strict gate) refused every trade
|
| // v7.34: in the Strategy Tester send through WinINet to the backtest gateway, marking the request as a backtest
|
| // with the simulated time so the gateway uses history up to that moment and writes nothing live.
|
| if(GWIsTester())
|
| {
|
| string sim = TimeToString(TimeGMT(), TIME_DATE | TIME_SECONDS);
|
| StringReplace(sim, ".", "-");
|
| StringReplace(sim, " ", "T");
|
| string body = json_payload;
|
| if(StringGetCharacter(body, 0) == '{')
|
| body = "{\"backtest\":true,\"sim_time\":\"" + sim + "Z\"," + StringSubstr(body, 1);
|
| string resp_t;
|
| int code_t = GWHttpPostWinInet(g_gw_url, headers, body, timeout, resp_t);
|
| if(code_t <= 0 || code_t >= 400)
|
| {
|
| GW_LastError = "TESTER HTTP " + IntegerToString(code_t);
|
| GW_Status = "ERROR";
|
| return false;
|
| }
|
| response = resp_t;
|
| GW_Status = "ACTIVE";
|
| return true;
|
| }
|
| int code = WebRequest("POST", g_gw_url, headers, timeout, post_data, result_data, result_headers);
|
|
|
| if(code <= 0 || code >= 400)
|
| {
|
| GW_LastError = "HTTP " + IntegerToString(code) + " err=" + IntegerToString(GetLastError());
|
| GW_Status = "ERROR";
|
| return false;
|
| }
|
|
|
| response = CharArrayToString(result_data, 0, -1, CP_UTF8);
|
| GW_Status = "ACTIVE";
|
| return true;
|
| }
|
|
|
| // ─── Initialize ───────────────────────────────────────────────────────────────
|
|
|
| bool InitializeAIGateway()
|
| {
|
| GW_Initialized = false;
|
| GW_Status = "NOT_INIT";
|
| GW_LastError = "";
|
|
|
| if(AI_Mode == "off")
|
| {
|
| GW_Status = "DISABLED";
|
| Print("AIGateway: Mode=off — AI calls disabled");
|
| return true;
|
| }
|
|
|
| string ping = "{\"action\":\"ping\",\"symbol\":\"" + GWJsonEscape(_Symbol) + "\"}";
|
| string resp;
|
|
|
| if(!GatewayRequest("ping", ping, resp))
|
| {
|
| if(AI_Mode == "advisory")
|
| {
|
| Print("AIGateway: Gateway unreachable — advisory mode, EA runs without AI gate | ", GW_LastError);
|
| GW_Status = "OFFLINE_ADVISORY";
|
| return true;
|
| }
|
| Print("AIGateway: Gateway init FAILED (mandatory mode) — ", GW_LastError);
|
| return false;
|
| }
|
|
|
| GW_Initialized = true;
|
| GW_Status = "ACTIVE";
|
| Print("AIGateway: OK | URL=", g_gw_url, " | Mode=", AI_Mode,
|
| " | env=", (g_is_container ? "CONTAINER" : "LAPTOP"));
|
| return true;
|
| }
|
|
|
| bool IsAIEnabled() { return GW_Initialized; }
|
|
|
| // ─── Trade Validation ────────────────────────────────────────────────────────
|
|
|
| int GetSLPoints(const bool continuation);
|
| int GetTPPoints(const bool continuation);
|
|
|
| // Last refusal per direction (0=sell,1=buy) so a setup that fires every tick doesn't re-ask the
|
| // gateway every tick (2026-09-17: XAUUSD M5 was making ~1 OpenAI call per 1.5 s).
|
| datetime g_ai_last_refusal_time[2] = {0, 0};
|
| string g_ai_last_refusal_note[2] = {"", ""};
|
|
|
| bool AIValidateTrade(const string setup_name, const bool is_buy, double &size_multiplier)
|
| {
|
| if(AI_Mode == "off")
|
| return true;
|
|
|
| // v7.21 (2026-11-09): a chart that started while n8n was down stayed gateway-offline until it was
|
| // reloaded, and with AI_Strict_Gate it refused every trade. Retry the ping once a minute instead.
|
| if(!GW_Initialized)
|
| {
|
| static datetime last_gw_retry = 0;
|
| if(TimeCurrent() - last_gw_retry >= 60)
|
| {
|
| last_gw_retry = TimeCurrent();
|
| // v7.33: a chart that started before Docker locked onto the public URL (12-17 s connects);
|
| // re-probe so it switches to the local n8n as soon as that answers.
|
| if(DeploymentProfile == "AUTO" && !g_is_container) AutoDetectDeployment();
|
| InitializeAIGateway();
|
| if(GW_Initialized) Print("AIGateway: reconnected after being offline");
|
| }
|
| }
|
| if(!GW_Initialized)
|
| {
|
| if(AI_Mode == "advisory" && !AI_Strict_Gate) { size_multiplier *= 0.5; return true; }
|
| return false;
|
| }
|
|
|
| if(Use_Watchlist_Rotation && !IsSymbolActiveTrading(_Symbol))
|
| {
|
| Last_AI_Analysis = "[WL] " + _Symbol + " not in active-trading top-10";
|
| return false;
|
| }
|
|
|
| string dir = is_buy ? "BUY" : "SELL";
|
| int di = is_buy ? 1 : 0;
|
| if(AI_Reask_Sec > 0 && g_ai_last_refusal_time[di] > 0 && TimeCurrent() - g_ai_last_refusal_time[di] < AI_Reask_Sec)
|
| {
|
| static datetime last_cached_note[2] = {0, 0};
|
| if(TimeCurrent() - last_cached_note[di] >= 30)
|
| {
|
| Print("AI gate: ", dir, " still refused (", g_ai_last_refusal_note[di], ") - re-ask in ",
|
| (int)(AI_Reask_Sec - (TimeCurrent() - g_ai_last_refusal_time[di])), "s");
|
| last_cached_note[di] = TimeCurrent();
|
| }
|
| return false;
|
| }
|
| string payload = "{";
|
| payload += "\"action\":\"validate_trade\",";
|
| payload += "\"symbol\":\"" + GWJsonEscape(_Symbol) + "\",";
|
| payload += "\"timeframe\":\"" + EnumToString((ENUM_TIMEFRAMES)Period()) + "\",";
|
| payload += "\"direction\":\"" + dir + "\",";
|
| payload += "\"setup\":\"" + GWJsonEscape(setup_name) + "\",";
|
| payload += "\"nn_bias\":" + IntegerToString(NN_Bias) + ",";
|
| payload += "\"nn_confidence\":" + DoubleToString(NN_Confidence, 2) + ",";
|
| payload += "\"mode\":\"" + GWJsonEscape(ModeToString(Current_Mode)) + "\",";
|
| payload += "\"state\":\"" + GWJsonEscape(StateToString(Current_State)) + "\",";
|
| payload += "\"warnings\":" + IntegerToString(Active_Warnings) + ",";
|
| payload += "\"praise\":" + IntegerToString(Active_Praise_Signals) + ",";
|
| payload += "\"cluster_strength\":" + DoubleToString(Coordinator_Cluster_Strength, 2) + ",";
|
| payload += "\"conflict_score\":" + DoubleToString(Coordinator_Conflict_Score, 2) + ",";
|
| payload += "\"news_bias\":" + IntegerToString(News_Bias_Direction) + ",";
|
| payload += "\"news_strength\":" + DoubleToString(News_Bias_Strength, 2) + ",";
|
| payload += "\"news_block\":" + (News_Trade_Block_Active || GW_News_Block_Flag ? "true" : "false") + ",";
|
| payload += "\"news_allowed_direction\":" + IntegerToString(News_Trade_Allowed_Direction) + ",";
|
| double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
|
| double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
|
| // the stops the order will actually use (ATR-scaled when Use_ATR_Exits), not the legacy manual points
|
| bool cont = (Current_Mode == MODE_TRENDING && Current_State == STATE_CONTINUATION);
|
| double sl_pts = GetSLPoints(cont) * point;
|
| double tp_pts = GetTPPoints(cont) * point;
|
| payload += "\"bias\":\"" + (Current_Bias_Direction > 0 ? "BULL" : Current_Bias_Direction < 0 ? "BEAR" : "NEUTRAL") + "\",";
|
| payload += "\"atr\":" + DoubleToString(Current_ATR, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS)) + ",";
|
| payload += "\"adx\":" + DoubleToString(Current_ADX, 1) + ",";
|
| payload += "\"session\":\"" + GWJsonEscape(GW_Session_Name + " " + GW_Session_Phase) + "\",";
|
| payload += "\"nn_status\":\"" + (NN_Bias == 0 ? "no signal (model stale, ignore)" : "signal") + "\",";
|
| if(Use_MA_Theory)
|
| {
|
| payload += "\"ma_trend_7x50\":\"" + MAT_TrendText() + "\",";
|
| payload += "\"ma_momentum\":" + IntegerToString(MAT_Momentum()) + ",";
|
| payload += "\"ma_stack\":\"" + (MAT_Stack() > 0 ? "7>14>21" : MAT_Stack() < 0 ? "7<14<21" : "mixed") + "\",";
|
| payload += "\"ma_htf\":\"" + MAT_HTFText() + "\",";
|
| payload += "\"ma_big\":\"" + MAT_BigMAText() + "\",";
|
| payload += "\"ma_momentum_score\":" + IntegerToString(MAT_MomentumScore()) + ",";
|
| }
|
| double est_sl = is_buy ? bid - sl_pts : bid + sl_pts;
|
| double est_tp = is_buy ? bid + tp_pts : bid - tp_pts;
|
| payload += "\"entry\":" + DoubleToString(bid, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS)) + ",";
|
| payload += "\"sl\":" + DoubleToString(est_sl, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS)) + ",";
|
| payload += "\"tp\":" + DoubleToString(est_tp, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
|
| payload += "}";
|
|
|
| string resp;
|
| if(!GatewayRequest("validate_trade", payload, resp))
|
| {
|
| if(AI_Mode == "advisory" && !AI_Strict_Gate) { size_multiplier *= 0.5; return true; }
|
| return false;
|
| }
|
|
|
| string decision = "", reason = "";
|
| double confidence = 70.0, new_mult = 1.0;
|
| GWExtractString(resp, "decision", decision);
|
| GWExtractString(resp, "reason", reason);
|
| GWExtractNumber(resp, "confidence", confidence);
|
| GWExtractNumber(resp, "size_multiplier", new_mult);
|
|
|
| Last_AI_Analysis = "[GW:" + dir + "] " + decision + " | " + reason;
|
|
|
| string u = decision;
|
| StringToUpper(u);
|
|
|
| // Order matters: "MAYBE" is tested before "NO" ("maybe not" style replies) and before "YES".
|
| if(StringFind(u, "MAYBE") >= 0)
|
| {
|
| string why = "";
|
| if(!AI_Accept_Maybe)
|
| why = "MAYBE not accepted (AI_Accept_Maybe=false)";
|
| else if(confidence < AI_Maybe_Min_Confidence)
|
| why = "confidence " + DoubleToString(confidence, 0) + " < " + DoubleToString(AI_Maybe_Min_Confidence, 0);
|
| else if(AI_Maybe_Require_Bias && Current_Mode == MODE_TRENDING && Current_Bias_Direction != 0)
|
| {
|
| // Direction the STATE expects: with the trend in CONTINUATION, against it in a
|
| // pullback/reversal when Pullback_Trade_Direction is COUNTER (same rule as setups).
|
| bool with_trend = (is_buy == (Current_Bias_Direction > 0));
|
| bool cont = (Current_State == STATE_CONTINUATION);
|
| bool expected = cont ? with_trend
|
| : (Pullback_Trade_Direction == PB_COUNTER_TREND ? !with_trend
|
| : Pullback_Trade_Direction == PB_WITH_TREND ? with_trend : true);
|
| if(!expected)
|
| why = cont ? "against Bias in CONTINUATION" : "with-trend entry in a pullback (counter-trend mode)";
|
| }
|
| else if(AI_Maybe_Require_Trending && Current_Mode != MODE_TRENDING)
|
| why = "Mode not TRENDING";
|
|
|
| if(StringLen(why) > 0)
|
| {
|
| Print("AI gate: MAYBE rejected for ", dir, " - ", why, " | ", reason);
|
| g_ai_last_refusal_time[di] = TimeCurrent(); g_ai_last_refusal_note[di] = "MAYBE: " + why;
|
| AI_Validation_Rejects++;
|
| return false;
|
| }
|
| double m = AI_Maybe_Size_Mult;
|
| if(new_mult > 0.0 && new_mult < m) m = new_mult;
|
| size_multiplier *= MathMax(0.1, m);
|
| ApplySymbolProbation(size_multiplier);
|
| Print("AI gate: MAYBE accepted for ", dir, " (conf ", DoubleToString(confidence, 0), ", x", DoubleToString(m, 2), ") | ", reason);
|
| AI_Validation_Accepts++;
|
| return true;
|
| }
|
| if(StringFind(u, "YES") >= 0)
|
| {
|
| size_multiplier *= MathMax(0.1, new_mult);
|
| ApplySymbolProbation(size_multiplier);
|
| Print("AI gate: YES for ", dir, " (conf ", DoubleToString(confidence, 0), ") | ", reason);
|
| AI_Validation_Accepts++;
|
| return true;
|
| }
|
| if(StringFind(u, "NO") >= 0)
|
| {
|
| Print("AI gate: NO for ", dir, " (conf ", DoubleToString(confidence, 0), ") | ", reason);
|
| g_ai_last_refusal_time[di] = TimeCurrent(); g_ai_last_refusal_note[di] = "NO conf " + DoubleToString(confidence, 0);
|
| AI_Validation_Rejects++;
|
| return false;
|
| }
|
|
|
| // Unknown response — fall back to advisory behaviour
|
| if(AI_Mode == "advisory" && !AI_Strict_Gate) { size_multiplier *= 0.5; return true; }
|
| AI_Validation_Rejects++;
|
| return false;
|
| }
|
|
|
| // ─── Multi-TF Briefing ───────────────────────────────────────────────────────
|
|
|
| string AIFetchBriefing(const string tf_str)
|
| {
|
| if(AI_Mode == "off" || !GW_Initialized)
|
| return "";
|
|
|
| // v7.34: briefings are chart text only (nothing in the trading logic reads them). In the Strategy Tester they
|
| // would cost ~70 AI calls per simulated hour per chart without changing a single trade, so skip them there.
|
| if(GWIsTester()) return "";
|
|
|
| string payload = "{";
|
| payload += "\"action\":\"get_briefing\",";
|
| payload += "\"symbol\":\"" + GWJsonEscape(_Symbol) + "\",";
|
| payload += "\"timeframe\":\"" + tf_str + "\",";
|
| payload += "\"price\":" + DoubleToString(iClose(_Symbol, PERIOD_CURRENT, 0), 5) + ",";
|
| payload += "\"session\":\"" + GWJsonEscape(GW_Session_Name) + "\"";
|
| payload += "}";
|
|
|
| string resp;
|
| if(!GatewayRequest("get_briefing", payload, resp))
|
| return "";
|
|
|
| string bias = "", regime = "", plan = "", reason = "";
|
| GWExtractString(resp, "bias", bias);
|
| GWExtractString(resp, "regime", regime);
|
| GWExtractString(resp, "plan", plan);
|
| GWExtractString(resp, "reason", reason);
|
|
|
| // One short phrase per timeframe: the whole recommendation for that TF
|
| // condensed to a call plus a few words of context, matching the style of
|
| // the news line. No confidence percentage — the panel shows a call, not a
|
| // score, and a number there said nothing a reader could act on.
|
| string low = bias;
|
| StringToLower(low);
|
| string action = "HOLD";
|
| if(StringFind(low, "bull") >= 0) action = "BUY";
|
| else if(StringFind(low, "bear") >= 0) action = "SELL";
|
|
|
| // Context, shortest useful first: an explicit reason from the gateway, else
|
| // the regime word, else fall back to the plan text.
|
| string note = reason;
|
| if(StringLen(note) == 0) note = regime;
|
| if(StringLen(note) == 0) note = plan;
|
|
|
| if(StringLen(note) == 0)
|
| return tf_str + ": " + action;
|
| return tf_str + ": " + action + " " + note;
|
| }
|
|
|
| // ─── Session Briefing ────────────────────────────────────────────────────────
|
|
|
| void AIFetchSessionBriefing()
|
| {
|
| if(AI_Mode == "off" || !GW_Initialized)
|
| return;
|
|
|
| datetime now = TimeCurrent();
|
| MqlDateTime dt;
|
| TimeToStruct(now, dt);
|
| string server_time = StringFormat("%04d-%02d-%02d %02d:%02d",
|
| dt.year, dt.mon, dt.day, dt.hour, dt.min);
|
|
|
| string payload = "{";
|
| payload += "\"action\":\"get_session\",";
|
| payload += "\"symbol\":\"" + GWJsonEscape(_Symbol) + "\",";
|
| payload += "\"server_time\":\"" + server_time + "\",";
|
| payload += "\"price\":" + DoubleToString(iClose(_Symbol, PERIOD_CURRENT, 0), 5) + ",";
|
| payload += "\"h4_bias\":\"" + GWJsonEscape(GW_Brief_H4) + "\"";
|
| payload += "}";
|
|
|
| string resp;
|
| if(!GatewayRequest("get_session", payload, resp))
|
| return;
|
|
|
| GWExtractString(resp, "phase", GW_Session_Phase);
|
| GWExtractString(resp, "session", GW_Session_Name);
|
| GWExtractNumber(resp, "confidence", GW_Session_Confidence);
|
| }
|
|
|
| // ─── Live News Bias ──────────────────────────────────────────────────────────
|
| //
|
| // Enriched payload: sends actual MT5 calendar event details (name, currency,
|
| // actual vs forecast, importance, minutes_until) so Claude can reason about
|
| // the specific event rather than just the symbol name.
|
|
|
| void AIFetchNewsBias()
|
| {
|
| if(AI_Mode == "off" || !GW_Initialized)
|
| return;
|
|
|
| // v7.34: in the Strategy Tester the backtest gateway has no historical news feed and answers neutral, which never
|
| // overrides the local news bias, so the call (every 30 simulated seconds) is skipped: same result, much faster.
|
| if(GWIsTester()) return;
|
|
|
| string payload = "{";
|
| payload += "\"action\":\"get_news_bias\",";
|
| payload += "\"symbol\":\"" + GWJsonEscape(_Symbol) + "\",";
|
| payload += "\"timeframe\":\"" + EnumToString((ENUM_TIMEFRAMES)Period()) + "\",";
|
| payload += "\"base_currency\":\"" + g_symbol_base + "\",";
|
| payload += "\"quote_currency\":\"" + g_symbol_quote + "\",";
|
| payload += "\"local_bias\":" + IntegerToString(News_Bias_Direction) + ",";
|
| payload += "\"local_strength\":" + DoubleToString(News_Bias_Strength, 2) + ",";
|
| payload += "\"pending_events\":" + News_Pending_Events_JSON;
|
| payload += "}";
|
|
|
| string resp;
|
| if(!GatewayRequest("get_news_bias", payload, resp))
|
| return;
|
|
|
| double bias_dir = 0.0, bias_str = 0.0;
|
| bool block_flag = false;
|
| string headlines = "";
|
|
|
| GWExtractNumber(resp, "bias_direction", bias_dir);
|
| GWExtractNumber(resp, "bias_strength", bias_str);
|
| GWExtractBool(resp, "news_block_flag", block_flag);
|
| GWExtractString(resp, "headlines", headlines);
|
|
|
| // Override local news bias only if gateway provides a stronger signal
|
| if(MathAbs(bias_dir) > 0.0 && bias_str > News_Bias_Strength)
|
| {
|
| News_Bias_Direction = (int)MathRound(bias_dir);
|
| News_Bias_Strength = bias_str;
|
| }
|
|
|
| if(block_flag)
|
| GW_News_Block_Flag = true;
|
|
|
| if(StringLen(headlines) > 0)
|
| GW_News_Headlines = headlines;
|
| }
|
|
|
| // ─── Trade Reporting (fire-and-forget after position close) ─────────────────
|
|
|
| void AIReportTrade(const double profit, const string setup, const string direction, const int duration_min, const ulong ticket = 0)
|
| {
|
| if(AI_Mode == "off")
|
| return;
|
|
|
| string payload = "{";
|
| payload += "\"action\":\"report_trade\",";
|
| payload += "\"symbol\":\"" + GWJsonEscape(_Symbol) + "\",";
|
| payload += "\"profit\":" + DoubleToString(profit, 2) + ",";
|
| payload += "\"setup\":\"" + GWJsonEscape(setup) + "\",";
|
| payload += "\"direction\":\"" + direction + "\",";
|
| payload += "\"duration_min\":" + IntegerToString(duration_min) + ",";
|
| payload += "\"dir_src\":\"entry\","; // 2026-11-04: direction is the position's, not the closing deal's
|
| payload += "\"account\":\"" + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + "\","; // v7.26: rows are per account
|
| payload += "\"server\":\"" + GWJsonEscape(AccountInfoString(ACCOUNT_SERVER)) + "\",";
|
| payload += "\"ticket\":" + IntegerToString((long)ticket);
|
| payload += "}";
|
|
|
| string resp;
|
| GatewayRequest("report_trade", payload, resp); // ignore result
|
| }
|
|
|
| // ─── Watchlist Status ────────────────────────────────────────────────────────
|
|
|
| // v7.23: cached for Rotation_Check_Seconds (was a gateway call on every check); fails open.
|
| bool IsSymbolActiveTrading(const string symbol)
|
| {
|
| if(!Use_Watchlist_Rotation || !GW_Initialized)
|
| return true;
|
|
|
| static datetime last_check = 0;
|
| if(last_check > 0 && TimeCurrent() - last_check < MathMax(60, Rotation_Check_Seconds))
|
| return GW_Symbol_Active;
|
| last_check = TimeCurrent();
|
|
|
| string payload = "{\"action\":\"watchlist_status\",\"symbol\":\"" + GWJsonEscape(symbol) + "\"}";
|
| string resp;
|
| if(!GatewayRequest("watchlist_status", payload, resp))
|
| return GW_Symbol_Active; // keep the last answer (true at start): fail open
|
|
|
| bool active = true;
|
| double trades = -1.0;
|
| GWExtractBool(resp, "active", active);
|
| if(GWExtractNumber(resp, "trade_count", trades)) GW_Symbol_TradeCount = (int)trades;
|
| if(active != GW_Symbol_Active)
|
| Print("Watchlist: ", symbol, active ? " is in the active rotation - entries allowed" : " left the active rotation - manage-only");
|
| GW_Symbol_Active = active;
|
| return active;
|
| }
|
|
|
| // v7.23: a symbol new to the rotation trades small until it has New_Symbol_Min_Trades in 30 days.
|
| void ApplySymbolProbation(double &size_multiplier)
|
| {
|
| if(!Use_Watchlist_Rotation || New_Symbol_Size_Mult <= 0.0 || New_Symbol_Size_Mult >= 1.0) return;
|
| if(GW_Symbol_TradeCount < 0 || GW_Symbol_TradeCount >= New_Symbol_Min_Trades) return;
|
| size_multiplier *= New_Symbol_Size_Mult;
|
| Print("Watchlist: ", _Symbol, " on new-symbol probation (", GW_Symbol_TradeCount, "/", New_Symbol_Min_Trades,
|
| " trades in 30d) - size x", DoubleToString(New_Symbol_Size_Mult, 2));
|
| }
|
|
|
| #endif
|