🐍 Tutoriel Pratique

Comment Exporter Python (PyTorch + Sklearn) vers ONNX et Utiliser dans MT5

Par Dan Machado · 11 min de lecture

Tutoriel pas à pas, sans superflu : vous finissez avec deux modèles ONNX fonctionnels (un Sklearn Random Forest, un PyTorch LSTM), prêts pour l’Expert Advisor MT5. Prérequis : Python 3.10+ et MT5 installé.

Configuration de l’environnement Python

pip install MetaTrader5 numpy pandas scikit-learn
pip install onnx onnxruntime onnxmltools skl2onnx
pip install torch torchvision

Partie 1 — Random Forest (Sklearn) → ONNX

Cas d’usage : classifier la direction de la prochaine bougie (haut/bas) basé sur les retours lagged. Random Forest est léger, s’entraîne vite, fonctionne bien comme baseline.

Étape 1 : Collecter les données MT5

import MetaTrader5 as mt5
import pandas as pd

mt5.initialize()
rates = mt5.copy_rates_from_pos("EURUSD", mt5.TIMEFRAME_H1, 0, 20000)
df = pd.DataFrame(rates)
df['time'] = pd.to_datetime(df['time'], unit='s')
df.to_csv("eurusd_h1.csv", index=False)
mt5.shutdown()

Étape 2 : Entraîner et exporter Random Forest

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType

X = np.load("X.npy")
y = np.load("y.npy")
split = int(len(X) * 0.8)

model = RandomForestClassifier(n_estimators=200, max_depth=8, random_state=42)
model.fit(X[:split], y[:split])
print(f"Accuracy: {model.score(X[split:], y[split:]):.3f}")

initial_type = [('input', FloatTensorType([None, 10]))]
onnx_model = convert_sklearn(model, initial_types=initial_type, target_opset=15)
with open("rf.onnx", "wb") as f:
    f.write(onnx_model.SerializeToString())

Partie 2 — LSTM (PyTorch) → ONNX

import torch
import torch.nn as nn

class LSTMTrader(nn.Module):
    def __init__(self):
        super().__init__()
        self.lstm = nn.LSTM(1, 32, 2, batch_first=True, dropout=0.2)
        self.fc = nn.Linear(32, 2)
    def forward(self, x):
        out, _ = self.lstm(x)
        return self.fc(out[:, -1, :])

model = LSTMTrader()
model.eval()
dummy_input = torch.randn(1, 10, 1)
torch.onnx.export(
    model, dummy_input, "lstm.onnx",
    input_names=['input'], output_names=['output'],
    dynamic_axes={'input': {0: 'batch'}, 'output': {0: 'batch'}},
    opset_version=15
)

Partie 3 — Utiliser dans Expert Advisor MT5

Les fichiers .onnx vont dans le dossier MQL5\Files. Dans l’EA, chargez via OnnxCreate :

long handle = OnnxCreate("rf.onnx", ONNX_DEFAULT);

const long input_shape[]  = {1, 10};
const long output_shape[] = {1};
OnnxSetInputShape(handle, 0, input_shape);
OnnxSetOutputShape(handle, 0, output_shape);

matrix input(1, 10);
for(int i = 0; i < 10; i++) {
    double c0 = iClose(_Symbol, PERIOD_CURRENT, i + 1);
    double c1 = iClose(_Symbol, PERIOD_CURRENT, i + 2);
    input[0][i] = (float)((c0 - c1) / c1);
}

vector output(1);
OnnxRun(handle, ONNX_DEFAULT, input, output);
int direction = (int)output[0];

Validation dans Strategy Tester

Avant le live, toujours backtester dans MT5 Strategy Tester. Checklist : Profit factor > 1.5, drawdown max < 20%, 200+ trades, 30 jours démo minimum, risque par trade ≤ 2%, stop loss toujours défini.

Troubleshooting courant

  • 'Operator not supported' à l'export : ajustez opset_version (essayez 13, 14, 15, 17)
  • OnnxRun retourne false : vérifiez les shapes
  • Prédictions NaN : feature scaling — normalisez pareil en Python et MQL5
  • Modèle gigantesque : simplifiez

🚀 Pour tester des EA avec ONNX, démo gratuite Deriv MT5 (10 000 $ virtuels) :

Ouvrir la démo Deriv MT5 →

DM

Dan Machado

Fondateur IA Trader Pro · Expert IA appliquée au trading

⚠️ Avertissement : Contenu éducatif, pas un conseil d'investissement. Le trading implique un risque substantiel. Les modèles d'IA ne garantissent pas les profits. Testez toujours en démo avant le réel. L'article contient un lien d'affiliation Deriv.