BACKTESTMARKET
MQL5 Portfolio Optimization: A Practical Workflow
backtesting·

MQL5 Portfolio Optimization: A Practical Workflow

How to optimize a multi-symbol portfolio in MQL5 and MetaTrader 5: objectives, constraints, tester setup, overfitting checks and the clean data it all depends on.

By BacktestMarket Team
mql5 portfolio optimization

Trader configuring an MQL5 portfolio optimization

Portfolio optimization in MQL5 means choosing how much capital, risk or lot size each strategy or symbol gets, then testing that choice in the MetaTrader 5 Strategy Tester. The optimizer only finds what your data allows. If the minute bars behind a multi-symbol test have gaps, shifted timestamps or mismatched sessions, the weights you select will fit the errors rather than the market. That is why we start with the workflow and treat the data as the first step, not an afterthought. Our historical data sets are built as complete, clean minute-bar downloads since 2014, ready to import into MT4 and MT5, so every symbol in your portfolio test comes from one consistent source.

TL;DR

  • Portfolio optimization differs from single-strategy optimization: you tune weights, risk budgets and constraints across several symbols or EAs, not one set of inputs.
  • MetaTrader 5's Strategy Tester handles multi-symbol Expert Advisors natively, but each symbol must be enabled in Market Watch and its history must be complete.
  • Use the tester's forward period and compare the best optimization runs against forward results to catch overfitting.
  • Gaps and timestamp errors in any one symbol distort correlations and drawdowns for the whole portfolio, so audit the data before you optimize.
  • Keep the objective simple, keep constraints explicit, and rerun the whole test when you change the data.

Table of Contents

What portfolio optimization means in MQL5

MetaTrader 5 describes strategy optimization as running an Expert Advisor (EA, an automated trading program) repeatedly over historical data with different input-parameter sets, to select the most suitable combination. That is the single-strategy case: one EA, a handful of inputs such as period lengths, stop distances and thresholds.

Portfolio optimization asks a different question. You already have strategies, or a list of symbols, and you want to decide how they share risk. The inputs you tune are allocation inputs: the lot multiplier for each symbol, the risk percentage per strategy, the maximum number of simultaneous positions, a cap on total exposure. The result you care about is not the best equity curve of any one component but the shape of the combined curve: smoother, with shallower drawdowns, with less dependence on one market.

In practice MQL5 portfolio work comes in three forms:

  1. A multi-symbol EA. One program trades several symbols and applies its own allocation logic. The tester runs it as a whole.
  2. Several EAs on one account. Each has its own magic number (the ID an EA stamps on its orders), and you analyze the combined history.
  3. An allocation layer. A script or EA computes weights from historical returns and feeds them to the trading logic.

The first form is the easiest to optimize inside MetaTrader 5, because the tester treats the portfolio as one test. For the other two, our walkthrough of three ways to run an MT5 portfolio backtest with clean minute bars lays out the options.

Choose the objective before the parameters

An optimizer will maximize whatever you hand it. If you pick net profit, it will happily pile risk into the most volatile symbol. Decide what a good portfolio looks like first.

Classical portfolio theory gives a vocabulary. MSCI's portfolio-construction paper describes mean-variance optimization as rewarding expected return and penalizing variance, with risk-aversion parameters controlling the trade-off between the two. You do not need to implement a full covariance optimizer to use the idea. In a trading context it translates into objectives like these:

ObjectiveWhat it rewardsWhere it goes wrong
Net profitTotal gainConcentrates risk in the loudest symbol
Profit divided by maximum drawdownReturn per unit of painSensitive to one bad stretch in the sample
Sharpe-style ratio of returnsReturn per unit of variabilityHides rare large losses
Custom criterionWhatever you codeEasy to build in an accidental bias

MetaTrader 5 lets you compute a custom optimization criterion, and its MQL5 documentation lists functions for working with optimization results so you can process them in your own code. A balanced custom score, such as return over drawdown with a penalty for too few trades, usually serves portfolios better than raw profit.

Add constraints that match how you trade

Optimization without constraints produces extreme answers: everything in one symbol, or leverage you would never run. The same MSCI paper lists the kinds of constraints portfolio builders apply: limits on total or active risk, factor or idiosyncratic risk, asset and group exposures, turnover, transaction costs, liquidity, exclusions and concentration.

For an MT5 trader, those become practical rules you can code or set as inputs:

  • Maximum risk per symbol, for example a fixed percentage of equity per trade.
  • Group caps, so that EUR pairs together cannot exceed a set exposure.
  • Total open risk, a ceiling across all positions at once.
  • Turnover and cost limits, meaning a minimum time between trades and realistic spread and commission settings.
  • Exclusions, such as skipping symbols around known low-liquidity windows.

Write these down before you run anything. Changing constraints after you have seen the results is the quietest form of overfitting.

Implementing allocation and risk calculations in MQL5

The MQL5 side is less exotic than it sounds. Three building blocks cover most portfolio EAs.

Three MQL5 portfolio risk calculation components

Position sizing from risk. Lot size comes from the equity you are willing to risk, the stop distance in price terms, and the tick value and tick size of the symbol. Use SymbolInfoDouble for tick value and tick size, SYMBOL_VOLUME_STEP to round to a legal volume, and the account's equity from AccountInfoDouble. Each symbol has different contract specifications, so compute per symbol rather than reusing one formula output.

Volatility-based weights. A simple, robust allocation is inverse volatility: measure each symbol's recent average true range (ATR, the average size of recent price swings) with iATR, and size positions so that each contributes similar risk. Our Average Range indicator is one way to see that range on a chart.

Correlation-aware limits. Copy returns for each symbol with CopyClose, convert them to percentage changes, and compute pairwise correlations over a rolling window. If two positions are strongly correlated, treat them as one risk and cap them together. Correlations computed on bars with gaps or misaligned timestamps are unreliable, because a missing bar in one symbol shifts every return after it relative to the other symbols.

Keep these calculations in a separate include file so the optimizer varies only the inputs, not the code paths.

Set up the Strategy Tester for a portfolio

The tester is built for this. MetaTrader 5 Help describes it as a multi-currency tool that automatically processes all symbols used by an EA, so you do not enter a separate symbol list in the tester settings. The MQL5 documentation adds that the tester loads the history of the used symbols from the client terminal the first time the EA asks for them.

The setup steps:

  1. Enable every symbol in Market Watch. MetaTrader 5 Help recommends enabling the instruments a multi-currency EA needs before optimization. The tester downloads their histories when accessed and requests only the missing price history from the trade server.
  2. Check the history you actually have. What the tester finds in the terminal is what it uses. If your broker's server supplies short or patchy history for some symbol, the tester will run on it without complaint.
  3. Choose the period and mode. Use a long window covering different market regimes: trends, ranges, high-volatility months. Pick a modeling mode that matches your strategy's timeframe. Strategies that depend on minute-level entries need minute-bar quality.
  4. Split the period. Set a forward period (more on that below).
  5. Run an optimization. Start with a coarse grid on the few inputs that matter, such as risk per symbol and the group cap, then refine.

The tester may also download pre-start history so that at least 100 bars are available when the test begins. For indicators with long lookbacks, begin the test later than your first data point so the warm-up is real data.

Why the data decides the result

Single-strategy tests forgive some data flaws. Portfolio tests do not, for three reasons.

Alignment. A portfolio result depends on what each symbol did at the same moment. If one symbol's timestamps are shifted by a time-zone or daylight-saving error, the tester sees diversification that never existed, or misses a correlation spike that did.

Gaps. A missing hour in one instrument means the EA either skips trades or trades on stale prices while the others keep moving. The drawdown you read from the report is then wrong in a direction you cannot predict.

Mixed sources. When each symbol comes from a different feed, the differences in spread handling, session boundaries and rollover treatment enter the portfolio as noise. Optimization will try to exploit that noise.

An audit before optimization is cheap compared with weeks of tuning on bad bars. Our five-step audit for handling missing bars and the guide to auditing MT5 backtesting data for gaps and timestamps walk through the checks: bar counts per session, timestamp continuity, duplicate bars, and outlier ranges.

Loading your own data into MT5

Once the data passes, you need it in the terminal. The usual route is a custom symbol: a symbol you create locally and fill with imported bars, so the tester runs on exactly the data you audited. Our guides cover how to load data in MT5 in four steps and how to create, import and test custom symbols. Build all the portfolio's symbols the same way so they share one convention for time and sessions.

Read the results without fooling yourself

An optimization produces thousands of passes. The top row of the table is the most flattering one, not the most likely one.

MetaTrader 5 gives you a built-in check: the forward period. Use it to verify optimization results and compare the best runs on the optimization and forward periods to assess possible overfitting, meaning a fit to past noise rather than a repeatable edge. The tester can report optimization and forward results separately, so you can see both side by side.

A workable routine:

  1. Optimize on the first part of your history and leave the last part as forward.
  2. Sort passes by your chosen objective, then look at the top cluster, not the top row.
  3. Check that neighboring parameter values give similar results. A sharp spike surrounded by poor results is a warning.
  4. Compare each candidate's forward result with its optimization result. A large drop means the weights were fitted to the sample.
  5. Inspect the combined drawdown, the longest losing stretch and the share of profit contributed by each symbol. If one symbol supplies nearly all the profit, you have a single-strategy account with extra steps.
  6. Rerun the chosen weights with higher spreads and commissions to see how much margin of safety remains.

Prefer fewer parameters. Every extra input is another way to fit the past.

Perspective: what we see in portfolio tests

Our view is simple: a portfolio optimization is only as honest as the weakest series in it. The optimizer cannot tell a real market move from a missing bar, so the quality has to be built in before the first pass runs.

That is the standard we hold our data to. Our minute-bar sets are verified bar by bar, adjustments are documented, and each set is delivered as a complete download that is ready for direct import into MT4 and MT5. For a multi-symbol test that means every instrument follows the same conventions, so correlations and drawdowns reflect the market, not the feed.

The same standard applies whether a person or an AI tool is reading the results. Clean inputs make every later decision easier to trust, and our engineers, who collect the data, answer support questions directly.

Start

Getting the data for your portfolio

If your portfolio spans forex pairs, metals, stock indices and bonds, you want those series from one provider with one set of rules. We sell complete, clean minute-bar data sets since 2014 as a one-time download, with bundles by asset class and back-adjusted futures data. Browse them on the historical data page, or take the Annual Plan at 119 EUR per year.

Backtestmarket

If you also want automation and portfolio tooling for MetaTrader, our Expert Advisors and Indicators pages list what is available.

From backtest to live tracking

A good portfolio test is the start of a monitoring routine, not the end. Once the weights go live, compare live behavior with the test: trade frequency, average trade, and drawdown depth. Our piece on live MT5 Expert Advisor tracking names three numbers worth watching. If live results drift from the test, rerun the audit on the data first, then revisit the weights.

FAQ

Is MT5 the same as MQL5?

No. MetaTrader 5 is the trading platform, and MQL5 is the programming language you use to write Expert Advisors, indicators and scripts for it. The Strategy Tester inside the platform runs programs written in MQL5.

How do I backtest a multi-symbol portfolio in MT5?

Build or load a multi-currency EA, enable every symbol it needs in Market Watch, choose the period and mode, and run the tester. The tester processes the symbols the EA uses automatically. For the data side, see our guide to running an MT5 portfolio backtest.

How many parameters should a portfolio optimization use?

As few as the question requires. Risk per symbol, a group cap and a total exposure limit cover most portfolio questions. Each extra input widens the space of possible fits to past noise, so validate every candidate on a forward period before you trust it.

Does data quality really change portfolio optimization results?

Yes. Weights depend on how symbols moved relative to each other, and gaps or misaligned timestamps change those relationships. Auditing bars before you optimize keeps the optimizer working on market behavior instead of data defects.

Sources

Recommended

Related resources

Explore BacktestMarket's Expert Advisor robots to put the ideas in this article into practice.

Newsletter

Stay updated

New datasets, expert advisors, discounts, and trading insights — straight to your inbox.

Cart

Your cart is empty

Add some products to get started.