A multi-agent trading system is useful when different tasks require different data, time horizons, and acceptance criteria. It is not useful when several agents merely repeat the same opinion and vote. Real specialization creates separation of concerns: one component classifies market regime, another evaluates a setup, another calculates portfolio exposure, and another checks execution conditions.
The agents should not negotiate their way into a trade. Their constrained outputs should enter a deterministic policy engine that resolves conflicts, enforces risk limits, and either produces a bounded trade intent or returns no trade. MetaTrader 5 should execute only the policy engine’s validated command.
This article is an educational software-architecture guide for MQL5 developers and systematic traders. It is not financial or investment advice. Multi-agent systems add operational complexity, latency, and failure modes. Test every component and the full system in controlled environments before any live use.
The Core Architecture
A safe multi-agent pattern is:
REGIME AGENT + SETUP AGENT + PORTFOLIO AGENT + EXECUTION AGENT → POLICY ENGINE → MT5
Each agent receives a constrained input and emits a typed, versioned result. The policy engine has deterministic authority over conflict resolution, risk, sizing, and approval. The MT5 execution adapter has authority only to transmit an already authorized request and reconcile the broker response.
The central design rule is:
Agents interpret specialized evidence. A policy engine resolves conflicts. MT5 executes only the policy engine’s validated command.
Why Use Multiple Agents?
Different trading tasks need different evidence. Market regime classification may use completed price bars and volatility features. Setup quality may use price structure and strategy rules. Portfolio risk must use current account positions, pending orders, correlation maps, and daily drawdown. Execution conditions must use live spread, broker trade mode, stop levels, and filling rules.
Trying to make one model or one EA infer all of these responsibilities can create a fragile system. A specialist design can improve clarity when each component has a narrow role, testable contract, and measurable contribution.
| Specialized Task | Primary Evidence | Appropriate Output |
|---|---|---|
| Market regime | Completed bars, volatility, trend structure, range behavior, session data. | TREND, RANGE, HIGH_VOLATILITY, LOW_LIQUIDITY, or UNCLEAR. |
| Setup quality | Strategy-specific entry conditions, location, confirmation, risk-to-reward, and invalidation. | APPROVE_CANDIDATE, REJECT, or NO_SETUP with reason codes. |
| Portfolio exposure | Account equity, open positions, pending orders, total risk, correlation, daily drawdown. | EXPOSURE_OK, REDUCE_ALLOWED_RISK, or EXPOSURE_BLOCKED. |
| Execution conditions | Bid, ask, spread, trade mode, session, stops level, margin, and broker constraints. | EXECUTABLE, DELAY, or EXECUTION_BLOCKED. |
Multi-agent complexity is justified only if this specialization produces measurable improvement over a simpler baseline with the same risk budget and realistic costs.
When Multi-Agent Design Is Not Useful
Do not use multiple agents merely because the concept sounds advanced. Several agents that consume the same input, produce similar vague opinions, and vote on direction add complexity without creating independent evidence.
Multi-agent design is usually a poor fit when:
- One deterministic strategy already has clear entry, risk, and execution rules.
- The agents use the same features and simply restate the same signal.
- No agent has a defined authority boundary or measurable output quality.
- Latency requirements do not allow multiple decision stages.
- The system cannot log, reproduce, and test each agent result separately.
- The team cannot maintain versioning, monitoring, fallback policy, and operational controls.
- A single-model or single-rule baseline has not yet been established.
Start with the smallest architecture that can test the hypothesis. Add an agent only when it contributes a distinct input that improves a measured decision or reduces a measurable risk.
Specialization, Not Voting
Voting sounds intuitive: ask several agents whether to buy or sell, then trade when most agree. In live trading systems, this is often weak design. Agreement can be correlated, agents can share the same bad input, and a majority cannot override account facts such as excessive exposure or an invalid stop distance.
Use authority by domain instead:
- The regime agent is authoritative only for the configured regime label.
- The setup agent is authoritative only for whether the technical setup meets its defined rules.
- The portfolio agent is authoritative for current exposure and portfolio limits because it reads the account system.
- The execution agent is authoritative for current broker and market tradeability conditions.
- The policy engine is authoritative for combining valid results into an approve or deny decision.
A setup agent should never be allowed to overrule the portfolio agent. A regime agent should never be allowed to invent account equity. The policy engine should not rely on an agent’s memory for facts that can be read directly from MetaTrader 5.
Agent Contracts Must Be Typed
Every agent should receive a constrained input contract and emit a typed output contract. Free-form prose is unsuitable for the live path because it is ambiguous, difficult to validate, and hard to reproduce.
A typed contract should define:
- Schema name and schema version.
- Unique request ID and result ID.
- Input snapshot ID and timestamp.
- Agent ID and agent version.
- Permitted enum values.
- Required fields and optional fields.
- Freshness and expiry requirements.
- Evidence references or feature hashes.
- Confidence meaning, if confidence is included.
- Validation status and reason codes.
The policy engine should reject any agent result that fails schema validation, uses an unknown enum, refers to an expired snapshot, lacks required evidence, or comes from an incompatible version.
Market-State Snapshot First
All agents should work from a shared, timestamped market-state snapshot whenever possible. This reduces disagreement caused by each agent observing a different tick, spread, account state, or bar close.
A snapshot may contain:
- Snapshot ID and UTC timestamp.
- Symbol and broker-specific symbol name.
- Decision timeframe and relevant higher or lower timeframes.
- Bid, ask, spread, tick metadata, and current session state.
- Recent completed bars and validated features.
- Account balance, equity, margin, free margin, and margin level.
- Open positions, pending orders, daily profit and loss, and maximum permitted risk.
- Exposure aggregated by symbol, currency, direction, strategy, and correlation group.
- News or event state from a validated deterministic event service, if used.
- Configuration and version identifiers.
Critical values such as current exposure, margin, and live spread should come from the platform or portfolio system, not an agent’s memory or an old research record.
Agent 1: Regime Agent
The regime agent classifies the broad market environment. It should not choose final trade direction, calculate volume, or transmit orders.
A regime agent may use completed bars, volatility measures, trend structure, range width, session context, and other pre-approved features. Its role is to answer a narrow question: which strategy conditions are currently compatible with the observed environment?
Example Regime Output
{ "schema_version": "regime_result_v1", "result_id": "reg_2026-08-24_001", "snapshot_id": "snap_2026-08-24_EURUSD_M15_001", "agent_id": "regime_agent", "agent_version": "1.8.0", "regime": "TREND_UP", "allowed_setup_families": ["TREND_PULLBACK", "BREAKOUT_RETEST"], "blocked_setup_families": ["RANGE_REVERSAL"], "confidence": 0.71, "evidence_tags": ["higher_highs", "higher_lows", "volatility_normal"], "created_at_utc": "2026-08-24T23:45:02Z", "valid_until_utc": "2026-08-24T23:50:00Z" }
The result may permit a setup family or identify an unclear state. It should not say “buy now” unless a tightly bounded strategy design explicitly needs a candidate direction—and even then, it remains only a candidate.
Agent 2: Setup Agent
The setup agent evaluates whether a particular deterministic strategy setup is present. It should operate only within an approved strategy definition and should be aware of the regime label if regime is part of the setup contract.
For example, a trend-pullback setup agent might verify:
- The regime permits trend-pullback logic.
- Price has reached a predefined entry zone.
- A defined confirmation condition is present.
- The proposed invalidation level is structurally valid.
- The target policy leaves realistic reward after costs.
- The signal is not stale or already consumed.
Example Setup Output
{
"schema_version": "setup_result_v1",
"result_id": "setup_2026-08-24_001",
"snapshot_id": "snap_2026-08-24_EURUSD_M15_001",
"agent_id": "trend_pullback_setup_agent",
"agent_version": "2.1.0",
"setup_family": "TREND_PULLBACK",
"candidate_action": "BUY",
"status": "APPROVE_CANDIDATE",
"entry_zone": {"min": 1.08000, "max": 1.08018},
"invalidation_price": 1.07890,
"target_policy_id": "trend_pullback_exit_v2",
"expected_horizon": "2_to_12_bars",
"evidence_tags": ["pullback_at_support", "bullish_confirmation"],
"created_at_utc": "2026-08-24T23:45:03Z",
"valid_until_utc": "2026-08-24T23:50:00Z"
} The setup agent creates a candidate. It should not decide the final volume or bypass portfolio and execution filters.
Agent 3: Portfolio Agent
The portfolio agent is a risk and exposure specialist. It should obtain facts from the account system, not from a predictive model. This agent is often best implemented as deterministic code rather than an LLM or probabilistic model.
Its role is to evaluate the impact of a proposed trade on current exposure. It may calculate:
- Current total open risk.
- Risk already committed by pending orders.
- Exposure by symbol, base currency, quote currency, and direction.
- Correlation-group concentration.
- Strategy allocation consumption.
- Daily loss, drawdown, and consecutive-loss state.
- Remaining trade count and remaining daily risk budget.
- Margin buffer after the proposed trade.
Example Portfolio Output
{ "schema_version": "portfolio_result_v1", "result_id": "portfolio_2026-08-24_001", "snapshot_id": "snap_2026-08-24_EURUSD_M15_001", "agent_id": "portfolio_risk_service", "agent_version": "3.0.0", "status": "EXPOSURE_BLOCKED", "reason_code": "USD_CORRELATION_LIMIT", "current_total_open_risk_r": 1.25, "proposed_incremental_risk_r": 0.25, "currency_exposure": {"USD": "OVER_LIMIT"}, "remaining_risk_budget_r": 0.00, "created_at_utc": "2026-08-24T23:45:03Z" }
If the portfolio agent reports excessive correlated exposure, the proposed trade is rejected even if every other agent approves.
Agent 4: Execution Agent
The execution agent checks whether a proposed trade can be implemented safely under current live conditions. Like the portfolio agent, this is usually best implemented as deterministic code close to MT5.
It may validate:
- Terminal connection and trading permissions.
- Symbol trade mode and market session state.
- Current bid, ask, spread, and spread threshold.
- Broker stops level, freeze level, tick size, volume step, and filling mode.
- Price drift from the approved entry zone.
- Required margin and free-margin buffer.
- Signal freshness and maximum allowed latency.
- Scheduled event blackout or volatility restrictions.
- Duplicate order, duplicate signal, cooldown, and trade-count restrictions.
Example Execution Output
{
"schema_version": "execution_result_v1",
"result_id": "exec_check_2026-08-24_001",
"snapshot_id": "snap_2026-08-24_EURUSD_M15_001",
"agent_id": "execution_conditions_service",
"agent_version": "2.6.0",
"status": "EXECUTION_BLOCKED",
"reason_code": "SPREAD_TOO_WIDE",
"spread_points": 28,
"max_allowed_spread_points": 15,
"market_tradeable": true,
"signal_fresh": true,
"created_at_utc": "2026-08-24T23:45:04Z"
} A trade that cannot be executed under policy should be denied. The order policy must not silently change the stop, increase tolerance, or chase price to make the trade happen.
The Policy Engine Is the Decision Authority
The policy engine receives valid agent results, current snapshot data, and versioned configuration. It is the only component allowed to convert specialized results into an approved trade intent.
Its logic should be deterministic. Given the same snapshot, agent results, and policy version, it should return the same approval or denial.
Policy Engine Responsibilities
- Validate every agent result against its schema and freshness rules.
- Verify that all results refer to the same snapshot, symbol, timeframe, and strategy context.
- Know which agent is authoritative for each field.
- Resolve conflicts according to predefined precedence rules.
- Apply hard account, daily-loss, exposure, and execution limits.
- Calculate final position size from fixed account risk and actual stop distance.
- Build a bounded trade intent or return a no-trade decision with reason codes.
- Log every input, version, rule evaluation, approval, denial, and fallback decision.
The policy engine should not ask agents to debate until agreement appears. It should apply known rules to known outputs.
Conservative Conflict Resolution
Conflict resolution must be conservative. A valid candidate setup is necessary but not sufficient for a trade. Any authoritative safety block should deny the trade.
| Regime Agent | Setup Agent | Portfolio Agent | Execution Agent | Policy Decision |
|---|---|---|---|---|
| Permits trend setup | Approves candidate | Exposure OK | Executable | Eligible for final risk gate and possible approval. |
| Permits trend setup | Approves candidate | Exposure blocked | Executable | Reject: portfolio safety block overrides setup approval. |
| Unclear regime | Approves candidate | Exposure OK | Executable | Reject or documented fallback, depending on strategy policy. |
| Permits range setup | Trend setup candidate | Exposure OK | Executable | Reject: setup family does not fit current regime. |
| Permits trend setup | Approves candidate | Exposure OK | Spread too wide | Reject: execution block overrides candidate. |
| Agent unavailable | Approves candidate | Exposure OK | Executable | Use only an explicit documented fallback or halt new entries. |
“Continue anyway” should never be an accidental behavior. If an agent is unavailable, the policy must explicitly define whether the strategy uses a tested fallback, operates in reduced mode, or stops new entries.
Define Precedence Rules
Write precedence rules before deployment. A clear order of authority prevents hidden behavior during stressful or unexpected conditions.
One conservative precedence model is:
- Global kill switch and terminal permission checks.
- Account-level limits: daily loss, drawdown, maximum total risk, and margin buffer.
- Portfolio exposure and correlation limits.
- Execution conditions: session, spread, stops level, freshness, and broker constraints.
- Event or news restrictions.
- Regime compatibility.
- Setup validity.
- Final position sizing and order-policy construction.
This order reflects a safety principle: an attractive setup cannot override a hard account constraint.
Policy Engine Pseudocode
function EvaluateMultiAgentDecision(snapshot, regime, setup, portfolio, execution, config): if KillSwitchActive(config): return Deny("KILL_SWITCH_ACTIVE") if !AllResultsReferenceSameSnapshot(snapshot, regime, setup, portfolio, execution): return Deny("SNAPSHOT_MISMATCH") if !AllRequiredResultsAreValidAndFresh(regime, setup, portfolio, execution, config): return Deny("INVALID_OR_STALE_AGENT_RESULT") if !AccountLimitsAllowNewRisk(snapshot, config): return Deny("ACCOUNT_LIMIT") if portfolio.status != "EXPOSURE_OK": return Deny(portfolio.reason_code) if execution.status != "EXECUTABLE": return Deny(execution.reason_code) if !RegimeAllowsSetup(regime, setup.setup_family): return Deny("REGIME_SETUP_MISMATCH") if setup.status != "APPROVE_CANDIDATE": return Deny(setup.reason_code) volume = CalculateVolumeFromRisk(snapshot, setup.invalidation_price, config) if !VolumeAndMarginAreValid(snapshot, volume, config): return Deny("INVALID_VOLUME_OR_MARGIN") return Approve(BuildTradeIntent(snapshot, setup, volume, config))
The policy engine does not “average” agent opinions. It verifies constraints and authorizations in a fixed sequence.
Avoid Open-Ended Agent Conversations
Open-ended conversations between agents are poor design for the live trading path. They create variable latency, unpredictable token use, weak reproducibility, and unclear stopping conditions. An agent may keep requesting more information, reinterpret another agent’s output, or create a narrative that cannot be reduced to a deterministic rule.
Prefer a directed graph with a maximum number of steps:
SNAPSHOT → REGIME RESULT → SETUP RESULT → PORTFOLIO RESULT → EXECUTION RESULT → POLICY DECISION → MT5
Each node should have:
- A constrained input schema.
- A maximum execution time.
- A known output schema.
- A clear timeout or failure state.
- A deterministic next node.
- A logged version and correlation ID.
If an agent needs more information, that information should be a defined field in the snapshot or a defined service call—not an unbounded dialogue.
Use a Directed Acyclic Graph
A directed acyclic graph, or DAG, is useful because it defines which tasks can run in parallel and which must wait for earlier results. It also prevents circular reasoning such as an execution agent asking the setup agent to change the setup because current spread is too wide.
For example:
Market Snapshot
├── Regime Agent
├── Portfolio Risk Service
└── Execution Conditions Service
│
Regime Result + Snapshot
└── Setup Agent
│
All Typed Results
└── Deterministic Policy Engine
│
Approved Trade Intent
└── MT5 Execution Adapter The portfolio and execution services can often run in parallel with regime classification. The setup agent can run after the regime result is available if regime is a requirement. The policy engine waits for all required results or times out safely.
Freshness and Latency Across Agents
Multi-agent systems can become stale while waiting for results. A regime result calculated from one snapshot should not be combined with an execution result from a different market moment without explicit policy.
Use these controls:
- Attach every result to a shared snapshot ID.
- Include creation time and expiry time in every agent result.
- Set a maximum allowed age for the whole decision graph.
- Require current price to remain inside an approved entry zone at policy time.
- Reject results that arrive after their validity window.
- Measure latency for every node and the complete path.
- Use a maximum graph duration; no result means no trade.
- Rerun the graph from a fresh snapshot rather than combining old and new partial results.
Do not chase price because a multi-agent result arrived late. A late decision is a new decision problem and should be evaluated from a new snapshot.
Failure and Fallback Policy
Every agent can fail: an external inference service can time out, a feature calculation can become invalid, an account-state query can fail, or an agent can return malformed output. Decide in advance what happens.
Possible policies include:
| Failure Condition | Conservative Default | Possible Tested Fallback |
|---|---|---|
| Regime agent unavailable | Block new entries for strategies that require regime confirmation. | Use a deterministic regime classifier only if it is separately tested and explicitly configured. |
| Setup agent unavailable | No candidate trade; no entry. | None unless a distinct deterministic setup path is configured. |
| Portfolio agent unavailable | Block new entries because current exposure is unknown. | None for live use; account facts must be current. |
| Execution agent unavailable | Block new entries because live broker conditions are unknown. | None for live use; execution conditions must be current. |
| Malformed result or schema mismatch | Reject the result and log an explicit reason. | Use a compatible previous version only if version policy explicitly permits it. |
| Snapshot becomes stale | Discard all partial results and do not trade. | Start a new graph using a fresh snapshot. |
Fallback behavior must be deliberate, versioned, and tested. A silent fallback is simply an untracked strategy change.
Keep Account Facts Deterministic
Some information should never be inferred by an agent. Current equity, margin, open positions, pending orders, broker stop levels, symbol trade mode, and actual spread should come directly from MT5 or a trusted account service.
Use agents for interpretation where interpretation adds value. Use the platform for facts where the platform is authoritative.
Examples:
- An agent can classify whether current price structure resembles a range.
- MT5 must supply actual bid, ask, spread, and symbol properties.
- An agent can rank a candidate setup.
- Deterministic code must calculate final volume from stop distance and account risk.
- An agent can flag possible thematic correlation.
- A portfolio service must calculate actual combined exposure and enforce hard limits.
Multi-Agent System State
Maintain a durable record of every decision graph. This prevents restart problems and lets you explain why a trade was denied or executed.
Each graph should have:
- Decision graph ID.
- Market snapshot ID and timestamp.
- Symbol, timeframe, and strategy ID.
- Required agent list and received result IDs.
- Current state: CREATED, RUNNING, WAITING, APPROVED, DENIED, EXPIRED, FAILED, or EXECUTED.
- Agent versions, model versions, feature-schema versions, and policy version.
- All validation results and reason codes.
- Final trade intent, if approved.
- MT5 request and reconciliation result, if execution was attempted.
On restart, do not resume a partially completed graph blindly. Verify freshness, reconcile account state, and discard expired graph instances. If the state is uncertain, default to no new trade.
Use a Single Execution Authority
Even in a multi-agent system, there should be one execution authority. Do not allow each agent to call OrderSend() or submit independent broker requests.
A safe execution path is:
AGENT RESULTS → POLICY ENGINE → BOUNDED TRADE INTENT → SINGLE MT5 EXECUTION ADAPTER → BROKER RESPONSE RECONCILIATION
The execution adapter should receive only a validated trade intent containing approved symbol, direction, volume, price bounds, stop-loss, target policy, expiry, strategy identifier, and correlation ID. It should not reinterpret agent outputs or create a different trade.
Version Every Node and Policy
A multi-agent trade should be reproducible after the fact. Version every component that can influence the decision.
Version:
- Regime agent model, prompt, features, and thresholds.
- Setup agent logic, model, feature schema, and strategy definition.
- Portfolio-service risk configuration and correlation map.
- Execution-service rules, spread thresholds, filling modes, and broker mappings.
- Policy-engine precedence rules and conflict-resolution configuration.
- Position-sizing, daily-loss, total-open-risk, and drawdown policies.
- Event filters, session filters, and news policies.
- MT5 EA build, source-control commit, and deployment environment.
Changing a prompt, a feature list, a correlation mapping, or a precedence rule can change live behavior. Treat each change as a controlled release, not a minor edit.
Audit Logging Requirements
Logging is essential because multi-agent systems can fail in ways that are difficult to reconstruct from account history alone. A single order may depend on several different results and policies.
Log:
- Shared market snapshot and data-quality status.
- Every agent input reference, output, validation result, and latency.
- Evidence tags, model confidence, and feature hashes where applicable.
- Portfolio calculations, open risk, correlation group, and remaining risk budget.
- Execution checks including spread, margin, stops level, and tradeability.
- Policy-engine precedence path and final reason code.
- Final trade intent, request, MT5 response, retcode, tickets, and fill details.
- Subsequent position lifecycle, stop changes, partial exits, and final result.
- No-trade and failure outcomes, not only executed orders.
Audit logs should use consistent timestamps, ideally UTC, and correlation IDs that link all outputs to one decision graph.
Testing Multi-Agent Systems
Test every layer independently and then test the graph as a whole. A model can appear accurate in isolation while the combined system creates poor decisions because of latency, mismatched snapshots, exposure logic, or failure handling.
| Test Area | What to Test |
|---|---|
| Agent contracts | Schema validation, missing fields, unknown enums, invalid timestamps, incompatible versions, and stale results. |
| Regime agent | Classification accuracy by market condition, no-trade behavior, and stability across intended instruments and sessions. |
| Setup agent | Rule consistency, candidate validity, stop and target proposal logic, and duplicate prevention. |
| Portfolio service | Total risk, correlation aggregation, pending-order handling, drawdown limits, and restart reconciliation. |
| Execution service | Spread checks, broker stop rules, trade mode, volume rounding, margin buffers, and order compatibility. |
| Policy engine | Conflict precedence, fallback policy, hard-limit override behavior, and deterministic repeatability. |
| End-to-end graph | Timeouts, late arrivals, stale snapshots, agent failures, duplicate signals, kill switches, and broker response reconciliation. |
Build fixed “golden cases” with recorded snapshots and expected agent outputs. Run them whenever code, prompts, models, features, configuration, or broker mappings change.
Compare Against a Single-Agent Baseline
Multi-agent complexity should be earned through measurable improvement. Before accepting the operational burden, compare the system against a simpler baseline with the same instruments, same costs, same risk budget, same execution assumptions, and the same out-of-sample period.
Compare:
- Net performance after spread, commission, slippage, and financing.
- Maximum drawdown and downside behavior.
- Exposure concentration and correlation-adjusted risk.
- Rule-compliance and number of denied unsafe trades.
- Latency and stale-signal rate.
- Operational failures, restart recovery, and error rate.
- Maintenance cost, monitoring burden, and version-management complexity.
- Out-of-sample robustness across market regimes.
If a simpler system produces similar or better results with lower operational risk, keep the simpler system. Complexity is not evidence of sophistication.
Start With a Minimal Multi-Agent System
A practical first design may use only two specialized services plus a deterministic policy engine:
- A regime classifier that permits or blocks a setup family.
- A deterministic portfolio and execution service that enforces account facts and broker conditions.
- A deterministic setup module within the EA.
- A single policy engine and execution adapter.
This is often enough to test whether regime awareness adds value without adding open-ended orchestration, external chat, or several overlapping models.
Example Minimal Graph
Market Snapshot ├── Regime Classifier ├── Portfolio and Exposure Service └── Execution Conditions Service │ Deterministic Setup Module │ Policy Engine │ MT5 Execution Adapter
Only add a separate setup agent, event agent, or external research agent when it has a clear contract and a measured purpose.
MQL5 Component Layout
Use a modular project structure so agents, policies, and execution can be tested and changed independently.
/MultiAgentMT5
/Core
MarketSnapshot.mqh
AgentContracts.mqh
AgentResultValidator.mqh
DecisionGraph.mqh
PolicyEngine.mqh
RiskGate.mqh
OrderPolicy.mqh
ExecutionAdapter.mqh
AuditLogger.mqh
KillSwitch.mqh
/Agents
RegimeAgentAdapter.mqh
SetupAgent.mqh
PortfolioRiskService.mqh
ExecutionConditionsService.mqh
/Infrastructure
Serialization.mqh
TimeUtils.mqh
SymbolUtils.mqh
ExposureAggregator.mqh
/Config
AgentRegistry.mqh
PolicyConfig.mqh
MultiAgentMT5.mq5 The main EA should coordinate a bounded graph. It should not contain unstructured conversations, duplicated risk logic, or independent order paths.
Conceptual MQL5 Orchestration Loop
OnTimer(): if KillSwitch.IsActive(): Audit.LogSystemState("NEW_ENTRIES_DISABLED") return snapshot = MarketSnapshotBuilder.Create() if !snapshot.IsReliable(): Audit.LogNoTrade("UNRELIABLE_SNAPSHOT") return regime = RegimeAgent.Evaluate(snapshot) portfolio = PortfolioRiskService.Evaluate(snapshot) execution = ExecutionConditionsService.Evaluate(snapshot) if !AgentResultsAreValid(regime, portfolio, execution): Audit.LogNoTrade("INVALID_AGENT_RESULT") return setup = SetupAgent.Evaluate(snapshot, regime) if !AgentResultIsValid(setup): Audit.LogNoTrade("INVALID_SETUP_RESULT") return decision = PolicyEngine.Evaluate(snapshot, regime, setup, portfolio, execution) Audit.LogDecisionGraph(snapshot, regime, setup, portfolio, execution, decision) if !decision.approved: return request = OrderPolicy.BuildRequest(decision.trade_intent) result = ExecutionAdapter.SendAndReconcile(request) Audit.LogExecution(decision.trade_intent, request, result)
Every branch fails safely. If a required result is invalid, stale, or unavailable, the system returns no trade rather than attempting to improvise.
Operational Controls
Multi-agent systems need controls independent of every individual agent. A global control layer should be able to stop new entries even if one or more agents continue producing results.
Useful controls include:
- Global kill switch for new orders.
- Per-agent enable or disable state.
- Per-symbol and per-strategy enable or disable state.
- Maximum graph duration and agent timeout.
- Maximum daily loss, drawdown, and consecutive-loss limits.
- Maximum total open risk and maximum correlated exposure.
- Maximum number of positions and pending orders.
- Maximum spread, volatility, and event-risk thresholds.
- Automatic pause after repeated schema failures, timeouts, or order rejections.
- Manual approval mode during early forward testing.
Define how controls interact with existing positions. A kill switch may block new entries while allowing deterministic stop-loss and take-profit management to continue. Make this behavior explicit before deployment.
Common Design Mistakes
Using Agents as a Voting Panel
Several correlated opinions do not create independent evidence. Assign domain authority and use deterministic conflict resolution instead.
Allowing Any Agent to Send Orders
Order execution must have one authority. Agents should return typed results; the policy engine approves; the execution adapter sends and reconciles.
Letting Agents Infer Account Facts
Current exposure, equity, margin, spread, and broker constraints must come from the platform or trusted account service, not agent memory.
Using Open-Ended Conversations in the Live Path
Unbounded agent dialogue creates unpredictable latency, cost, and reproducibility. Use a directed graph with maximum steps and fixed contracts.
Combining Results From Different Snapshots
A regime result from one market moment and an execution result from another can create invalid decisions. Use shared snapshot IDs, freshness limits, and graph expiry.
Making Fallback Behavior Implicit
If an agent fails, “continue anyway” should never occur by accident. Define and test no-trade, documented fallback, or manual-review behavior.
Not Comparing Against a Simpler Baseline
More components can create more failure modes. Measure whether specialization improves outcomes after costs and risk before retaining the complexity.
Ignoring Auditability
If you cannot reconstruct why agents disagreed and why a policy approved an order, the system is too opaque for reliable operation.
Implementation Checklist
Use this checklist when designing a multi-agent MT5 system:
- Use agents only when each one has a distinct task, data source, time horizon, and acceptance criterion.
- Assign domain authority rather than using open-ended voting.
- Use shared, timestamped market-state snapshots and require every result to reference the snapshot ID.
- Define strict typed contracts with versions, enums, expiry, evidence references, and reason codes.
- Keep account facts, margin, spread, positions, and broker rules deterministic and platform-sourced.
- Make portfolio and execution safety blocks authoritative over setup approvals.
- Use a deterministic policy engine to resolve conflicts and construct bounded trade intents.
- Use one MT5 execution authority and reconcile every broker result.
- Avoid open-ended agent conversations in the live decision path.
- Use a directed graph with maximum steps, timeouts, and explicit failure states.
- Define conservative fallback behavior before deployment; uncertainty should default to no trade.
- Version every agent, feature schema, prompt, policy, configuration, and EA build.
- Log all snapshot data, agent results, validation outcomes, conflict rules, decisions, requests, and fills.
- Test each agent independently and test full graph failures, stale data, restarts, and duplicate decisions.
- Compare performance and operational burden against a single-model or single-rule baseline before keeping added complexity.
Final Thoughts
A multi-agent trading system can improve an MT5 workflow when it creates real specialization: one component interprets regime, another evaluates a setup, another protects portfolio exposure, and another verifies execution conditions. It becomes unsafe when agents are allowed to negotiate vague opinions into an order.
Use constrained inputs, typed outputs, a bounded directed graph, conservative conflict resolution, and one deterministic policy engine. Let MT5 execute only a validated command from that engine. If a required agent is unavailable, stale, or invalid, the default should be no trade unless a separate fallback has been explicitly tested. Complexity must earn its place through measurable improvement, not novelty.
Risk disclaimer: Automated trading, artificial intelligence, multi-agent systems, Expert Advisors, foreign exchange, CFDs, commodities, indices, stocks, cryptocurrencies, and other leveraged products involve substantial risk and may not be suitable for all investors. This article is for educational and software-architecture purposes only and does not constitute financial, investment, legal, tax, cybersecurity, or regulatory advice. Agent outputs can be incorrect, delayed, incomplete, inconsistent, or unavailable. Past performance, backtests, forward tests, and demo results do not guarantee future results. Test all systems carefully, verify broker-specific behavior, and use robust independent risk controls before considering live deployment.


