May 4, 2026 · 12 min read

Neural Networks in MQL5 Expert Advisors

Algorithmic TradingBacktestingProgramming

Neural Networks in MQL5 Expert Advisors

Neural networks are transforming the way MQL5 Expert Advisors operate, moving beyond simple rule-based strategies to systems capable of learning directly from market data. By analyzing patterns in OHLC prices, volumes, and technical indicators, these networks produce trading signals like buy, sell, or hold. Here’s what you need to know:

  • What they do: Neural networks mimic human brain functions to process market data and make decisions.
  • Why they matter: They handle complex, multidimensional data, offering better performance than traditional EAs.
  • How they’re used in MQL5: Through libraries like ALGLIB and tools like the MetaTrader 5 Strategy Tester, these networks can be integrated and optimized for trading.

Results are promising. For example, a neural network EA achieved a 66.7% annual return with only an 11% drawdown on EURUSD data from 2017–2025. By normalizing inputs, defining effective network structures, and using advanced optimization techniques, MQL5 traders can significantly improve their strategies.

The key steps include:

  • Adding neural network libraries to MQL5.
  • Defining network topology and activation functions.
  • Training with normalized market data and technical indicators.
  • Backtesting and optimizing using tools like MetaTrader’s Strategy Tester.

This approach allows traders to develop smarter, more responsive EAs capable of adapting to market changes. Regular retraining and careful parameter tuning ensure these systems remain effective over time.

Complete Neural Network Implementation Process for MQL5 Expert Advisors

Complete Neural Network Implementation Process for MQL5 Expert Advisors

The BEST Free DEEP NEURAL NETWORK (DNN) For Forex Trading. How To Create DNN In MQL5/MT5 - PART 124

MQL5

Setting Up Neural Networks in MQL5

Setting up a neural network in MQL5 involves three main steps: incorporating the necessary libraries, defining the network's structure, and training it with normalized data. These steps form the foundation for integrating neural networks into MQL5 Expert Advisors, improving automated trading strategies.

Adding Neural Network Libraries to MQL5

Start by including the required neural network libraries in your Expert Advisor file using the #include directive. Depending on the library you choose, common header files might be NeuroNet.mqh, DeepNeuralNetwork.mqh, or MLP.mqh. After including the library (e.g., NeuroNet.mqh), you can create an instance of the network, such as Net = new CNet(Topology). To save resources, you can load a pre-trained model using the .Load() function.

To maintain continuity and enable integration with external tools, use the Save() and Load() functions to store the trained weights in a .nnw file. These files are saved in the Common/Files directory, making them accessible for future use.

Once the libraries are in place, the next step is to define the network's structure.

Building a Basic Neural Network Structure

The network's structure is defined by its topology, which specifies the number of neurons in each layer. For example, a simple 4-4-3 topology consists of 4 input neurons, 4 hidden neurons, and 3 output neurons, requiring 35 weights and biases. If you need a more complex model, you could use a 4-4-5-3 structure, which requires 63 weights and biases.

To set up the topology, use a CArrayInt object where each element represents the number of neurons in a specific layer. Since MQL5 only allows dynamic arrays in the first dimension, you can use #define statements to manage additional dimensions efficiently. Weights assign importance to inputs, while biases adjust the weighted sums before applying activation functions.

For activation functions, use Tan-h in the hidden layers and Softmax in the output layer. Adding a scaling coefficient - such as 0.4 for Sigmoid or 0.2 for Tan-h - can improve the activation range and performance.

With the structure defined, the final step is to train the network using normalized market data.

Training Neural Networks with Market Data

To train the network effectively, normalize your input data. Instead of using absolute prices, feed the network with differences, such as the gap between the Close and Open prices. This method provides normalized directional and size data that the network can process more efficiently.

A single candlestick can be represented by up to 12 neurons, capturing details like Open-Close and High-Open differences, Low-Open differences, tick volumes, and time components (e.g., month, hour, and day of the week). Technical indicators such as RSI, CCI, ATR, and MACD are also excellent inputs as they are pre-normalized and add context beyond a single candlestick.

For supervised learning, label your data by identifying patterns, such as fractals or the direction of the next candle (e.g., 1 for an upward move, -1 for a downward move). Split your historical data into training and testing sets, typically using a 70/30 ratio. Avoid shuffling the data to preserve the time-series sequence.

Since MQL5 does not support asynchronous calls, use the OnChartEvent function to trigger training. For instance, you can create a custom event like EventChartCustom to prevent the terminal from freezing when initializing a large network. This approach ensures smoother operation during the training process.

Optimizing Neural Network Expert Advisors

Once you've trained your neural network, the next step is optimization. This means fine-tuning the model to ensure it performs well not just in theory but also in live trading. This process involves backtesting, adjusting parameters, and deploying the model in live markets with careful monitoring.

Backtesting Neural Network Strategies

After building and training your neural network, backtesting is crucial to evaluate its performance on historical data. Tools like the MetaTrader 5 Strategy Tester are ideal for this. But instead of focusing solely on profit, use metrics like mean square error (MSE), root mean squared error (RMSE), and percentage of correct signal predictions to assess the model's effectiveness. A forecast accuracy of 70% or higher is often a good benchmark before moving to live testing.

To avoid overfitting - where the model performs well on past data but struggles in real markets - split your historical data into training and testing sets. A common practice is to use three years of data for training and one year for forward testing on unseen data. For more reliability, try time-series cross-validation with 5- or 10-fold splits. This ensures the model is tested on future data without leaking information from the training phase.

When optimizing strategies in the MetaTrader Strategy Tester, choose "Complex Criterion max" mode instead of "Maximum profit." This approach tends to produce more stable results for neural networks. Visual backtesting can also help you see how the network's signals align with actual market movements in real-time. For advanced models, consider training in Python and exporting to ONNX for seamless integration with MQL5.

Evaluation Method Primary Metric Purpose
In-Sample Testing Mean Square Error (MSE) Checks how well the network learned the data
Out-of-Sample Testing Forecast Accuracy % Tests predictive power on new data
Forward Testing Profit Factor / Drawdown Measures trading performance and risk
Cross-Validation Average RMSE Evaluates error across multiple time periods

Adjusting Parameters for Better Performance

Once backtesting confirms the model's viability, it's time to fine-tune its parameters for better stability and accuracy. Start with learning rate adjustments. A dynamic learning rate works well - raise it by 5% when errors decrease and lower it by 10% when errors spike to maintain balance. The Adam optimizer is a popular choice for online training because of its adaptability.

For smaller networks (fewer than 500 weights), the Levenberg-Marquardt (LM) algorithm is efficient. Larger networks, however, benefit from the L-BFGS algorithm, which handles deeper architectures more effectively.

Feature selection is another critical step. Use tools like Mutual Information or Random Forest importance to rank your inputs. Then, focus on the top-performing features to reduce noise and improve predictions. For prediction targets, using log returns instead of raw price changes can help stabilize variance and treat upward and downward moves equally. For example, a deep neural network strategy tested from 2022 to 2024 achieved 58.6% out-of-sample accuracy, a profit factor of 1.65, and a recovery factor of 13.48 with a 3:1 risk-to-reward ratio.

Running Neural Network EAs in Live Trading

Deploying your neural network in live trading is where the real challenge begins. Continuous monitoring and periodic re-optimization are essential because market conditions change frequently. Re-optimizing the model every six months is a common practice to maintain performance.

Advanced Expert Advisors (EAs) can even "self-optimize" by re-training at regular intervals - hourly, daily, or monthly - using the OnTimer() function. This allows the EA to adapt automatically without manual intervention. Keeping the same training normalization range for live data ensures consistency. If errors spike during live trading, immediately lower the learning rate to stabilize the model.

Instead of relying on a single set of optimized weights, consider combining the top 10–20 sets into a portfolio. This diversification reduces the risk of failure from any one model.

Platforms like Traidies (https://traidies.com) simplify the transition from development to live trading. They offer tools for generating MQL5 code, automated backtesting, and AI-powered strategy creation, making it easier to validate and deploy neural network strategies without extensive manual effort.

Advanced Neural Network Techniques for MQL5

Creating Custom Neural Network Architectures

When building custom neural network architectures in MQL5, dynamic matrices and vectors play a key role. While deep neural networks with multiple hidden layers are common, trading applications often find two layers sufficient. Networks with three or more hidden layers are rarely necessary in this domain.

To implement these networks, you can create a class like DeepNeuralNetwork to manage weight matrices (input-to-hidden, hidden-to-hidden, and hidden-to-output) and bias arrays. Using matrix operations ensures flexibility, allowing models to scale based on the number of inputs. For the output layer, the Softmax activation function is a popular choice. It generates decimal probabilities for multiple classes (e.g., Buy, Sell, Hold) that sum to 1.0, helping the model converge more efficiently during training.

Advanced methods like Transfer Learning can significantly speed up the development process. By reusing pre-trained layers from models such as autoencoders, you can save time when building strategies for new markets. Another approach is implementing Actor-Critic architectures, where the Actor proposes trading actions, and the Critic evaluates these actions to guide the Actor toward better profitability. Once trained, save the network parameters in binary (.bin) files for easy reuse across different Expert Advisors.

"All of the effort that previously went into feature design now goes into architecture design and loss function design and optimization scheme design. The manual labor has been raised to a higher level of abstraction." - Stefano Soatto

A real-world example highlights the potential of these techniques. In August 2025, developer Edmondlubangakene created a deep neural network breakout strategy for USD/JPY using H4 data from 2010–2021. The model incorporated 20 features, including Williams %R, MACD, and intermarket data from GBP/USD and XAU/USD. Backtesting from January 2022 to December 2024 showed impressive results: a $10,000 account grew to $152,824.69. Despite a win rate of only 41.48%, the system achieved a Profit Factor of 1.65 and a Sharpe Ratio of 8.61, thanks to a disciplined 3:1 risk-to-reward ratio.

This flexibility in architecture design allows developers to integrate technical indicators and refine predictions further.

Using Neural Networks with Technical Indicators

Combining neural networks with technical indicators enhances their predictive accuracy, especially when done thoughtfully. Indicators like RSI, CCI, and ATR are particularly useful because their naturally normalized values work well with activation functions. Instead of forecasting raw price movements, try predicting future indicator values. These values tend to be smoother and easier to model since they filter out much of the market noise.

To provide temporal context, feed the network data such as price differences (Open, High, Low, Close) and use a "moving window" of recent bars (typically 6–20 bars) for each indicator. Adding raw price data (OHLC), trading volume, and time-based factors (like the hour or day of the week) alongside oscillators can help the network identify seasonal patterns.

To ensure the network focuses on the most relevant inputs, apply statistical techniques like Mutual Information and Random Forest Importance to rank and select the most predictive indicators before training. Incorporating a batch normalization layer within the MQL5 model can also help by reducing variability between inputs, ensuring the output data has a near-zero mean and unit variance. For heavy mathematical computations, many MQL5 developers rely on the ALGLIB library for multilayer perceptrons or custom OpenCL-based libraries to handle deep learning tasks directly in MetaTrader 5.

By leveraging these techniques, neural networks can better adapt to the complexities of the financial markets.

Managing Files and Custom Libraries in MQL5

Efficient file and library management is essential for implementing advanced neural networks in MQL5. Save trained network weights and biases to external files (e.g., .nnw or .csv) to enable the system to recover its state after a terminal restart, avoiding the need for retraining. Using TERMINAL_COMMONDATA_PATH ensures that neural network data can be shared across multiple MetaTrader instances or even with external Python scripts using TensorFlow or Keras.

Encapsulate neural network logic within classes, such as CNeuralNetwork, to efficiently manage layers, deltas, and learning rates. To keep the network updated with market changes, use the OnTimer() function to schedule regular retraining, such as daily or weekly intervals. For optimization tasks across multiple CPU cores, implement a while loop with FileOpen checks to ensure that only one core writes to a shared optimization CSV file at any given time.

Training methods like the Levenberg-Marquardt algorithm or L-BFGS are commonly used. The latter is particularly effective for networks with over 500 weights, making it a preferred choice for more complex architectures.

These practices ensure that your neural network models remain reliable and efficient, even in demanding live trading environments.

Conclusion

Neural networks elevate MQL5 Expert Advisors from basic rule-based systems to sophisticated trading tools capable of analyzing multiple indicators at once. Instead of manually coding intricate conditions, neural networks make binary decisions instantly, streamlining the codebase while uncovering patterns that traditional methods might miss.

The results speak for themselves. In tests with the high-liquidity EURUSD pair, a self-learning EA utilizing a Markov state-transition matrix and a multilayer perceptron achieved a 66.7% annual return with an 11% drawdown between 2017 and 2025. Another system posted a 62.3% win rate and a Sharpe ratio of 1.65, demonstrating the effectiveness of these approaches.

"What is 'today' for NN is 'tomorrow' for us." - Andrey Dibrov

Staying ahead means keeping the network updated. Markets evolve, and a model trained six months ago might not align with current conditions. Regular retraining is crucial - whether every 48 hours for aggressive strategies or every six months for more conservative ones. Normalize inputs (e.g., 0 to 1 or –1 to 1) and take advantage of the MQL5 Matrix API for efficient batch computations.

Start with simpler architectures like basic multilayer perceptrons; they often perform as well as deeper networks while requiring less computational power. Once comfortable, explore hybrid strategies that combine neural networks with technical indicators or adaptive learning rates that respond to market volatility. Always test extensively, save optimized weights externally, and monitor live performance to ensure consistent results.

FAQs

What data should I feed a neural network EA in MQL5?

To train a neural network-based Expert Advisor (EA) in MQL5, start with well-organized data. This includes historical price data - such as open, high, low, and close prices - along with volume information and technical indicators like the Commodity Channel Index (CCI).

Data preparation is key. Before feeding the data into the neural network, ensure it's properly preprocessed. One crucial step is normalizing the data. Normalization helps eliminate biases and ensures the network learns effectively without being skewed by outliers or varying scales.

For the best results, use recent and relevant market data. Incorporating data from multiple timeframes can help the neural network identify meaningful patterns and adapt more effectively to market conditions, ultimately improving its trading performance.

How can I prevent overfitting when training on market history?

When training neural networks on market history, it's important to avoid overfitting - where a model learns patterns too specific to the training data and fails to perform well on new, unseen data. To tackle this, you can use regularization techniques to keep the model's complexity in check. This might include methods like dropout, weight decay, or limiting the number of parameters.

Another helpful strategy is to closely monitor the validation loss during training. If you notice the validation loss starts increasing while the training loss continues to decrease, it’s a sign of overfitting. In such cases, early stopping can be employed to stop training at the optimal point.

Additionally, analyzing the training history using a time series classifier can provide insights into when overfitting starts to occur. This dynamic approach ensures your model is better equipped to generalize to unseen market data, improving its real-world performance.

How often should I retrain a neural network EA for live trading?

The retraining schedule for a neural network Expert Advisor (EA) largely hinges on factors like market volatility, the stability of the trading environment, and how well the model is performing. It’s a good idea to retrain regularly - this could mean weekly, monthly, or whenever you notice a significant drop in performance. Regular updates help the model stay in tune with shifting market conditions, integrate fresh data, and maintain precision, which is especially critical in highly volatile markets. Keep a close eye on the model’s predictive accuracy to fine-tune the timing of retraining.

Related posts