#ifndef NEURAL_NET_MQH #define NEURAL_NET_MQH // --------------------------------------------------------------------------- // NeuralNet.mqh — trade-outcome model, run natively in MT5 (ONNX). 2026-11-10. // // Until v7.31 every prediction was a WebRequest to the vizion-nn container (/predict). // The model now runs here: vizion-nn is a weekly job that trains, checks the ONNX export // against sklearn (<=1e-5) and writes two files into MQL5/Files/VizionAI/: // nn_trade.onnx the active model (float input [N,29] -> label, probabilities [N,2]) // nn_trade.cfg version=..., min_p=..., min_edge=..., n_features=29 (key=value lines) // The EA re-reads nn_trade.cfg every NN_ReloadSeconds and swaps the model when the version // changes, so a retrain goes live without a recompile. version=none -> NN stays neutral. // // NN_Featurize() is a line-by-line port of trade_model.featurize(); NN_OnnxPredict() of // TradePredictor.predict(). Keep them in step with the Python side. // --------------------------------------------------------------------------- #include "NNFeatures.mqh" #define NN_NFEAT 29 long g_nn_onnx = INVALID_HANDLE; string g_nn_version = ""; double g_nn_min_p = 0.55; double g_nn_min_edge = 0.05; bool g_nn_extra_on[10]; // which EXTRAS the active model was trained with (cfg "extras") datetime g_nn_cfg_check = 0; double NN_NaN() { return MathSqrt(-1.0); } double NN_Sign(const double x) { return (x > 0.0) ? 1.0 : ((x < 0.0) ? -1.0 : 0.0); } double NN_Tanh(const double x) { if(x > 20.0) return 1.0; if(x < -20.0) return -1.0; double e = MathExp(2.0 * x); return (e - 1.0) / (e + 1.0); } // EXTRAS in trade_model.py order. Only those the model's cfg lists are filled; the rest are NaN, // exactly like training (the old /predict payload carried none, nn_entries.tsv carries 0-2). double NN_Extra(const int i) { if(i < 0 || i >= 10 || !g_nn_extra_on[i]) return NN_NaN(); switch(i) { case 0: return Coordinator_Cluster_Strength; // cluster_strength case 1: return Coordinator_Conflict_Score; // conflict_score case 2: return (double)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD); // spread_points } return NN_NaN(); } void NN_Featurize(const double &fv[], const bool is_buy, matrixf &X, const ulong row) { double f[12]; for(int i = 0; i < 12; i++) f[i] = (i < ArraySize(fv)) ? fv[i] : 0.0; double s = is_buy ? 1.0 : -1.0; double den = MathAbs(f[0]) + MathAbs(f[1]) + MathAbs(f[2]) + MathAbs(f[3]) + 1e-9; double fden = MathAbs(f[10]) + MathAbs(f[11]) + 1e-9; // computed in double like Python, rounded to float on store (training uses the same rounding) for(int k = 0; k < 4; k++) X[row][k] = (float)(s * f[k] / den); X[row][4] = (float)(s * NN_Sign(f[4])); X[row][5] = (float)(s * NN_Sign(f[5])); X[row][6] = (float)(s * NN_Tanh(f[4] / (MathAbs(f[0]) + 1e-9))); X[row][7] = (float)(s * NN_Tanh(f[5] / (MathAbs(f[1]) + 1e-9))); X[row][8] = (float)(f[6] / 100.0); X[row][9] = (float)(f[7] / 100.0); X[row][10] = (float)(s * (f[6] - 50.0) / 50.0); X[row][11] = (float)(f[8] / 50.0); X[row][12] = (float)f[9]; X[row][13] = (float)(s * f[10] / fden); X[row][14] = (float)(s * f[11] / fden); X[row][15] = (float)s; for(int e = 0; e < 10; e++) X[row][16 + e] = (float)NN_Extra(e); // EXTRAS for(int d = 0; d < 3; d++) X[row][26 + d] = (float)NN_NaN(); // DIR_EXTRAS (news_bias, ma_trend, above_ma50) } // ─── model files ───────────────────────────────────────────────────────────── bool NN_ReadCfg(string &version, double &min_p, double &min_edge, int &nfeat, string &extras) { int h = FileOpen(NN_ModelDir + "\\nn_trade.cfg", FILE_READ|FILE_TXT|FILE_ANSI|FILE_SHARE_READ|FILE_SHARE_WRITE); if(h == INVALID_HANDLE) return false; version = ""; nfeat = 0; extras = ""; while(!FileIsEnding(h)) { string line = FileReadString(h); int eq = StringFind(line, "="); if(eq <= 0) continue; string k = StringSubstr(line, 0, eq), v = StringSubstr(line, eq + 1); StringTrimRight(v); if(k == "version") version = v; if(k == "min_p") min_p = StringToDouble(v); if(k == "min_edge") min_edge = StringToDouble(v); if(k == "n_features") nfeat = (int)StringToInteger(v); if(k == "extras") extras = v; } FileClose(h); return version != ""; } void NN_ReleaseModel() { if(g_nn_onnx != INVALID_HANDLE) OnnxRelease(g_nn_onnx); g_nn_onnx = INVALID_HANDLE; } // Load or swap the model when nn_trade.cfg names a new version. Cheap: one small file read. void NN_RefreshModel(const bool force) { datetime now = TimeLocal(); if(!force && now - g_nn_cfg_check < NN_ReloadSeconds) return; g_nn_cfg_check = now; string ver, ex; double mp = g_nn_min_p, me = g_nn_min_edge; int nf = 0; if(!NN_ReadCfg(ver, mp, me, nf, ex)) { if(g_nn_onnx == INVALID_HANDLE) NN_Explain = "no model file (" + NN_ModelDir + "\\nn_trade.cfg)"; return; // keep whatever is loaded } if(ver == g_nn_version && (g_nn_onnx != INVALID_HANDLE || ver == "none")) return; NN_ReleaseModel(); g_nn_version = ver; if(ver == "none") { NN_Explain = "no promoted trade model yet"; return; } if(nf != NN_NFEAT) { NN_Explain = "model wants " + IntegerToString(nf) + " features, EA builds " + IntegerToString(NN_NFEAT); return; } long h = OnnxCreate(NN_ModelDir + "\\nn_trade.onnx", ONNX_DEFAULT); if(h == INVALID_HANDLE) { NN_Explain = "OnnxCreate failed " + IntegerToString(GetLastError()); Print("NN: ", NN_Explain); return; } const ulong in_shape[] = {2, NN_NFEAT}; const ulong lab_shape[] = {2}; const ulong pr_shape[] = {2, 2}; if(!OnnxSetInputShape(h, 0, in_shape) || !OnnxSetOutputShape(h, 0, lab_shape) || !OnnxSetOutputShape(h, 1, pr_shape)) { NN_Explain = "ONNX shape setup failed " + IntegerToString(GetLastError()); Print("NN: ", NN_Explain); OnnxRelease(h); return; } g_nn_onnx = h; g_nn_min_p = mp; g_nn_min_edge = me; ArrayInitialize(g_nn_extra_on, false); string parts[]; int np = StringSplit(ex, ',', parts); for(int i = 0; i < np; i++) { int idx = (int)StringToInteger(parts[i]); if(StringLen(parts[i]) > 0 && idx >= 0 && idx < 10) g_nn_extra_on[idx] = true; } Print("NN: loaded ", ver, " (ONNX, min_p=", DoubleToString(mp, 2), " min_edge=", DoubleToString(me, 2), " extras=", (ex == "" ? "none" : ex), ")"); } // ─── predict ───────────────────────────────────────────────────────────────── bool NN_OnnxPredict(const double &fv[], double &p_buy, double &p_sell) { if(g_nn_onnx == INVALID_HANDLE) return false; matrixf X(2, NN_NFEAT); NN_Featurize(fv, true, X, 0); NN_Featurize(fv, false, X, 1); long label[2]; matrixf probs(2, 2); if(!OnnxRun(g_nn_onnx, ONNX_NO_CONVERSION, X, label, probs)) { NN_Explain = "OnnxRun failed " + IntegerToString(GetLastError()); return false; } p_buy = probs[0][1]; p_sell = probs[1][1]; return true; } // ─── self-test: Python <-> MT5 parity, on every start ─────────────────────── // vizion-nn writes nn_selftest.onnx + nn_selftest.tsv (raw features \t featurized \t p_win from // onnxruntime). Re-featurize here with extras off, run the model, compare. Logs one line. void NN_SelfTest() { string dir = NN_ModelDir + "\\"; int h = FileOpen(dir + "nn_selftest.tsv", FILE_READ|FILE_TXT|FILE_ANSI|FILE_SHARE_READ|FILE_SHARE_WRITE); if(h == INVALID_HANDLE) return; long m = OnnxCreate(dir + "nn_selftest.onnx", ONNX_DEFAULT); if(m == INVALID_HANDLE) { FileClose(h); Print("NN selftest FAIL: OnnxCreate ", GetLastError()); return; } const ulong in_shape[] = {2, NN_NFEAT}; const ulong lab_shape[] = {2}; const ulong pr_shape[] = {2, 2}; OnnxSetInputShape(m, 0, in_shape); OnnxSetOutputShape(m, 0, lab_shape); OnnxSetOutputShape(m, 1, pr_shape); bool saved[10]; ArrayCopy(saved, g_nn_extra_on); ArrayInitialize(g_nn_extra_on, false); // the reference rows were featurized without extras int rows = 0; double feat_diff = 0.0, p_diff = 0.0; bool run_ok = true; while(!FileIsEnding(h)) { string line = FileReadString(h); string col[]; if(StringSplit(line, '\t', col) < 3) continue; string a[], b[]; int na = StringSplit(col[0], ',', a), nb = StringSplit(col[1], ',', b); if(nb != NN_NFEAT) continue; double fv[]; ArrayResize(fv, na); for(int i = 0; i < na; i++) fv[i] = StringToDouble(a[i]); matrixf X(2, NN_NFEAT); NN_Featurize(fv, true, X, 0); NN_Featurize(fv, true, X, 1); for(int j = 0; j < NN_NFEAT; j++) { bool ref_nan = (b[j] == "nan"), ea_nan = !MathIsValidNumber(X[0][j]); if(ref_nan != ea_nan) feat_diff = 1e9; else if(!ref_nan) feat_diff = MathMax(feat_diff, MathAbs(X[0][j] - StringToDouble(b[j]))); } long lab[2]; matrixf pr(2, 2); if(!OnnxRun(m, ONNX_NO_CONVERSION, X, lab, pr)) { run_ok = false; break; } p_diff = MathMax(p_diff, MathAbs(pr[0][1] - StringToDouble(col[2]))); rows++; } FileClose(h); OnnxRelease(m); ArrayCopy(g_nn_extra_on, saved); bool pass = run_ok && rows > 0 && feat_diff <= 1e-5 && p_diff <= 1e-4; Print("NN selftest ", (pass ? "PASS" : "FAIL"), ": rows=", rows, " feature_diff=", DoubleToString(feat_diff, 8), " p_diff=", DoubleToString(p_diff, 8), (run_ok ? "" : " OnnxRun error " + IntegerToString(GetLastError()))); } bool InitializeNeuralNet() { if(!Use_NeuralNet) return false; NN_Initialized = true; NN_LastRun = 0; NN_Bias = 0; NN_Confidence = 0.0; NN_RiskScore = 50.0; NN_Explain = "NN init ok"; g_nn_version = ""; NN_RefreshModel(true); NN_SelfTest(); // cheap (8 rows); every chart logs PASS/FAIL return true; } void ReleaseNeuralNet() { NN_ReleaseModel(); g_nn_version = ""; } bool UpdateNeuralNetSignal() { NN_UsedLastTick = false; if(!Use_NeuralNet || !NN_Initialized) return false; datetime now = TimeCurrent(); if(NN_LastRun > 0 && (now - NN_LastRun) < NN_CooldownSeconds) return false; NN_RefreshModel(false); double feat[]; if(BuildNNFeatures(feat) <= 0) return false; double p_buy = 0.0, p_sell = 0.0; if(!NN_OnnxPredict(feat, p_buy, p_sell)) { NN_Bias = 0; NN_Confidence = 0.0; NN_RiskScore = 100.0; // no model = not usable return false; } // Same rule as TradePredictor.predict(): vote only when that side is likely to win AND // clearly better than the other side. double best = MathMax(p_buy, p_sell), other = MathMin(p_buy, p_sell); int d = (p_buy >= p_sell) ? 1 : -1; bool vote = (best >= g_nn_min_p && best - other >= g_nn_min_edge); NN_Bias = vote ? d : 0; NN_Confidence = NN_Clamp(best * 100.0, 0.0, 100.0); NN_RiskScore = NN_Clamp((1.0 - best) * 100.0, 0.0, 100.0); NN_Explain = g_nn_version + " p_buy=" + DoubleToString(p_buy, 2) + " p_sell=" + DoubleToString(p_sell, 2); NN_LastRun = now; NN_UsedLastTick = true; if(NN_DebugPrint) Print("NN => bias=", NN_Bias, " conf=", DoubleToString(NN_Confidence, 1), " risk=", DoubleToString(NN_RiskScore, 1), " | ", NN_Explain); return true; } bool NN_IsUsable() { if(!Use_NeuralNet || !NN_Initialized) return false; if(g_nn_onnx == INVALID_HANDLE) return false; if(NN_Confidence < NN_MinConfidenceToUse) return false; if(NN_RiskScore > NN_MaxRiskToUse) return false; return true; } #endif