← Back to Blog
Guides 12 min read

ONNX Models in MT5: How Real AI Trading Actually Works

Most 'AI trading bots' don't use AI at all. ONNX changed that — it lets you run real neural networks inside MetaTrader 5. Here's a technical deep dive on how it works, what it enables, and how we use it to trade gold with 4 ML models running in parallel.

EN ES DE FR PT RU ZH JA AR

TL;DR

  • ONNX (Open Neural Network Exchange) is an open-source format that lets you run trained ML models directly inside MT5 — no external servers, no API calls.
  • MetaTrader 5 has native ONNX Runtime support since build 3600+, with dedicated MQL5 functions for loading, running, and managing models.
  • This is what separates real AI EAs from fake ones: if there's no .onnx file in the EA package, it's not using machine learning.
  • Karat Killer uses 4 ONNX models (XGBoost, LightGBM, CatBoost, Neural Network) running as an ensemble inside MT5 for XAUUSD trading.

What Is ONNX? (And Why Should Traders Care)

ONNX (Open Neural Network Exchange) is an open-source format for machine learning models. Think of it as a universal translator: you train a model in Python using frameworks like PyTorch, TensorFlow, XGBoost, or scikit-learn — then export it to .onnx format so it can run anywhere.

For traders, this matters because MetaTrader 5 has native ONNX Runtime support. That means you can train a sophisticated ML model on your workstation, export it as an .onnx file, embed it directly in an Expert Advisor, and run it on every tick — without external servers, API calls, or internet dependencies.

This is a fundamental shift. Before ONNX, running ML models in MT5 meant either:

ONNX solved all three problems. The model runs natively inside the terminal, at the speed of C++, with zero external dependencies.

The ONNX project is backed by Microsoft, Meta, Amazon, and dozens of other major tech companies — so it's not a niche experiment. It's the industry standard for model interoperability.

How ONNX Works Inside MetaTrader 5

MetaQuotes added native ONNX support to MT5 starting with build 3600+. Here's the technical flow:

The Pipeline: Train → Export → Embed → Run

  1. Train your model in Python (or any ML framework). This is where you do feature engineering, cross-validation, walk-forward testing — all the heavy lifting.
  2. Export the trained model to .onnx format using libraries like onnxmltools, skl2onnx, or torch.onnx.export().
  3. Embed the .onnx file as a resource in your MQL5 Expert Advisor (similar to embedding images or sound files).
  4. Run the model on every tick using MQL5's native ONNX functions: OnnxCreate(), OnnxRun(), OnnxRelease().

Key MQL5 ONNX Functions

MT5 provides a complete set of functions for working with ONNX models:

The ONNX Runtime handles automatic data type conversion between MQL5 types and the model's expected tensor types — so you don't need to manually cast between float/double formats.

Performance

Because the ONNX Runtime is compiled C++ code running inside the MT5 process, inference is extremely fast. A typical model with 50-100 features runs in under 1 millisecond per prediction. That's fast enough for tick-by-tick analysis on even the most volatile instruments.

What Makes ONNX a Game-Changer for EA Development

Before ONNX in MT5, the gap between ML research and live trading was massive. You could build incredible models in Python — but getting them into a production EA was a nightmare. Here's what ONNX specifically solves:

1. Framework Independence

You're not locked into any specific ML toolkit. Train with XGBoost today, switch to LightGBM tomorrow, add a PyTorch neural network next month — they all export to the same .onnx format and run identically inside MT5.

2. No External Dependencies

The model runs inside the MT5 process. No Python server to maintain. No API calls that might fail. No internet connection required for predictions. This is critical for live trading, where reliability matters more than anything.

3. Full Strategy Tester Compatibility

ONNX models work natively in the MT5 Strategy Tester. You can backtest an ML-based EA across 10+ years of tick data — exactly the same way you'd test a traditional rule-based EA. This is huge for validation.

4. Model Updates Without Code Changes

When you retrain a model with new data, you just replace the .onnx file. The EA code stays the same. This makes maintenance and updates dramatically simpler than hardcoded approaches.

5. Multi-Model Architecture

MT5 can load multiple ONNX models simultaneously. This enables ensemble approaches — running several different models and combining their predictions for more robust signals. More on this below.

The ONNX Training Workflow (Step by Step)

Here's what the actual development process looks like for building an ONNX-powered EA — not the marketing version, the real one:

Step 1: Feature Engineering

Raw price data (OHLCV) is nearly useless for ML models. You need to transform it into meaningful features: technical indicators, statistical measures, volatility metrics, time-based patterns, inter-market correlations. A good feature set might include 50-200 engineered features per bar.

This is where 80% of the actual work happens. The model is only as good as its inputs.

Step 2: Training & Validation

You split your data into training, validation, and test sets — but never randomly for time series. Walk-forward validation is the standard: train on 2015-2020, validate on 2021, test on 2022. Then shift the window forward and repeat.

If your model only works on one specific time window, it's overfit. Genuine ML models must demonstrate stability across multiple market regimes.

For more on why most ML EAs fail at this stage, see our deep dive on machine learning Expert Advisors: hype vs reality.

Step 3: ONNX Export

Once validated, you export the model. Example for XGBoost:

from onnxmltools import convert_xgboost
onnx_model = convert_xgboost(xgb_model, initial_types=[('features', FloatTensorType([None, n_features]))])

The exported .onnx file typically ranges from 100KB to 5MB depending on model complexity.

Step 4: MQL5 Integration

Embed the .onnx file as a resource in your EA, load it in OnInit(), run predictions in OnTick(), and release in OnDeinit(). The MQL5 code handles feature calculation from live price data and feeds it to the model.

Step 5: Strategy Tester Validation

Before going live, backtest the EA with the embedded ONNX model across your entire dataset — including out-of-sample periods. If backtest results don't match your Python validation, something is wrong with the integration.

Ensemble Models: Why One ONNX Isn't Enough

In competitive ML, single models rarely win. Ensembles — combinations of multiple models — consistently outperform individual models in accuracy and robustness. The same applies to trading.

Why Ensembles Work

Different ML algorithms see the data differently:

When you combine their predictions, errors from one model get corrected by others. The ensemble's signal is more stable and reliable than any individual model.

How Ensembles Work in MT5

MT5's ONNX support makes this practical. You can load 2, 3, 4, or more ONNX models simultaneously — each running its own inference on the same input features. Then your MQL5 code combines the predictions using voting, averaging, or weighted schemes.

The overhead is minimal. Running 4 ONNX models instead of 1 might add 2-3 milliseconds per tick — negligible for any trading strategy.

Real Example: 4-Model Ensemble for Gold

Our Karat Killer EA uses exactly this approach for XAUUSD trading: 4 different ONNX models (XGBoost, LightGBM, CatBoost, and a neural network) running in parallel. Each model votes on whether to go long, short, or stay flat. Trades are only executed when the ensemble reaches consensus — reducing false signals significantly.

The result: a backtest return of +7,229% across 10 years of XAUUSD data, with the model validated through walk-forward testing across multiple market regimes.

ONNX vs Other AI Approaches in MT5

ONNX isn't the only way to add intelligence to an EA. Here's how it compares to the alternatives:

ApproachProsConsBest For
ONNX RuntimeNative MT5 support, fast, reliable, backtestableRequires ML expertise for trainingProduction-grade ML EAs
External API (Python server)Full Python ecosystem, easy to prototypeLatency, reliability, can't backtest properlyResearch & prototyping
Hardcoded weightsSimple, no dependenciesFragile, can't update easily, limited model typesVery simple models only
DLL importsFull flexibilitySecurity risks, compatibility issues, MQL5 Market won't allow itCustom institutional systems
"AI" label onlyEasy to marketNot actually AI — misleadingMarketing (unfortunately common)

For anyone serious about ML in trading, ONNX is the clear winner. It's the only approach that gives you production-grade reliability, Strategy Tester compatibility, AND the ability to sell on the MQL5 Market (since DLLs are restricted).

This is also why it's the most reliable indicator of whether an EA actually uses machine learning. If an EA claims to be "AI-powered" but doesn't include .onnx files in its resources — it's not using real ML. Period. We covered the full list of red flags in our article on ML Expert Advisors: hype vs reality.

How BLODSALGO Uses ONNX (Our Actual Architecture)

We're going to be specific — because vague "AI" claims are exactly what we stand against.

Karat Killer — 4-Model XAUUSD Ensemble

Karat Killer is our most technically advanced EA. Here's what's inside:

Stability Killer AI — ML-Powered AUDCAD

Stability Killer AI uses a different approach — a single specialized ONNX model optimized for AUDCAD's unique mean-reverting characteristics. The priority here is capital preservation:

Both EAs include the .onnx model files as embedded resources — you can verify this yourself by checking the EA's resource structure in MetaEditor. If you want to understand how gold and AI intersect in trading, we wrote a dedicated piece on AI and machine learning for XAUUSD trading.

Getting Started with ONNX in Your Own EAs

If you're an MQL5 developer looking to add ML capabilities to your EAs, here's a practical roadmap:

Prerequisites

Minimal Working Example

The simplest ONNX integration looks like this in MQL5:

// In OnInit()
int handle = OnnxCreate("model.onnx", 0);
OnnxSetInputShape(handle, 0, input_shape);
OnnxSetOutputShape(handle, 0, output_shape);

// In OnTick()
float features[];
// ... fill features from price data ...
float prediction[];
OnnxRun(handle, 0, features, prediction);

// In OnDeinit()
OnnxRelease(handle);

Common Pitfalls

MetaQuotes has published extensive ONNX documentation with code examples for various model types.

The Future of ONNX in Algorithmic Trading

ONNX adoption in MT5 is still early. Most EAs on the MQL5 Market are still purely rule-based — which isn't necessarily bad, but it means the competitive advantage of genuine ML is significant.

What's Coming

Why This Matters Now

The edge in algorithmic trading comes from doing what others can't — or won't. Right now, the barrier to building ONNX-powered EAs is high enough that very few developers attempt it. That barrier will drop over time.

For traders evaluating EAs, understanding ONNX is a practical skill: it lets you distinguish between genuine ML products and marketing-only "AI" labels. Check for .onnx files, ask about training methodology, demand walk-forward results. The technology is real — but only when actually implemented.

FAQ: ONNX Models in MetaTrader 5

What version of MT5 supports ONNX?
ONNX Runtime support was added in MetaTrader 5 build 3600+. Make sure your terminal is updated to the latest version. You can check your build number in Help → About in the terminal.
Do ONNX models slow down my EA?
Minimal impact. A typical model with 50-100 input features runs inference in under 1 millisecond. Even a 4-model ensemble adds only 2-3ms per tick. For most strategies, this is imperceptible.
Can I use ONNX models in the MT5 Strategy Tester?
Yes — this is one of ONNX's biggest advantages. Models run natively in the Strategy Tester, so you can backtest ML-based EAs across years of historical data just like any other EA.
What ML frameworks can export to ONNX?
Most major frameworks: scikit-learn, XGBoost, LightGBM, CatBoost, PyTorch, TensorFlow, Keras, and more. The conversion tools (onnxmltools, skl2onnx, torch.onnx) handle the export process.
How do I know if an EA actually uses ONNX?
Open the EA in MetaEditor and check the Resources tab. Real ONNX-based EAs include .onnx files as embedded resources. If there are no .onnx files, the EA isn't using machine learning — regardless of what the marketing says.
Does ONNX work with VPS hosting?
Yes. Since the ONNX Runtime runs inside the MT5 process, it works on any system that can run MetaTrader 5 — including VPS servers. No additional software installation required.

Risk Disclaimer: Trading foreign exchange, gold (XAUUSD), and other financial instruments involves significant risk of loss and is not suitable for all investors. The information in this article is for educational purposes only and does not constitute financial advice. Past performance of any Expert Advisor does not guarantee future results. Always test strategies on a demo account before trading with real capital, and never risk money you cannot afford to lose.