How This Works:
- MQL4 Sends Market Data – The EA extracts relevant market features and sends them to a Python script via a file or TCP communication.
- Python Processes Data & Makes Predictions – A machine learning model (e.g., a neural network or decision tree) is trained externally and provides trading signals.
- MQL4 Executes Trades – The EA reads the AI-generated signals and executes trades accordingly.
Step 1: MQL4 Expert Advisor
This EA will interact with an external AI model by saving market data and reading AI-generated signals.
//+------------------------------------------------------------------+
//| Trainable AI-Based Expert Advisor for MT4 |
//+------------------------------------------------------------------+
#property strict
// Input parameters
input double LotSize = 0.1;
input double StopLoss = 50;
input double TakeProfit = 100;
// File paths (ensure proper paths for live trading)
string DataFile = "market_data.csv";
string SignalFile = "ai_signal.txt";
// Function to write market data for AI model
void WriteMarketData()
{
int fileHandle = FileOpen(DataFile, FILE_CSV | FILE_WRITE, ',');
if (fileHandle != INVALID_HANDLE)
{
for (int i = 0; i < 100; i++) // Collect last 100 candles
{
double open = iOpen(Symbol(), PERIOD_M15, i);
double high = iHigh(Symbol(), PERIOD_M15, i);
double low = iLow(Symbol(), PERIOD_M15, i);
double close = iClose(Symbol(), PERIOD_M15, i);
double volume = iVolume(Symbol(), PERIOD_M15, i);
FileWrite(fileHandle, open, high, low, close, volume);
}
FileClose(fileHandle);
}
}
// Function to read AI-generated trading signal
int ReadAISignal()
{
int signal = 0;
int fileHandle = FileOpen(SignalFile, FILE_CSV | FILE_READ);
if (fileHandle != INVALID_HANDLE)
{
string line = FileReadString(fileHandle);
FileClose(fileHandle);
signal = StringToInteger(line);
}
return signal; // 1 = Buy, -1 = Sell, 0 = No Trade
}
// Main trading logic
void OnTick()
{
WriteMarketData(); // Export market data for AI processing
int signal = ReadAISignal(); // Get AI decision
if (signal == 1 && OrdersTotal() == 0)
{
OrderSend(Symbol(), OP_BUY, LotSize, Ask, 10, Ask - StopLoss * Point, Ask + TakeProfit * Point, "AI Buy", 0, 0, clrBlue);
}
else if (signal == -1 && OrdersTotal() == 0)
{
OrderSend(Symbol(), OP_SELL, LotSize, Bid, 10, Bid + StopLoss * Point, Bid - TakeProfit * Point, "AI Sell", 0, 0, clrRed);
}
}
Step 2: Python AI Model
This Python script reads the market data, makes a prediction, and saves a trading signal for MQL4 to use.
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
import joblib
# Load data
data = pd.read_csv("market_data.csv", header=None)
data.columns = ["Open", "High", "Low", "Close", "Volume"]
# Feature engineering (example)
data["PriceChange"] = data["Close"].pct_change()
data["Volatility"] = data["High"] - data["Low"]
data.dropna(inplace=True)
# Load trained AI model
try:
model = joblib.load("ai_trading_model.pkl")
except:
model = RandomForestClassifier(n_estimators=100) # Initialize if no model exists
# Prepare input for prediction
scaler = StandardScaler()
X = scaler.fit_transform(data[["PriceChange", "Volatility"]].tail(1))
# Make AI prediction: 1 (Buy), -1 (Sell), 0 (Hold)
signal = model.predict(X)[0]
# Save signal for MT4
with open("ai_signal.txt", "w") as f:
f.write(str(signal))
Step 3: Training the AI Model
You can train the model using historical forex data and save it as ai_trading_model.pkl using the following script:
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import joblib
# Load and preprocess historical market data
data = pd.read_csv("historical_data.csv") # Use real historical data
data["PriceChange"] = data["Close"].pct_change()
data["Volatility"] = data["High"] - data["Low"]
data["Target"] = np.where(data["PriceChange"] > 0, 1, -1) # 1 = Buy, -1 = Sell
data.dropna(inplace=True)
X = data[["PriceChange", "Volatility"]]
y = data["Target"]
scaler = StandardScaler()
X = scaler.fit_transform(X)
# Train AI model
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
# Save trained model
joblib.dump(model, "ai_trading_model.pkl")
print("AI Model Trained & Saved!")
How to Use This System
- Train the AI Model: Run the training script using historical data.
- Deploy Python AI Script: This script will generate trading signals continuously.
- Run MQL4 Expert Advisor: The EA will read AI signals and execute trades accordingly.
Advantages of This Approach
✅ Trainable AI: The AI model can be retrained with new data for better predictions.
✅ External Processing: Python handles machine learning, avoiding MQL4 limitations.
✅ Scalability: Can be extended to deep learning models like TensorFlow or PyTorch.