Most traders rely on technical indicators and experience to decide when to open or close trades. But what if your Expert Advisor (EA) could use a machine learning model to filter trade entries in real time? That’s what I set out to build — a connection between MetaTrader 5 and a Python-based prediction server that evaluates every potential trade before it happens.
Project Overview
This project combines two main parts:
1. A MetaTrader 5 Expert Advisor (EA) that calculates technical indicators such as EMAs, ATR, and trend strength, then sends that data to an API for validation before trading.
2. A Flask prediction server running a trained RandomForestClassifier model that returns whether a trade has a high probability of success.
The EA checks the prediction result and confidence score before deciding to execute or reject the trade.
How It Works
- The EA collects key metrics every time a signal forms.
- It sends a JSON request to the Flask API endpoint /predict.
- The Flask app preprocesses the data, scales the features, and uses the model to predict the trade outcome.
- The server responds with:
{ "prediction": 1, "confidence_pct": 74.3, "should_trade": true, "message": "High confidence trade" } - The EA uses that response to decide whether to proceed or skip the trade.
When running, the EA logs lines like this in MetaTrader:
--- ML FILTER CHECK ---
ML Prediction: WIN ML Confidence: 74.3% ML Decision: TRADE
Training the Model
I trained the model using past gold (XAUUSD) trade data stored in a CSV file.
The training script (simple_ema_strategy.py) builds engineered features such as EMA spreads, ATR percentages, trend strength variations, and time-based sin-cos encodings.
The model pipeline:
model = RandomForestClassifier(
n_estimators=200,
max_depth=15,
min_samples_split=10,
min_samples_leaf=5,
class_weight='balanced',
random_state=42
)
Once trained, it saves:
- xau_model.pkl – the model
- feature_scaler_advanced.pkl – the StandardScaler object
- feature_names_advanced.txt – feature order for inference
- model_info_advanced.txt – model summary and accuracy stats
Deploying the Prediction Server
The Flask API is defined in app.py.
It loads the model and exposes three endpoints:
- GET /health — returns model status
- POST /predict — returns a prediction
- POST /reload — reloads the model without restarting the server
For local development:
python app.py
The server runs at:
http://localhost:5000
To host it online for 24/7 access, I deployed it to Render with a simple Procfile:
web: gunicorn app:app --workers 2 --timeout 120
and the standard requirements.txt:
Flask
gunicorn
joblib
scikit-learn
pandas
numpy
Render automatically builds the service and gives it a public URL like:
https://xau-ml-server.onrender.com
Connecting MetaTrader 5
Inside the EA settings:
input bool UseMLFilter = true;
input string ML_ServerURL = "https://xau-ml-server.onrender.com/predict";
input double MinMLConfidence = 60.0;
In MetaTrader 5:
- Go to Tools → Options → Expert Advisors
- Check Allow WebRequest for listed URL
- Add your Render URL root:
https://xau-ml-server.onrender.comNow, every time the EA prepares a trade, it queries the server before acting. If the server is offline, the EA logs “ML: OFFLINE” and trades normally.
Common Pitfalls
- HTTP 500 errors: usually mean the incoming feature list doesn’t match what the model expects. Align your EA inputs and model feature columns.
- Model not loaded: check that all .pkl files exist in the same directory as app.py before deployment.
- Blocked WebRequest: ensure the API URL is whitelisted in MT5 settings.
Next Steps
The next iteration of this project will include:
- Real-time model updates via /reload
- Better feature selection for live trading
- Optional cloud logging for predictions
- A lightweight dashboard to visualize trade outcomes vs. model confidence
Blocked WebRequest: ensure the API URL is whitelisted in MT5 settings.
Next Steps
The next iteration of this project will include:
Real-time model updates via /reload
Better feature selection for live trading
Optional cloud logging for predictions
A lightweight dashboard to visualize trade outcomes vs. model confidence
Takeaway
This small project shows how easily machine learning can be integrated into trading workflows. With a simple Flask API and a few lines in your EA, you can turn static strategies into adaptive systems that make smarter trade decisions.
If you want to explore or adapt this approach for your own MetaTrader strategies, clone the setup, plug in your own model, and start experimenting.
Top comments (0)