LSTM Library
- Libraries
-
Thalles Nascimento De Carvalho
🚀 **Exploring the fascinating paths of the financial markets**, I am passionate about both the art of trading and the science of programming. My journey began with a curiosity to understand market movements, evolving into the development of sharp skills to identify and seize profitable - Version: 4.12
- Activations: 5
Professional Neural Network Library for Algorithmic Trading
LSTM Library brings the power of recurrent neural networks to your trading strategies in MQL5. This professional-level implementation includes LSTM, BiLSTM, and GRU networks with advanced features typically found only in specialized machine learning frameworks.
Key Features
- Complete implementation of LSTM, BiLSTM and GRU
- Recurrent dropout for better generalization
- Multiple optimization algorithms (Adam, AdamW, RAdam)
- Advanced normalization techniques
- Comprehensive metrics evaluation system
- Training progress visualization
- Support for imbalanced data with class weights
Technical Specifications
- Pure MQL5 implementation - no external dependencies
- Optimized for trading applications
- Comprehensive error handling and validation
- Complete support for saving/loading trained models
- Extensive documentation
Integration Instructions
To integrate the LSTM Library into your Expert Advisor, follow these steps:
1. Full Library Import
#import "LSTM_Library.ex5" // Library Information void GetLibraryVersion(string &version); void GetLibraryInfo(string &info); // Model Management int CreateModel(string name); int DeleteModel(int handle); // Layer Construction int AddLSTMLayer(int handle, int units, int input_size, int seq_len, bool return_seq); int AddLSTMLayerEx(int handle, int units, int input_size, int seq_len, bool return_seq, double recurrent_dropout); int AddGRULayer(int handle, int units, int input_size, int seq_len, bool return_seq); int AddBiLSTMLayer(int handle, int units, int input_size, int seq_len, bool return_seq); int AddBiLSTMLayerEx(int handle, int units, int input_size, int seq_len, bool return_seq, double recurrent_dropout); int AddDenseLayer(int handle, int input_size, int units, int activation); int AddDropoutLayer(int handle, double rate); int AddBatchNormLayer(int handle, int size); int AddLayerNormLayer(int handle, int size); // Compilation and Training int CompileModel(int handle, int optimizer, double lr, int loss); int SetClassWeights(int handle, double &weights[], int n_classes); int EnableConfusionMatrixTracking(int handle, int n_classes); int GetConfusionMatrix(int handle, int &confusion_matrix[]); int FitModel(int handle, double &X_train[], double &y_train[], int n_train, int input_dim, double &X_val[], double &y_val[], int n_val, int epochs, int batch); // Prediction and Evaluation int PredictSingle(int handle, double &input_data[], int input_size, double &output_data[]); int PredictBatch(int handle, double &X[], int n_samples, int input_dim, double &predictions[]); double EvaluateModel(int handle, double &X[], double &y[], int n_samples, int input_dim); double CalculateClassificationMetrics(double &y_true[], double &y_pred[], int n_samples, int n_classes, double &precision[], double &recall[], double &f1[]); // Data Preprocessing int CreateScaler(); int DeleteScaler(int handle); int FitScaler(int handle, double &data[], int samples, int features); int TransformData(int handle, double &data[], double &transformed[], int samples, int features); int InverseTransform(int handle, double &transformed[], double &original[], int samples, int features); int FitTransformData(int scaler, double &data[], double &transformed[], int samples, int features); // Callbacks and Schedulers int AddEarlyStopping(int handle, int patience, double min_delta); int AddProgressBar(int handle, int epochs); int AddCosineScheduler(int handle, double base_lr, int T_0, int T_mult); int AddOneCycleLR(int handle, double max_lr, int total_steps); // Utilities int PrintModelSummary(int handle); int SetModelTrainingMode(int handle, int training); int GetModelTrainingMode(int handle); int SaveModel(int handle, string filename); int LoadModel(int handle, string filename); int SaveHistory(int handle, string filename); void CleanupAll(); int GetActiveModelsCount(); int GetActiveScalersCount(); #import
2. Initialization in OnInit()
int model_handle = 0; int OnInit() { // Create LSTM model model_handle = CreateModel("TradingModel"); if(model_handle <= 0) return INIT_FAILED; // Add layers if(AddLSTMLayer(model_handle, 32, 5, 10, false) <= 0) return INIT_FAILED; if(AddDropoutLayer(model_handle, 0.2) <= 0) return INIT_FAILED; if(AddDenseLayer(model_handle, 32, 1, 1) <= 0) return INIT_FAILED; // Compile model (Adam optimizer, MSE loss) if(CompileModel(model_handle, 1, 0.001, 0) <= 0) return INIT_FAILED; // Load existing model if available if(FileIsExist("model.bin")) LoadModel(model_handle, "model.bin"); return INIT_SUCCEEDED; }
3. Cleanup in OnDeinit()
void OnDeinit(const int reason) { if(model_handle > 0) { SaveModel(model_handle, "model.bin"); DeleteModel(model_handle); } CleanupAll(); }
4. Usage in OnTick()
void OnTick() { // Prepare features double features[50]; // For example, 5 features * 10 sequence length // Fill feature array with market data // ... // Make prediction double prediction[]; if(PredictSingle(model_handle, features, ArraySize(features), prediction) > 0) { if(prediction[0] > 0.5) { // Bullish signal - place buy order } else { // Bearish signal - place sell order } } }
HARNESS THE POWER OF MACHINE LEARNING IN TRADING
The LSTM Library is designed to be easily integrated into your EAs and indicators, providing advanced machine learning capabilities directly in MetaTrader 5.
Follow the code example above to start implementing neural network-based predictions in your trading systems. The simple example can be easily adapted to your specific needs.
Explore the advanced features detailed below to leverage the full potential of this library in your trading strategies.
Advanced Features Available
Recurrent Layer Variants
- AddLSTMLayerEx() - LSTM with recurrent dropout for better generalization
- AddBiLSTMLayerEx() - Bidirectional BiLSTM with recurrent dropout
Normalization and Regularization
- AddBatchNormLayer() - Batch normalization for stable training
- AddLayerNormLayer() - Layer normalization
Handling Imbalanced Data
- SetClassWeights() - Set weights for minority classes
- EnableConfusionMatrixTracking() - Detailed performance monitoring by class
Advanced Optimization
- AddCosineScheduler() - Cyclic learning rates with warm restarts
- AddOneCycleLR() - One-Cycle Learning Rate implementation
Comprehensive Evaluation
- PredictBatch() - Batch predictions for higher efficiency
- EvaluateModel() - Complete evaluation on test data
- CalculateClassificationMetrics() - Detailed metrics (precision, recall, F1)
Data Preprocessing
- CreateScaler/FitScaler - Normalization of input data
- TransformData/InverseTransform - Conversion between scales
Requirements
- MetaTrader 5
- Basic understanding of machine learning concepts
- Intermediate MQL5 programming skills
SUPERCHARGE YOUR TRADING SYSTEMS
Transform your existing strategies and indicators with the power of machine learning directly in MQL5. This direct integration means no external connections, no Python dependencies, and no API complexities - just pure predictive power inside your trading platform.
Whether you're developing price prediction systems, volatility forecasting, or advanced pattern recognition, LSTM Library provides the foundation for truly intelligent trading decisions that adapt to changing market conditions.
Keywords: LSTM Stock Prediction, LSTM Price Forecasting, Neural Network Trading, MQL5 Deep Learning, Time Series Forecasting, Forex Machine Learning, Cryptocurrency AI Trading, Market Pattern Recognition, BiLSTM Trading System, GRU Market Analysis, AI Algorithmic Trading, MQL5 Deep Learning, Price Direction Prediction, Machine Learning for HFT
