VANTH Agentic AI Native Trading Architecture for MetaTrader 5

VANTH Agentic AI Native Trading Architecture for MetaTrader 5

7 June 2026, 16:41
Giordan Cogotti
0
50

Introduction: Why static rule‑based EAs are no longer enoughFor most retail traders, an “Expert Advisor” still means a bundle of hard‑coded rules wrapped inside OnTick: if indicator A is above level X and indicator B crosses indicator C, the EA fires a trade, places a fixed stop, and waits. These systems automate execution, but they do not reason about the market, the account, or their own recent behavior.

This approach assumes that the statistical properties of the market remain close to the period on which the strategy was optimized. When volatility, spread structure, or intraday flow patterns change regime, the same rule set continues to act as if nothing had changed, often leading to a sudden decay in performance. The strategy has no concept of market regime, no notion of account‑level risk state, and no memory of whether its signals have been working or failing in the recent environment.

In practical terms, static EAs try to solve a non‑stationary, multi‑layered problem with a single layer of fixed logic. The device may be perfectly functional, but it is fundamentally mismatched to the complexity of the system it is controlling.

The central idea behind VANTH is to move from automation to agency: away from “if conditions then trade” toward an EA that observes, reasons, remembers, and acts under explicit risk and capital‑preservation constraints.

From automation to agency: what “agentic AI” means in tradingIn current AI literature, a clear distinction is drawn between automated systems and agentic systems.

Automation is about executing predefined steps reliably: given inputs, run rules, produce outputs. Agency is about agents that pursue goals, maintain internal state, reason about context, and select actions under constraints.

An agentic AI system is typically characterized by three properties:
It maintains a representation of its goals (for example, “do not breach a daily loss limit” and “prioritize higher‑quality opportunities when risk budget is scarce”).
It maintains memory of past interactions and outcomes, allowing it to adapt behavior over time and avoid repeating past mistakes blindly.
It can call tools and services—risk engines, model APIs, data sources—and integrate their outputs into its decisions.

When applied to trading, the agent is not simply a “signal generator”. It is a decision‑making layer that decides whether now is an appropriate time to take risk, whether the trade fits into the current portfolio and risk state, and how to manage a position once it is open.

In other words, a truly agentic EA must answer questions that static EAs barely recognize as questions at all, for example:
Is the account already close to a daily or weekly loss limit?
Is the current opportunity adding to a crowded currency exposure or diversifying it?
Is the market in a clean trend, a genuine range, or a noisy drift where most “setup patterns” are simply short‑term mean‑reversion noise?
Has this type of signal been performing poorly over the last N trades or N days, to the point that the EA should reduce aggression or temporarily stand aside?

VANTH is designed explicitly around these questions. It is not just an EA that “uses AI”. It is a complete agentic‑AI native architecture built on top of MetaTrader 5.

VANTH as an AI‑native architecture on MetaTrader 5VANTH is not implemented as a single monolithic .mq5 file with everything in one place. Instead, it is organized as a set of clearly separated layers, each with a well‑defined responsibility: configuration, AI engine, risk manager, entry engine, position manager, memory, mesh, and dashboard.

At the top, a core orchestrator owns and coordinates all subsystems:
it loads configuration and constructs a runtime configuration object;
it initializes indicator engines, memory, entry, and position managers per symbol (“lanes”);
it maintains a multi‑symbol lane registry, spreading AI evaluations in a round‑robin fashion via the timer event, so that asynchronous WebRequest calls do not block the entire EA;
it integrates with the MetaTrader events (OnInit, OnTick, OnTimer, OnTradeTransaction, OnDeinit), forwarding each to the appropriate subsystem.

That core layer does not decide which trade to take, where to place stops, or how to trail. It delegates those decisions to specialized modules, and in particular to the agentic AI layer, which is treated as a first‑class component rather than an afterthought.

From an engineering perspective, this architectural choice is crucial. It allows the EA to evolve over time by upgrading individual layers—for example, the AI decision engine, the risk governance logic, or the memory subsystem—without rewriting the entire system or breaking backward compatibility.

Configuration as a contract between trader and agentInstead of scattering input variables across multiple files, VANTH centralizes configuration in a single struct (VanthConfig) that aggregates identity, AI providers, runtime behavior, strategy engines, risk limits, memory, mesh, dashboard, and tester options.

The configuration is organized into logical groups such as:
Identity – node ID, node role (solo, master, agent), multi‑symbol enable flag, curated symbol basket.
AI Models and Providers – primary and secondary model selection, model overrides per slot and per provider (for example, Azure OpenAI or self‑hosted gateways).
AI Runtime – timeouts, retries, minimum interval between calls, caching behavior, and minimum confidence threshold for live trades.
News Filter – whether to enrich prompts with macro context and whether to enforce trading blackouts around high‑impact events based on the native MT5 Economic Calendar.
Strategy Engines – primary timeframe, choice of entry engine (Pending Momentum, Mean Reversion, Sacred Phi, AI Dynamic, Hybrid), intrabar versus bar‑close evaluation, session and day filters.
Position Management – position‑management mode, partial‑closing enable flags, AI‑managed stops/targets, hard stop/target defaults, time‑based exits, and ATR‑based AI backstop.
Risk – risk per trade, maximum open trades, daily and weekly loss limits, maximum drawdown, currency and correlation exposure caps, margin‑level floor, spread‑regime controls, and prop‑firm profile settings.
Memory – persistent‑memory enable flag, maximum stored trades, summary depth, self‑optimization window, and optional neural checkpoints.
Dashboard – theme, opacity, layout, and which panels to display (exposure panel, AI trace, etc.).
Tester Validation – static entry engine for backtests, options to disable AI and mesh in the tester, and signal thresholds tuned for simulation.

This configuration struct is created once at initialization time and passed into each subsystem. Individual modules do not read raw input values; they work against the contract of VanthConfig, which makes the system easier to reason about and less error‑prone.

Selected fields can be hot‑reloaded at runtime from a JSON control file (for example, adjusting risk per trade, minimum confidence, blackout windows, or maximum spread multiplier) under tight bounds checks to prevent accidental or malicious over‑risking. This gives the operator a safe way to dial the agent up or down without redeploying the EA.

The agentic AI layer: from model routing to trading‑aware reasoningIn most “AI‑powered” EAs, the model is treated as a black box that receives a partial snapshot of the market and responds with a prediction or classification. VANTH takes the opposite approach: the AI engine is treated as a trading‑aware component, and the system invests heavily in the structure of information that is passed into and out of it.

Multi‑provider, multi‑model routingVANTH can route requests to multiple providers (OpenAI, Anthropic, Google Gemini, xAI, DeepSeek, OpenRouter) and various model families (GPT‑style, Claude, Gemini, Grok, DeepSeek Reasoner, Llama, Nemotron).

The configuration allows a primary and secondary model to be defined, with optional per‑slot and per‑provider overrides and an optional consensus mode where the secondary model confirms borderline calls from the primary.

For each provider, the AI engine computes an effective model ID based on override precedence and ensures that any reasoning‑related features are only used on models that actually support them. For example, extended reasoning is enabled only for specific Anthropic, Gemini or Grok variants where a dedicated reasoning or thinking budget is documented, and the engine guards against sending unsupported fields to simpler models.

Reasoning depth and token managementBecause the EA relies on the AI to reason about structure, regime, and risk, prompt design and token budgeting are critical. To avoid truncated responses and partial JSON, VANTH:
increases the overall completion‑token ceiling above typical chat defaults;
allocates a dedicated reasoning budget for models that support chain‑of‑thought or “thinking” sections;
parses the trailing JSON object from the response, ignoring any earlier prose reasoning, so that longer reasoning chains do not break parsing.

The net effect is that the model is free to spend tokens on reasoning internally, but the EA only consumes and validates the final structured decision payload.

Market‑aware prompting: the “market photograph”Rather than feeding the AI a flat set of technical indicators, VANTH constructs a market photograph that describes the environment in trading‑native terms. This photograph includes, among others:
current bid/ask, mid price, spread in pips, and a rolling EMA of typical spread;
ATR and its relationship to its recent average (expanding versus contracting volatility);
Bollinger‑band levels, width, and a qualitative interpretation of whether bands are being stretched or compressed;
current timeframe trend structure (fast versus slow‑moving averages, slope in pips, RSI);
higher‑timeframe (H1/H4) trend and RSI for top‑down bias;
major swing highs and lows that define structural invalidation, separate from minor noise;
Fibonacci‑based “Sacred Phi” levels, explicitly marked as secondary structure for entries and targets, not primary invalidation;
a “market map” of key reference levels: previous day/week highs and lows, day open, Asian session range, nearby round numbers, and liquidity pools where stop clusters are likely;
net displacement and velocity in ATR units, and a trend‑efficiency metric that distinguishes clean trends from weak drifts and chop;
a noise gauge derived from the maximum of spread and a fraction of ATR, used to decide whether a level is decisively broken or just touched inside noise.

On top of price action, the AI also sees account‑level information: balance, equity, current PnL, leverage, free margin, used margin, margin level; risk state: node/portfolio/mesh states, open‑risk percentage, currency concentration, prop‑firm compliance flags; and portfolio context: a compact summary of net per‑currency exposure and cross‑lane capacity. It also receives memory context: summaries of recent performance, block reasons, and trade patterns, so it can adjust its aggressiveness or priorities in line with what has actually been happening.

The prompts instruct the AI to think like a professional discretionary trader: establish higher‑timeframe bias, classify the market as trending, ranging, volatile or thin, identify meaningful structure for invalidation, and only then select an appropriate playbook (trend continuation, structured breakout, liquidity‑sweep reversal, genuine range mean‑reversion, or wait).

Strictly structured outputsThe AI is asked to respond exclusively with a single JSON object for each decision type.

For entries: action (BUY/SELL/WAIT); entry type (market/pending); entry price; stop loss and take profit as absolute prices; optional lot multiplier; confidence; reason tags; a one‑sentence narrative; engine preference (which entry engine is most appropriate); and optional memory update.

For position reviews: position action (HOLD, CLOSE FULL, CLOSE PARTIAL, MOVE SL, MOVE TP, ARM BREAK EVEN); new SL/TP; partial‑close percentage; reason tags; narrative; and optional memory update.

All values are then checked against broker constraints (minimum stop distance, volume steps, margin requirements) and risk constraints before any order is placed or modified. The result is an EA where AI is not a black box but a constrained, well‑informed decision module living inside a robust risk and execution framework.

Risk governance: preserving capital as a first‑class objectiveVANTH’s risk manager is deliberately designed as a three‑layer system, aligned with the agentic‑AI philosophy: stateful, context‑aware, and independent from any single trade’s signal quality.

Node‑level risk stateAt the node (account) level, the manager tracks:
the starting balance of the current day and week;
the current equity high watermark;
the number of trades taken today.

From this, it computes daily and weekly loss in percentage and current drawdown from the high watermark, then maps these to discrete states such as NORMAL, CAUTION, REDUCED, BLOCKED, or EMERGENCY, based on configured limits (daily loss, weekly loss, max drawdown). These states influence whether new trades are allowed at all and whether the risk factor used to scale lot sizes is reduced. In more severe states, the EA can emit alerts and, if configured, stop trading completely for the remainder of the period.

Portfolio‑level risk: open risk and concentrationAt the portfolio level, the manager computes both open risk and currency concentration in monetary terms:

open risk is calculated by summing, across all positions, the risk amount implied by their stop‑loss distance and pip value, and dividing it by account balance;
currency concentration aggregates that risk per currency (base and quote for each pair), returning the maximum share of account risk carried by any single currency.

These metrics allow the EA to cap risk for the overall portfolio (through parameters such as maximum currency and correlation exposure) and to block new trades even when a single signal looks attractive, if adding it would create an unacceptable concentration on a particular currency.

Mesh‑level risk and prop‑firm constraintsThe mesh layer allows multiple nodes to coordinate and share risk information. Conceptually, a mesh aggregate state can feed back into the node‑level decision about whether a trade is acceptable, especially in multi‑account or multi‑server deployments.

In prop‑firm mode, additional constraints are applied, such as daily and total loss limits that mimic evaluation rules. If those are breached or approached, the risk manager can block trades irrespective of what the AI or entry engines propose.

A full entry gate around every signalEvery proposed entry—whether generated by deterministic engines or by the AI—is passed through the risk gate. The gate checks:

node, portfolio, and mesh states;
daily trade count against the configured maximum;
spread regime (current spread versus typical spread times a tolerance);
open risk and currency concentration;
broker volume limits and per‑symbol cumulative exposure;
margin requirements and projected margin level if the order were to be filled.

Only if all checks pass does the gate approve the trade and provide an approved lot size, scaled by the current risk factor. Otherwise, it returns a block reason that is logged, stored in memory, and visible on the dashboard, so that the operator and the AI can understand why a valid setup was vetoed.

This makes risk governance the core of the agent, not an afterthought.

Entry logic: blending deterministic engines and agentic AIVANTH’s entry engine layer is designed to support both classical systematic logic and full AI‑driven entries, with a hybrid mode that picks the best tool for current conditions.

The main engines can be summarized conceptually as:

Pending Momentum – identifies squeezes and places pending orders above or below recent structure, aligned with directional bias, to capture breakouts when volatility expands.
Mean Reversion – trades range extremes only when confirmed by volatility contraction, Bollinger‑band context, and RSI extremes, and avoids genuinely trending or highly volatile regimes.
Sacred Phi – trades structured retracements in clean trends when price revisits key Phi levels (0.382, 0.5, 0.618), with confirmation from RSI and trend alignment.
AI Dynamic – delegates full entry decisions to the AI, using the entire market photograph and account context, while relying on deterministic post‑filters for SL/TP validity and order execution.
Hybrid – classifies the regime and selects the most appropriate engine (for example, Sacred Phi or AI Dynamic in strong trends, Mean Reversion in genuine ranges, AI Dynamic in volatile or thin conditions).

In live trading, the default is typically an AI‑prevalent mode, while the tester mode can be configured to run a purely deterministic engine to ensure reproducible backtests without WebRequest calls. Regardless of the engine, all entries converge through the same risk gate and execution pipeline, ensuring unified control over lot sizes, stop distances, broker constraints, and risk state.

Position management: R‑centric, structure‑aware and AI‑assistedPosition management is where many EAs lose their edge. A strategy may have a good entry concept but manage trades in a naïve way: moving stops to break even too early, trailing too tightly inside noise, or failing to bank partial profits when structure calls for it. VANTH treats position management as a separate intelligence layer, combining deterministic safety logic with AI‑assisted decisions.

R‑based representation and intra‑trade memoryInstead of focusing only on raw pips or monetary profit, each position is tracked primarily in units of R: the distance between entry and initial structural stop. The system maintains, per position and at the account level:

current R;
maximum favorable excursion in pips and in R;
maximum adverse excursion in pips and in R;
remaining fraction of the original size still on.

This allows the AI and the deterministic logic to speak the same language: a trade that has delivered 2R and given back 0.5R is treated very differently from a trade that is still oscillating around +0.3R inside noise.

Partial closing and Sacred Phi exitsThe management layer supports partial closes based on both classical levels and AI decisions. For example, in Sacred Phi mode, the system can:

realize a fixed fraction of the position at the first structured target;
move the stop to break even after the first partial exit;
let the remainder run toward a higher structural target or liquidity pool.

This “scale‑out and trail” behavior is explicitly exposed to the AI, which can decide when a situation justifies a partial exit versus a full close or a simple hold.

AI‑aware safety mechanisms: “let it breathe” and ATR backstopsTwo safety concepts illustrate the interplay between AI and deterministic logic:

Let it breathe – the system enforces a rule that, below roughly 1R in profit, the structural stop defined at entry should normally not be tightened. This avoids the common retail pathology where a trade is scratched at break even on every minor fluctuation, preventing the strategy from capturing meaningful winners.

ATR‑based backstop – an optional AI‑SL backstop defines a one‑way disaster floor based on ATR multiples that can tighten the stop behind a profitable trade if, for any reason, the AI stops updating it. It only moves in the favorable direction and never chokes fresh trades, functioning as a safety net rather than a trailing rule.

The AI is free to suggest moves and partial closes, but its actions are filtered through these structural principles before being applied.

Persistent memory and online adaptationA central difference between VANTH and a typical EA is that VANTH never treats each tick or each session as a blank slate. Instead, it maintains a structured memory of trades, risk blocks, and lessons.

The memory subsystem:

stores trades with symbols, regime at entry, session, direction, R, maximum favorable and maximum adverse excursion, tags, and narrative;
records why trades were blocked (risk, spread, news, capacity, and similar factors), building a qualitative picture of the EA’s operating environment;
aggregates this information into summaries per symbol and per agent, which are fed back into the AI prompts;
optionally supports a form of self‑optimization where the AI is asked, on windows of N trades, to provide high‑level suggestions that the operator can review and selectively adopt.

By combining structured quantitative memory with qualitative AI‑generated lessons, the system can slowly adapt its behavior in response to the realities it encounters, while keeping all changes observable and reversible.

Multi‑symbol orchestration, news awareness and meshAt the orchestration level, VANTH is designed for multi‑symbol operation from a single chart. A lane registry tracks which symbols are traded, and each lane receives its own indicators, memory file, entry engine, and position manager.

The timer event drives a round‑robin evaluation of lanes, so that AI calls are serialized across symbols and cannot overload the network or the CPU. At each lane evaluation, the system:

refreshes indicator snapshots and risk state;
applies symbol‑specific news blackout based on currencies involved and configured blackout windows;
injects per‑lane context (open‑position summary, cross‑lane capacity, recent stop‑outs) into the AI request;
cleans up stale pending orders for that symbol, respecting broker limits and EA magic.

The mesh component can be used, when enabled, to propagate state across multiple nodes—sharing, for example, aggregated currency exposures or high‑level directives—so that the overall system behaves more like a distributed portfolio manager than a collection of isolated robots.

Dashboard and observability: making the agent legibleA critical requirement for any agentic EA that aspires to be used by serious traders is observability. The internal state and decisions of the agent must be legible.

VANTH’s dashboard is designed as a left‑side overlay that is both information‑dense and unobtrusive. It surfaces, per symbol lane:

identity and runtime mode (LIVE, DEMO, TESTER);
current spread versus typical spread, ATR, regime classification, and volatility status;
risk state at node, portfolio, and mesh levels, plus daily/weekly drawdown and open‑risk percentage;
whether the EA is currently under a news lockdown and why;
current positions and their aggregate R, direction, size, entry/SL/TP, and age;
AI status: primary and secondary models, consensus flag, cache state, last confidence, last action, last reason tags, and narrative;
memory status: number of trades recorded, best/worst sessions, current lesson summary, checkpoints;
mesh metrics: active and stale nodes, total mesh exposure, and any mesh‑level directives.

By rotating through lanes, the dashboard gives the operator a near real‑time view of how the agent perceives the world and why it is acting—or refusing to act—in a certain way. This makes it far easier to trust the system and to debug any unexpected behavior.

Implications for retail trading: from rules to infrastructureThe story of VANTH is not primarily “here is a profitable robot”, but “here is what a modern trading infrastructure can look like on MetaTrader 5”. The architecture illustrates several broader shifts:

From indicator formulas to execution infrastructure – the edge is less in “which indicator” and more in how signals are filtered, sized, sequenced, and managed under changing regimes.
From single‑strategy testing to portfolio and capacity management – by tracking open risk, currency concentration, lane capacity, and cross‑lane exposure, the system behaves more like a portfolio manager than a single strategy.
From backtest‑only validation to live, stateful learning – persistent memory, neural checkpoints, and self‑optimization windows allow the EA to adjust its behavior based on actual live results, not just static historical runs.
From opaque “AI magic” to constrained, audit‑ready decision‑making – the AI is not a mysterious oracle; it is given a precise, trading‑aware context, asked to emit structured decisions, and wrapped in strong risk and validation layers.

For the MQL5 community, architectures like VANTH suggest a path forward: EAs that behave more like institutional‑grade systems—risk‑aware, context‑sensitive, and memory‑driven—while still operating entirely within the standard MetaTrader runtime, respecting all platform constraints and editorial guidelines.