Published in Architecture · 7 min read

MetaTrader 5 Portfolio Framework: Multi-Asset Guide

metatrader-5 portfolio-framework multi-asset-trading mql5 algorithmic-trading order-management trading-infrastructure
MetaTrader 5 Portfolio Framework: Multi-Asset Guide

Can you really manage multiple symbols on MetaTrader 5 with one Expert Advisor? How do you handle capital normalization when gold moves $80 per point and EUR/USD only $10? What happens to your open positions when MT5 crashes at 3 AM?

If you've tried building multi-asset portfolios on MetaTrader 5, you know these aren't theoretical questions. They're the problems that force you back to running separate EAs for each symbol, manually tracking everything in spreadsheets, and hoping nothing breaks during the night.

MetaTrader 5 is not natively designed for portfolio management. There's little quality documentation on how to solve this. So I built the Horizon Portfolio Framework to handle multi-asset, multi-strategy execution with proper capital allocation, position persistence, and real-time metrics.

Table of Contents:

Why MetaTrader 5 Struggles with Portfolios

MetaTrader 5 was designed for one Expert Advisor to trade one symbol. That's the default mental model. When you want to run multiple strategies across multiple assets, you hit walls immediately.

You can run multiple EAs, but then you face these issues:

  • No centralized capital allocation across strategies
  • Each EA calculates lot sizes independently without knowing about others
  • Risk management happens per-EA, not at portfolio level
  • No unified metrics or reporting
  • Position tracking is scattered across multiple EAs

The alternative is building a custom framework that handles portfolio orchestration from the ground up. That's what Horizon does.

The MetaTrader 5 Portfolio Framework Architecture

Horizon uses a hierarchical architecture with three core concepts: Assets, Strategies, and Services. This MQL5 framework provides the algorithmic trading infrastructure needed for portfolio management.

Asset-Strategy Hierarchy

An Asset represents a tradable symbol along with the strategies that operate on it. A Strategy contains the trading logic for one specific approach.

Here's how you define an asset:

Each asset can have multiple strategies. The framework extracts all strategies from all assets and manages capital allocation automatically.

At initialization, the framework distributes capital equally across all strategies:

This approach scales naturally. If you have 2 symbols with 2 strategies each, that's 4 total strategies with 25% capital allocated to each.

Event Propagation System

The framework propagates time-based events to all assets and strategies in cascade:

Events available:

  • onTick() - Every price update
  • onStartMinute() - New minute
  • onStartHour() - New hour
  • onStartDay() - New day
  • onStartWeek() - Monday
  • onEndWeek() - Friday 23:00
  • onStartMonth() - First day of month

Each strategy receives these events and decides when to act. This decouples timing logic from trading logic.

Service Layer

The framework provides reusable services that all strategies can use:

  • Order - Order lifecycle management with status tracking
  • Statistics - Real-time metrics calculation
  • SymbolCost - Capital normalization between symbols
  • Logger - Structured logging system
  • OrderPersistence - Position serialization to JSON
  • ReportOfOrderHistory - Complete order export for analysis

Strategies don't implement these from scratch. They use the services.

Problems This Portfolio Framework Solves

Problem 1: Multiple Symbols, Single Connection

MetaTrader 5 typically runs one EA per symbol. Horizon allows you to manage multiple symbols with one EA through the Asset-Strategy architecture.

When you add a new symbol, you create one file and register it:

The framework handles propagation, capital allocation, and reporting for all symbols automatically.

Problem 2: Capital Normalization Across Symbols

Different symbols have different point values. Gold moves $80 per point. EUR/USD moves $10 per point. If you use the same lot size for both, you're taking 8x more risk on gold.

The SymbolCost service normalizes this:

When calculating lot size, the strategy applies this multiplier:

This ensures equal dollar risk across symbols regardless of their point value.

Problem 3: Position Loss on Restart

If MetaTrader crashes or your VPS reboots, your EA loses track of open positions. They're still in the market, but your code doesn't know about them.

OrderPersistence serializes each order to JSON immediately when it opens:

On initialization, the framework automatically loads positions:

The EA resumes tracking immediately without manual intervention.

Problem 4: Quantitative Strategy Evaluation

During backtesting, you need to evaluate strategy quality beyond just profit. The Statistics service calculates metrics in real-time:

  • Sharpe Ratio
  • Maximum Drawdown (dollars and percentage)
  • R-Squared (equity curve linearity)
  • Risk/Reward Ratio
  • Win Rate
  • Recovery Factor
  • Layer Distribution (for recovery strategies)

The framework supports 8 optimization formulas you can select during backtesting:

  • Performance
  • Drawdown
  • Risk/Reward
  • Sharpe Ratio
  • Win Rate
  • R-Squared
  • Trade Count
  • Layer Distribution

You configure thresholds, and the framework scores each backtest run:

The OnTester() function returns the quality score for optimization:

This allows proper multi-objective optimization in the MetaTrader Strategy Tester.

How to Add New Assets

Adding a new asset requires three steps:

  1. Create the asset file in assets/:

  2. Include it in Horizon.mq5:

  3. Add to the assets array:

The framework handles the rest. Capital allocation updates automatically. Event propagation works. Statistics track per-strategy.

Technical Implementation Details

Order Lifecycle Management

Orders progress through a state machine:

The Order class extends the Trade service and manages lifecycle:

  • PENDING - Limit order placed but not filled
  • OPEN - Position active in market
  • CLOSING - Close request sent, waiting for confirmation
  • CLOSED - Position closed with profit/loss recorded

The OnTradeTransaction event updates order status based on broker confirmations:

This ensures the framework stays synchronized with MetaTrader's execution state.

Statistics Calculation

The Statistics service maintains NAV (Net Asset Value) and performance arrays updated hourly:

When orders close, profits update the NAV:

Sharpe Ratio calculation uses returns between performance snapshots:

R-Squared measures equity curve linearity by calculating correlation between time and NAV:

These metrics update automatically. Strategies don't implement statistical calculations.

Backtesting Integration

The framework integrates with MetaTrader's Strategy Tester through standard callbacks:

Each backtest run exports a JSON report with complete order history:

You can analyze these reports externally with Python or Excel.

Repository and Getting Started

The Horizon Portfolio Framework is open source and available on GitHub: https://github.com/pedrocarvajal/horizon-portfolio-framework

The repository contains:

  • Complete MQL5 source code
  • Interface definitions for Asset and Strategy
  • Reusable services (Order, Statistics, Logger, etc.)
  • Example implementations

To get started:

  1. Clone the repository into your MetaTrader 5 MQL5/Experts/ directory
  2. Create your strategy by extending IStrategy
  3. Create an asset by extending IAsset and adding your strategies
  4. Register the asset in Horizon.mq5
  5. Compile and run in Strategy Tester or live

The framework handles multi-asset orchestration, capital allocation, position persistence, and metrics automatically. You focus on trading logic.

If you're building portfolio-based systems on MetaTrader 5, this solves the infrastructure problems so you can focus on strategy development rather than framework engineering.