Vizion-Trading-EA/profitgtx.mq5
335 行
12 KiB
MQL5
//+------------------------------------------------------------------+
//| profitgtx.mq5 |
//| Trading EA entrypoint (profitgtx) |
//| Base: AlgoForge RSI-Stoch-MA-EA modular v5.8 |
//| Extensions: News bias, SignalCoordinator, NN logging, AI Gateway|
//+------------------------------------------------------------------+
#property copyright "QuarterTheory x VIZION"
#property version "7.32"
// v7.32 (2026-11-10) NN runs in MT5 (ONNX, MQL5/Files/VizionAI/nn_trade.onnx, hot-swapped by version) instead of the vizion-nn server; every trade logs entry features to nn_entries.tsv (labelled from broker P/L); AUTO deploy probe uses n8n /healthz; ONNX self-test at start
// v7.31 (2026-11-09) entry upgrades: MAGNET-WALK-UP / FIB-BREAK / FIB-RECLAIM trade a failed break the other way unless H1+H4 agree (MAGNET-UP always in London); MAGNET-WALK-DN uses break-retest outside London; structure stops
// v7.30 (2026-11-09) setup fixes: MAGNET-WALK-UP skips 7-12 UTC and is small on XAUUSD/US Tech 100; FIB-BREAK-UP needs H1+H4 trend agreement; MAGNET-WALK-DN small against H1; optional hour probation (off)
// v7.29 (2026-11-09) setup conditions from the setup review: no entry against the H1 EMA20 slope; MAGNET-WALK-UP / FIB-BREAK-UP small against the H1 trend; small size in quiet markets (except MAGNET-WALK-DN)
// v7.28 (2026-11-09) per-action gateway timeouts: validate_trade 15 s, report_trade/reconcile 30 s, others 5 s
// v7.27 (2026-11-09) weekly ladder: the leader scores the 20 ladder symbols hourly (research_scores); first sync/research 10 min after start
// v7.26 (2026-11-09) trade reports carry the account; the rotation leader re-sends 48h of closed positions every 30 min (broker values)
// v7.25 (2026-11-09) R-based exits: break-even at +1.5R, trail 1.5R from +2R, target unchanged (exit study: early BE/trail at +0.67R gave away ~70% of the edge)
// v7.24 (2026-11-09) rotation closes only charts it opened itself; hand-opened charts are never closed
// v7.23 (2026-11-09) watchlist rotation: 20-symbol watchlist, the ranker's top 10 trade; the leader chart opens and
// closes EA charts; new symbols trade at 0.25 size until they have 20 trades; Trade_Symbols -> Trade_Symbols_Fixed ("")
// v7.22 (2026-11-09) daily loss limit = 5% of start-of-day balance (was a flat 100), latched for the rest of the
// server day; coordinator logs "no signals" instead of "conflict 100" for an empty cluster
// v7.21 (2026-11-09) a chart that started while the AI gateway was down retries it every minute
// (it used to stay offline until reloaded and, with AI_Strict_Gate, refuse every trade)
// v7.20 (2026-11-09) learning upgrades - setups are upgraded from their record, never removed:
// - re-entries arm only after a winning / break-even parent (after a win: 71 re-entries 87% won +4,492;
// after a loss: 80 re-entries 4% won -7,947, 2026-10-09..11-06)
// - same-side stacking cap and no adding to a losing side (2026-11-06: 12 XAUUSD SELLs from 4 setups
// stacked into one rally, about -5,800)
// - daily loss limit counts open losses too
// - CHOP-SNAP moves from the blocklist to probation (trades at reduced size while it rebuilds a record)
#property strict
#include <Trade/Trade.mqh>
CTrade Trade;
// Base configuration
#include "Config.mqh"
#include "InputParams.mqh"
#include "GlobalVariables.mqh"
// Utilities + core systems
#include "Utilities.mqh"
#include "Indicators.mqh"
#include "RiskGuards.mqh"
#include "RiskSizing.mqh"
#include "FibLevels.mqh"
#include "TradePolicy.mqh"
#include "Warnings.mqh"
#include "Praise.mqh"
#include "PatternCoordinator.mqh"
// Advanced systems
#include "MATheory.mqh"
#include "MarketState.mqh"
#include "ReEntry.mqh"
#include "PositionManagement.mqh"
#include "EntryUpgrade.mqh"
#include "TradeExecution.mqh"
#include "SignalCoordinator.mqh"
#include "NewsEngine.mqh"
#include "ChartLabels.mqh"
#include "TradingSetups.mqh"
// AI systems
#include "AISignalConfirmation.mqh"
#include "MasterAICoordinator.mqh"
#include "TradeSync.mqh"
#include "LadderResearch.mqh"
#include "Rotation.mqh"
int OnInit()
{
// Trade object config
Trade.SetExpertMagicNumber(MagicNumber);
Trade.SetDeviationInPoints(50);
Trade.SetTypeFilling(ORDER_FILLING_FOK);
if(!InitializeIndicators())
return INIT_FAILED;
MAT_Init();
ArrayInitialize(SetupCount, 0);
ArrayInitialize(LastEntryTime, 0);
InitializeSignalCoordinator();
PanelInit(); // restores a dragged panel position, if any
ApplySymbolProfile();
InitReEntry();
InitNewsEngine();
UpdateNewsEngine();
CalculateLevels();
if(Show_Levels) DrawLevels();
// Resolve live URLs (AUTO probes internal NN; LAPTOP/CONTAINER use fixed set)
// Must run before InitializeAIGateway() which uses g_gw_url
AutoDetectDeployment();
// AI Gateway (advisory: EA starts even if gateway is unreachable)
bool gw_ok = InitializeAIGateway();
if(!gw_ok)
return INIT_FAILED; // Only fails when AI_Mode="mandatory" and gateway is down
InitAISession();
if(!InitializeMasterAI())
{
// Master AI unavailable — EA runs with NN + pattern system only
}
else
{
SetUseNeuralNetwork(true);
SetUseAIGateway(AI_Mode != "off");
SetRequireAIValidation(AI_Mode == "mandatory");
}
// Fetch initial D1 briefing if gateway is active
if(GW_Initialized && AI_Briefing_D1)
{
GW_Brief_D1 = AIFetchBriefing("D1");
if(StringLen(GW_Brief_D1) > 0)
DisplayAIBriefing(GW_Brief_D1);
Last_GW_Briefing_D1 = TimeCurrent();
}
EventSetTimer(MathMax(5, News_Update_Seconds));
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
EventKillTimer();
MAT_Release();
ReleaseIndicators();
CleanupLevels();
CleanupLabels();
CleanupMasterAI();
}
// Chart snapshot for remote review (2026-09-17): MQL5\Files izion\chart_<symbol>_<tf>.png
void SaveChartSnapshot()
{
static datetime last = 0;
if(Chart_Snapshot_Sec <= 0 || TimeCurrent() - last < Chart_Snapshot_Sec) return;
last = TimeCurrent();
string sym = _Symbol; StringReplace(sym, " ", "_");
string tf = StringSubstr(EnumToString((ENUM_TIMEFRAMES)Period()), 7);
ChartScreenShot(0, "vizion\\chart_" + sym + "_" + tf + ".png", 1600, 900, ALIGN_RIGHT);
}
void OnTimer()
{
RotationTick();
UpdateNewsEngine();
SaveChartSnapshot();
if(!GW_Initialized || AI_Mode == "off")
return;
datetime now = TimeCurrent();
MqlDateTime dt;
TimeToStruct(now, dt);
// M1 briefing — refresh every minute
if(AI_Briefing_M1 && now - Last_GW_Briefing_M1 >= 60)
{
string b = AIFetchBriefing("M1");
if(StringLen(b) > 0) GW_Brief_M1 = b;
Last_GW_Briefing_M1 = now;
}
// M5 briefing — refresh every 5 minutes
if(AI_Briefing_M5 && now - Last_GW_Briefing_M5 >= 300)
{
string b = AIFetchBriefing("M5");
if(StringLen(b) > 0) GW_Brief_M5 = b;
Last_GW_Briefing_M5 = now;
}
// M15 briefing — refresh every 15 minutes
if(AI_Briefing_M15 && now - Last_GW_Briefing_M15 >= 900)
{
string b = AIFetchBriefing("M15");
if(StringLen(b) > 0) GW_Brief_M15 = b;
Last_GW_Briefing_M15 = now;
}
// M30 briefing — refresh every 30 minutes
if(AI_Briefing_M30 && now - Last_GW_Briefing_M30 >= 1800)
{
string b = AIFetchBriefing("M30");
if(StringLen(b) > 0) GW_Brief_M30 = b;
Last_GW_Briefing_M30 = now;
}
// H1 briefing — refresh when a new H1 bar has opened
if(AI_Briefing_H1 && now - Last_GW_Briefing_H1 >= 3600)
{
string b = AIFetchBriefing("H1");
if(StringLen(b) > 0) GW_Brief_H1 = b;
Last_GW_Briefing_H1 = now;
}
// H4 briefing — refresh every 4 hours
if(AI_Briefing_H4 && now - Last_GW_Briefing_H4 >= 14400)
{
string b = AIFetchBriefing("H4");
if(StringLen(b) > 0) GW_Brief_H4 = b;
Last_GW_Briefing_H4 = now;
AIFetchSessionBriefing();
}
// D1 briefing — at configured hour, at most once per day
if(AI_Briefing_D1 && dt.hour == AI_Briefing_Hour && now - Last_GW_Briefing_D1 > 3600)
{
string b = AIFetchBriefing("D1");
if(StringLen(b) > 0)
{
GW_Brief_D1 = b;
DisplayAIBriefing(b);
}
Last_GW_Briefing_D1 = now;
}
}
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
// Dragging the panel background repositions the whole panel.
PanelHandleEvent(id, sparam);
}
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
if(trans.type != TRADE_TRANSACTION_DEAL_ADD)
return;
ulong deal_ticket = trans.deal;
if(!HistoryDealSelect(deal_ticket))
return;
long entry = HistoryDealGetInteger(deal_ticket, DEAL_ENTRY);
if(entry != DEAL_ENTRY_OUT && entry != DEAL_ENTRY_INOUT)
return; // Only process closing deals
// OnTradeTransaction fires on EVERY chart for every deal in the account. Without this
// filter each EA instance reported every close under its own _Symbol (4 charts = 4 rows,
// 3 of them mislabelled). Report only our own deals on this chart's symbol.
if(HistoryDealGetString(deal_ticket, DEAL_SYMBOL) != _Symbol) return;
if(HistoryDealGetInteger(deal_ticket, DEAL_MAGIC) != MagicNumber) return;
// Real setup name for this position (captured at entry) — read before labeling consumes it
ulong pos_id = (ulong)HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
string setup = NN_SetupForPosition(pos_id);
if(StringLen(setup) == 0) setup = "auto";
// Label and write the NN training record for this closed trade
NN_LabelFromDeal(deal_ticket);
double profit = HistoryDealGetDouble(deal_ticket, DEAL_PROFIT);
string symbol = HistoryDealGetString(deal_ticket, DEAL_SYMBOL);
long deal_type = HistoryDealGetInteger(deal_ticket, DEAL_TYPE);
// Duration: from the position's opening deal to this closing deal (the old code measured
// the closing deal against itself and always reported 0).
// 2026-11-04: direction and setup also come from the OPENING deal. The closing deal of a BUY
// is a SELL, so every report so far had the direction inverted (97 of 108 checked against
// nn_dataset_trades.csv). The setup was only in memory (lost on every EA restart -> "auto"
// for 99% of trades); OpenBuy/OpenSell put it in the order comment, which the deal keeps.
datetime close_time = (datetime)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
datetime open_time = close_time;
long entry_type = -1;
string entry_comment = "";
if(HistorySelectByPosition(pos_id))
{
for(int i = 0; i < HistoryDealsTotal(); ++i)
{
ulong t = HistoryDealGetTicket(i);
if(t != 0 && HistoryDealGetInteger(t, DEAL_ENTRY) == DEAL_ENTRY_IN)
{
open_time = (datetime)HistoryDealGetInteger(t, DEAL_TIME);
entry_type = HistoryDealGetInteger(t, DEAL_TYPE);
entry_comment = HistoryDealGetString(t, DEAL_COMMENT);
break;
}
}
HistoryDealSelect(deal_ticket); // restore selection for the reads below
}
int duration_min = (int)((close_time - open_time) / 60);
string direction = (entry_type >= 0) ? ((entry_type == DEAL_TYPE_BUY) ? "BUY" : "SELL")
: ((deal_type == DEAL_TYPE_BUY) ? "SELL" : "BUY");
if(setup == "auto" && StringLen(entry_comment) > 0) setup = entry_comment;
AIReportTrade(profit, setup, direction, duration_min, pos_id);
}
void OnTick()
{
UpdateIndicators();
MAT_Update();
UpdateMasterAI();
DetectWarnings();
DetectPraiseSignals();
static int tick_count = 0;
tick_count++;
if(tick_count >= 100)
{
CalculateLevels();
if(Show_Levels) DrawLevels();
tick_count = 0;
}
UpdateModeAndState();
CoordinateAllSignals();
ManagePositions();
EU_Tick(); // v7.31 entry-upgrade watches (once per closed M1 bar)
ExecuteReEntries();
ExecuteMATheorySetups();
ExecuteMAFloorCeilingSetups();
ExecuteMARetestAndRejectionSetups();
ExecuteContinuationSetups();
ExecuteRangeSetups();
ExecuteChopSetups();
ExecuteForceEntrySetups();
UpdateLabels();
}