Sign up with our partner broker and get free XAU/USD signals. JOIN US
LIVE MT5 BUILD 5830 LAST REV 2026-05-23
SESSION -- UTC --:--
SESSIONS
SYDNEY22:00–07:00 UTC
TOKYO00:00–09:00 UTC
LONDON07:00–16:00 UTC
NEW YORK12:00–21:00 UTC

Running ONNX machine learning models inside MT5

Since MT5 build 3620, released in March 2023, MetaQuotes added native support for ONNX models. ONNX support has been expanded across several builds since, including Float8 and Float16 inputs in build 4230 (March 2024) and CUDA-accelerated GPU inference in build 5572 (January 2026). You can train a model in Python (or any ONNX-compatible framework) and run inference directly inside an MQL5 EA. The mechanics are straightforward; whether ML actually improves your trading is a much harder question.

PUBLISHED 2026-05-24 READING TIME 12 MIN MT5 BUILD 5830 CATEGORY TOOLS
Reality check: Loading an ONNX model into MT5 is the easy part. Building a model that produces an edge worth trading is the hard part. The vast majority of academic ML research on financial markets does not survive walk-forward testing on real costs. This guide explains the mechanics; it cannot make a profitable model.

1. What ONNX is

ONNX (Open Neural Network Exchange) is a standard format for representing machine learning models. The idea: train a model in any framework (PyTorch, TensorFlow, scikit-learn, XGBoost), export to .onnx, and run inference in any environment that supports the format. The runtime is portable, the model artifact is a single file.

MetaQuotes added ONNX runtime support to MT5 starting with build 3620, released on March 10, 2023. This means MQL5 code can call OnnxCreate, OnnxRun, and related functions to perform inference on an ONNX model embedded in or loaded alongside an EA. Support has been actively expanded since: build 4230 (March 2024) added Float8 and Float16 input types, and build 5572 (January 2026) added CUDA-accelerated GPU inference on supported hardware.

2. The MT5 ONNX API surface

The core functions:

FunctionPurpose
OnnxCreateLoad an ONNX file and create a session handle
OnnxCreateFromBufferLoad an ONNX model from an in-memory byte buffer (useful for embedding the model as a resource)
OnnxRunPerform inference: provide input tensor(s), receive output tensor(s)
OnnxSetInputShape / OnnxSetOutputShapeSpecify tensor shapes when the model has dynamic dimensions
OnnxReleaseFree the session and resources

The full API is documented in the official MQL5 reference under the Onnx section. Function signatures and supported tensor types may change between MT5 builds; consult current docs before writing production code.

3. A minimal example

The pattern for using ONNX in an EA, simplified:

// In OnInit
long onnx_handle = OnnxCreate("model.onnx", ONNX_DEFAULT);
if(onnx_handle == INVALID_HANDLE)
{
   Print("Failed to load model");
   return(INIT_FAILED);
}

// Specify input shape if dynamic
const long input_shape[] = {1, 10};  // 1 batch, 10 features
OnnxSetInputShape(onnx_handle, 0, input_shape);

// In OnTick (or OnTimer, on bar close)
float features[10];
// ... fill features array with normalised inputs from market data

float prediction[1];
if(!OnnxRun(onnx_handle, ONNX_DEFAULT, features, prediction))
{
   Print("Inference failed");
   return;
}

// Act on prediction[0]

The actual ONNX file must be placed in the MQL5/Files directory of the MT5 data folder, or embedded into the EA as a resource.

4. What kinds of models work

Most common ML model types can be exported to ONNX:

  • Tree-based models: XGBoost, LightGBM, scikit-learn random forests. Often the most practical for tabular financial features.
  • Linear models: Logistic regression, ridge regression. Lightweight and fast.
  • Neural networks: Feedforward, recurrent (LSTM, GRU), convolutional, transformers. PyTorch and TensorFlow both export to ONNX.
  • Sequence models: LSTM and GRU networks for sequential time-series input.

Things that do not work well:

  • Models with custom operators not in the ONNX standard set.
  • Models trained with very recent framework features that the ONNX export does not yet support.
  • Models with extreme input dimensionality (millions of features) due to inference latency.

5. The feature engineering reality

The ONNX file is the easy part. Feature engineering is where most ML trading projects fail.

Common features used in retail-scale ML trading:

  • Lagged returns over multiple horizons (5-minute, 1-hour, 1-day).
  • Technical indicators (RSI, ATR, Bollinger position) computed over the window the EA needs.
  • Cross-asset features (USD index, VIX, sector indices) where the EA can read them.
  • Calendar features (day of week, hour of day, days to NFP, days to FOMC).
  • Volatility regime features (recent realised volatility, ATR ratio current to long-term).

The trap: feature engineering on historical data is a form of data snooping. Every feature you add that "works" in backtest may simply be exploiting historical noise. Walk-forward validation is non-negotiable.

6. The training pipeline

Workflow for building a model to use in MT5:

  1. Export historical data from MT5. Use Strategy Tester's data export or pull via MT5 Python integration.
  2. Define your target. What is the model predicting? Common choices: next-bar return sign (classification), next-bar return magnitude (regression), or probability of stop loss hit before take profit (classification).
  3. Engineer features. Compute the same features you will be able to compute in real time inside the EA.
  4. Train and validate. Use time-series cross-validation (not random shuffle, which leaks future information into training).
  5. Export to ONNX. Use the framework's ONNX export utility (e.g. torch.onnx.export, skl2onnx.convert_sklearn).
  6. Verify ONNX inference matches framework inference. Run the same inputs through both and confirm outputs are identical (or near-identical due to float precision).
  7. Place the .onnx file in MT5 and write the EA inference code. Backtest in MT5 to confirm the EA produces the same predictions as your Python pipeline did on the same data.

7. Inference latency

ONNX inference inside MT5 is fast for typical retail models. A small tree-based model with 10-20 features runs in well under a millisecond. Even moderate neural networks (a few thousand parameters) run in single-digit milliseconds.

This is fast enough for any non-HFT use case. EAs that act on bar close (1-minute or longer) have hundreds of milliseconds of latency budget; ONNX inference is not the bottleneck. EAs that try to act on every tick may need to consider whether feature computation (not the ONNX inference itself) is fast enough.

8. Common pitfalls

PitfallWhy it goes wrong
Training on future-leaking featuresUsing future data to compute features that the EA cannot compute in real time. The model looks brilliant in research; useless in production.
Normalisation driftFeatures were normalised during training using the mean and std of the training period. If you do not apply the same normalisation in the EA, inputs go to the model on different scales.
Target leakage through featuresIncluding the target itself or a closely correlated quantity as a feature. Common in lagged-return setups when lag is misaligned by one bar.
Overfitting through hyperparameter tuningTuning on validation data turns validation data into training data. Hold out a true test set you only use once.
Ignoring trading costsModel predictions need to exceed spread plus commission to be worth acting on. Most "profitable" predictions have edges smaller than costs.
Stationarity violationsMarkets change. A model trained on 2018-2022 may not generalise to current regimes. Retraining schedules and regime detection are open research problems.

9. Should you use ML in your EA?

An honest answer: probably not as your first or second EA. The conventional wisdom in quantitative trading is that simple, robust, well-understood strategies outperform complex ML approaches in most retail contexts. Reasons:

  • Retail data sources are limited compared to institutional alternative data. Without unique data, the model has limited room to find unique edges.
  • Sample sizes for distinctive market events (NFP releases, FOMC decisions, crisis days) are tiny. Models learn what the dataset contains; rare events are systematically underweighted.
  • Statistical edges in retail-accessible features are typically thin and degrade quickly as the strategy ages.
  • The discipline required to walk-forward test honestly and not overfit is harder than the modelling itself.

That said, ONNX in MT5 is a legitimate tool for traders who have already built statistical intuition with simpler strategies and want to encode more complex relationships. The mechanics are sound; the strategic application is where most attempts fail.

10. Where to start

If you do want to experiment:

  1. Read the MetaQuotes ONNX documentation and the official ONNX example projects in MQL5 Code Base.
  2. Try the simplest possible model first: logistic regression with 5 features predicting next-bar direction. Most of the lessons (data leakage, normalisation, walk-forward) apply to even this simple case.
  3. Get a clean Python data pipeline working before complicating with neural networks.
  4. Backtest brutally honestly. If your "ML EA" cannot beat a simple moving average baseline on the same data, the model is not adding value.

FAQ

Do I need a GPU to use ONNX in MT5?

Inference uses CPU by default. GPU inference may be supported in some MT5 builds but is rarely needed for retail-scale models. Training (in Python, outside MT5) may benefit from GPU; inference does not.

Can I retrain the model inside the EA?

No. MT5 supports ONNX inference but not training. You must train externally (typically in Python) and import the resulting model. To retrain periodically, your workflow needs an external retraining pipeline that produces updated .onnx files.

What ONNX runtime version does MT5 use?

This changes between MT5 builds. Recent builds support a broad set of ONNX operators; very recent operators from latest ONNX specifications may not be supported. Check the current documentation if your model export complains about unsupported operators.

Can I share an ONNX model with other MT5 users?

Yes. The .onnx file is portable. If your EA loads the model from MQL5/Files, distribute the .onnx alongside the EA. If the model is embedded as a resource in the EA, the .ex5 file contains it.

Is using ML in MT5 cheating?

No. Retail traders have always used computers to assist trading; ML is just another tool. The market does not care which tools you use; it cares whether your decisions are profitable after costs.