Viewing the resource: Deep Neural Network Trading System in MQL5

Deep Neural Network Trading System in MQL5

Allan Munene Mutiiria 2025-06-25 19:57:01 125 Views
This article details the MQL5 code for the Deep Neural Network EA, automating trades using a neural ...

Introduction

Imagine forecasting market movements with the precision of an advanced predictive model, leveraging complex patterns to guide your trading decisions. The Deep Neural Network EA is your cutting-edge trading engine, designed to automate trades by processing candlestick patterns through a three-layer neural network ("DeepNeuralNetwork"). With 4 inputs ("numInput"=4), two hidden layers (4 and 5 nodes, "numHiddenA"=4, "numHiddenB"=5), and 3 outputs ("numOutput"=3), it analyzes the upper wick, lower wick, body size, and trend of the latest candle ("_XValues") to predict buy, sell, or hold signals. Confidence scores above 60% ("OUT[0]", "OUT[1]", "OUT[2]") trigger 0.01-lot trades ("Lot"=0.01) with "Trade_Object.Buy()", "Trade_Object.Sell()", or close positions ("Trade_Object.PositionClose()") using a unique magic number ("magic123"=123456). Opposite positions are closed to align with predictions, without stop losses or take profits. This high-risk EA suits traders embracing predictive models in volatile markets, requiring robust risk management.

This article is crafted with a professional, engaging, and seamless narrative, flowing like a well-calibrated predictive system, designed to inform and captivate readers. Tailored for both novice and experienced traders, we’ll dissect each code component with clear, precise explanations, as if guiding an apprentice analyst through a predictive trading project. With vivid examples—like trading EURUSD—and a polished tone, we’ll explore how the EA initializes, processes inputs, predicts signals, executes trades, and ensures cleanup. Using a precision predictive trading metaphor, this guide will illuminate the code’s technical rigor, empowering you to harness predictive trading with confidence. Let’s activate the system and begin this trading expedition!

Strategy Blueprint

Let’s outline the EA’s predictive framework, like drafting specifications for a forecasting system:

  • Input Processing: Extracts 4 inputs from the latest candle ("_XValues"): upper wick, lower wick, body size, and trend, using "candlePatterns()", "CopyRates()".

  • Neural Network Prediction: Feeds inputs through a 4-4-5-3 neural network ("DeepNeuralNetwork") with weights ("weightsTotal") and biases, outputting buy, sell, or hold confidences ("OUT") via "ComputeOutputs()".

  • Trade Execution: Opens 0.01-lot buys ("Trade_Object.Buy()") if buy confidence exceeds 60% ("OUT[0] > 0.6"), sells for sell confidence ("OUT[1] > 0.6"), or closes positions for hold ("OUT[2] > 0.6"), using "PositionClose()".

  • Position Management: Closes opposite positions ("Positions_Object") to align with predictions, tracked by "magic123"=123456.

  • Execution: Processes signals on each tick ("OnTick()") without risk controls.

  • Enhancements: Adding stop losses or dynamic weights could improve safety and accuracy. This framework automates predictive trading with precision, leveraging neural networks for data-driven decisions.

Code Implementation

Let’s step into the predictive control room and dissect the MQL5 code that powers this Deep Neural Network EA. We’ll guide you through each phase like expert analysts, ensuring the narrative flows seamlessly with professional clarity and engaging precision that captivates readers. We’ll cover initialization, input preparation, neural network prediction, trade execution, and cleanup, with detailed explanations and examples—like trading EURUSD—to make it accessible for beginners. Each phase will build on the last, crafting a cohesive technical narrative that transforms code into a compelling predictive project. Let’s power up the system and begin!

Phase 1: Constructing the Framework—Initialization

We start by building the predictive system, initializing the neural network and trading settings.

//+------------------------------------------------------------------+
//|                                      Our DEEP NEURAL NETWORK.mq5 |
//|                           Copyright 2025, Allan Munene Mutiiria. |
//|                                   https://t.me/Forex_Algo_Trader |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Allan Munene Mutiiria."
#property link      "https://t.me/Forex_Algo_Trader"
#property version   "1.00"
#property strict

#define SIZEI 4
#define SIZEA 5
#define SIZEB 3

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
CTrade Trade_Object;
CPositionInfo Positions_Object;

int numInput = 4;
int numHiddenA = 4;
int numHiddenB = 5;
int numOutput = 3;
DeepNeuralNetwork dnn(numInput,numHiddenA,numHiddenB,numOutput);

input double w_i_0 = 1;
// ... (other weight inputs)
input double Lot = 0.01;
input long magic123 = 123456;

double _XValues[4];
double weightsTotal[63];
double OUT[];
string Our_Symbol;
ENUM_TIMEFRAMES Our_Tf;
double Our_Volume;

int OnInit(){
   Our_Symbol = Symbol();
   Our_Tf = PERIOD_CURRENT;
   Our_Volume = Lot;
   Trade_Object.SetExpertMagicNumber(magic123);
   weightsTotal[0] = w_i_0;
   // ... (other weight assignments)
   return(INIT_SUCCEEDED);
}

The system begins with the #property header, setting copyright and contact details, like calibrating a predictive engine’s core. The "OnInit()" function initializes the setup, including "Trade\Trade.mqh" and "Trade\PositionInfo.mqh" for trading ("Trade_Object", "Positions_Object"). It defines the neural network ("DeepNeuralNetwork", "numInput"=4, "numHiddenA"=4, "numHiddenB"=5, "numOutput"=3) and sets trading parameters ("Our_Symbol", "Our_Tf", "Our_Volume"=0.01, "magic123"=123456) with "SetExpertMagicNumber()". Weights ("weightsTotal", 63 elements) are assigned from inputs ("w_i_0", etc.), like tuning the model. Returning INIT_SUCCEEDED signals, “System is ready, let’s predict!” This primes the EA for neural network trading, like a forecasting tool poised for action.

Phase 2: Preparing Inputs—Analyzing Candlestick Patterns

With the system active, we extract candlestick features as inputs, like gathering data for a predictive model.

void OnTick(){
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int copiedRatesData = CopyRates(_Symbol,PERIOD_CURRENT,1,5,rates);
   int err_CandleStickValue = candlePatterns(rates[0].high,rates[0].low,rates[0].open,rates[0].close,
                              rates[0].close - rates[0].open,_XValues);
   if (err_CandleStickValue < 0) return;
}

int candlePatterns(double high, double low, double open, double close, double barSize, double &XInputs[]){
   double barsize100per = high - low;
   double higherPer = 0;
   double lowerPer = 0;
   double bodyPer = 0;
   double trend = 0;
   if (barSize > 0){
      higherPer = high - close;
      lowerPer = open - low;
      bodyPer = close - open;
      trend = 1;
   }
   else {
      higherPer = high - open;
      lowerPer = close - low;
      bodyPer = open - close;
      trend = 0;
   }
   if (barsize100per == 0) return(-1);
   XInputs[0] = higherPer/barsize100per;
   XInputs[1] = lowerPer/barsize100per;
   XInputs[2] = bodyPer/barsize100per;
   XInputs[3] = trend;
   return(1);
}

In the input preparation hub, "OnTick()" fetches 5 bars of price data ("CopyRates()", "MqlRates", "ArraySetAsSeries()") and processes the latest candle with "candlePatterns()". This function calculates four inputs ("_XValues") as percentages of the candle’s range ("high - low"): upper wick ("higherPer"), lower wick ("lowerPer"), body ("bodyPer"), and trend ("trend"=1 for bullish, 0 for bearish), returning -1 if the range is zero. For example, on EURUSD M5, a candle (open=1.2000, high=1.2010, low=1.1990, close=1.2005) yields _XValues[0]=0.25 (upper wick), _XValues[1]=0.25 (lower wick), _XValues[2]=0.25 (body), _XValues[3]=1 (bullish), like feeding data into a predictive model.

Phase 3: Forecasting Signals—Neural Network Prediction

With inputs prepared, we predict signals using the neural network, like generating forecasts from a model.

class DeepNeuralNetwork{
   private: int numInput; int numHiddenA; int numHiddenB; int numOutput;
            double inputs[]; double iaWeights[][SIZEI]; double abWeights[][SIZEA];
            double boWeights[][SIZEB]; double aBiases[]; double bBiases[]; double oBiases[];
            double aOutputs[]; double bOutputs[]; double outputs[];
   public: DeepNeuralNetwork(int _numInput,int _numHiddenA,int _numHiddenB,int _numOutput){
               this.numInput = _numInput; this.numHiddenA = _numHiddenA;
               this.numHiddenB = _numHiddenB; this.numOutput = _numOutput;
               ArrayResize(inputs,numInput); ArrayResize(iaWeights,numInput);
               ArrayResize(abWeights,numHiddenA); ArrayResize(boWeights,numHiddenB);
               ArrayResize(aBiases,numHiddenA); ArrayResize(bBiases,numHiddenB);
               ArrayResize(oBiases,numOutput); ArrayResize(aOutputs,numHiddenA);
               ArrayResize(bOutputs,numHiddenB); ArrayResize(outputs,numOutput);
           }
           void SetWeights(double &weights[]){
               int numTotalWeights_Biases = ((numInput*numHiddenA)+numHiddenA+(numHiddenA*numHiddenB)+
                                             numHiddenB + (numHiddenB*numOutput) + numOutput);
               if (ArraySize(weights) != numTotalWeights_Biases){
                  Print("We have not enought weights to work with");
                  return;
               }
               int k = 0;
               for (int i = 0; i < numInput; ++i)
                  for (int j = 0; j < numHiddenA; ++j)
                     iaWeights[i][j] = NormalizeDouble(weights[k++],2);
               for (int i = 0; i < numHiddenA; ++i)
                  aBiases[i] = NormalizeDouble(weights[k++],2);
               for (int i = 0; i < numHiddenA; ++i)
                  for (int j = 0; j < numHiddenB; ++j)
                     abWeights[i][j] = NormalizeDouble(weights[k++],2);
               for (int i = 0; i < numHiddenB; ++i)
                  bBiases[i] = NormalizeDouble(weights[k++],2);
               for (int i = 0; i < numHiddenB; ++i)
                  for (int j = 0; j < numOutput; ++j)
                     boWeights[i][j] = NormalizeDouble(weights[k++],2);
               for (int i = 0; i < numOutput; ++i)
                  oBiases[i] = NormalizeDouble(weights[k++],2);
           }
           void ComputeOutputs(double &xValues[],double &yValues[]){
               double aSums[]; double bSums[]; double oSums[];
               ArrayResize(aSums,numHiddenA); ArrayFill(aSums,0,numHiddenA,0);
               ArrayResize(bSums,numHiddenB); ArrayFill(bSums,0,numHiddenB,0);
               ArrayResize(oSums,numOutput); ArrayFill(oSums,0,numOutput,0);
               int size = ArraySize(xValues);
               for (int i = 0; i < size; ++i) this.inputs[i] = xValues[i];
               for (int j = 0; j < numHiddenA; ++j)
                  for (int i = 0; i < numInput; ++i)
                     aSums[j] += this.inputs[i]*this.iaWeights[i][j];
               for (int i = 0; i < numHiddenA; ++i) aSums[i] += this.aBiases[i];
               for (int i = 0; i < numHiddenA; ++i)
                  this.aOutputs[i] = HyperTanhFunction(aSums[i]);
               for (int j = 0; j < numHiddenB; ++j)
                  for (int i = 0; i < numHiddenA; ++i)
                     bSums[j] += this.aOutputs[i]*this.abWeights[i][j];
               for (int i = 0; i < numHiddenB; ++i) bSums[i] += this.bBiases[i];
               for (int i = 0; i < numHiddenB; ++i)
                  this.bOutputs[i] = HyperTanhFunction(bSums[i]);
               for (int j = 0; j < numOutput; ++j)
                  for (int i = 0; i < numHiddenB; ++i)
                     oSums[j] += this.bOutputs[i]*this.boWeights[i][j];
               for (int i = 0; i < numOutput; ++i) oSums[i] += this.oBiases[i];
               double softOut[];
               SoftMax(oSums,softOut);
               ArrayCopy(outputs,softOut);
               ArrayCopy(yValues,outputs);
           }
           double HyperTanhFunction(double x){
               if (x < -20.0) return -1.0;
               else if (x > 20) return 1.0;
               else return (1-exp(-2*x)/1+exp(-2*x));
           }
           void SoftMax(double &oSums[], double &_softOut[]){
               double max = oSums[0];
               for (int i = 0; i < ArraySize(oSums); ++i)
                  if (oSums[i] > max) max = oSums[i];
               double scale = 0.0;
               for (int i = 0; i < ArraySize(oSums); ++i)
                  scale += MathExp(oSums[i]-max);
               ArrayResize(_softOut,ArraySize(oSums));
               for (int i = 0; i < ArraySize(oSums); ++i)
                  _softOut[i] = MathExp(oSums[i]-max)/scale;
           }
};

void OnTick(){
   // ... (input preparation)
   dnn.SetWeights(weightsTotal);
   dnn.ComputeOutputs(_XValues,OUT);
   Print(OUT[0]);
}

In the forecasting hub, "OnTick()" sets neural network weights with "SetWeights()", assigning "weightsTotal" (63 weights/biases) to "iaWeights", "abWeights", "boWeights", "aBiases", "bBiases", "oBiases" using "NormalizeDouble()". The "ComputeOutputs()" function processes "_XValues" through the network: input to hidden layer A ("iaWeights", "aBiases", "HyperTanhFunction()", "aOutputs"), hidden A to B ("abWeights", "bBiases", "bOutputs"), and hidden B to output ("boWeights", "oBiases", "SoftMax()", "outputs"). The "HyperTanhFunction()" activates hidden layers, and "SoftMax()" normalizes outputs ("OUT", 3 values: buy, sell, hold). For example, on EURUSD, inputs _XValues=[0.25,0.25,0.25,1] yield OUT=[0.7,0.2,0.1], predicting a buy with 70% confidence, like a model forecasting a trend.

Phase 4: Executing Trades—Acting on Predictions

With signals predicted, we execute trades based on confidence scores, like acting on a model’s forecasts.

void OnTick(){
   // ... (prediction)
   if (OUT[0] > 0.6){
      if (Positions_Object.Select(Our_Symbol)){
         if (Positions_Object.PositionType()==POSITION_TYPE_SELL)
            Trade_Object.PositionClose(Our_Symbol);
         if (Positions_Object.PositionType()==POSITION_TYPE_BUY) return;
      }
      Trade_Object.Buy(Our_Volume,Our_Symbol);
   }
   if (OUT[1] > 0.6){
      if (Positions_Object.Select(Our_Symbol)){
         if (Positions_Object.PositionType()==POSITION_TYPE_BUY)
            Trade_Object.PositionClose(Our_Symbol);
         if (Positions_Object.PositionType()==POSITION_TYPE_SELL) return;
      }
      Trade_Object.Sell(Our_Volume,Our_Symbol);
   }
   if (OUT[2] > 0.6){
      Trade_Object.PositionClose(Our_Symbol);
   }
}

In the trade execution hub, "OnTick()" checks "OUT". If buy confidence exceeds 60% ("OUT[0] > 0.6"), it closes sells ("Positions_Object.Select()", "PositionClose()") and opens a 0.01-lot buy ("Trade_Object.Buy()", "Our_Volume"=0.01) unless a buy exists. If sell confidence is above 60% ("OUT[1] > 0.6"), it closes buys and opens a sell. A hold signal ("OUT[2] > 0.6") closes all positions. For example, on EURUSD, OUT=[0.7,0.2,0.1] triggers a buy at 1.2007, closing any sell, like executing a predictive trade signal.

Phase 5: Shutting Down the System—Cleaning Up Resources

As our expedition concludes, we shut down the system, ensuring resources are cleared.

void OnDeinit(const int reason){
}

In the shutdown control room, "OnDeinit()" is empty, leaving no cleanup, like an active predictive model. Adding cleanup would ensure a clean slate:

ArrayFree(_XValues);
ArrayFree(weightsTotal);
ArrayFree(OUT);

This would free arrays ("_XValues", "weightsTotal", "OUT") with "ArrayFree()", like archiving a forecasting system, ready for the next task.

Why This EA is a Predictive Triumph

The Deep Neural Network EA is a predictive trading triumph, automating trades with precision, like a master-crafted forecasting engine. Its neural network ("DeepNeuralNetwork", "ComputeOutputs()") and candlestick inputs ("candlePatterns()") offer data-driven signals, with potential for stop losses or dynamic weights. Picture a buy on EURUSD at 1.2007 with 70% confidence—strategic brilliance! Beginners will value the clear predictions, while experts can refine its model, making it essential for predictive traders.

Putting It All Together

To deploy this EA:

  1. Open MetaEditor in MetaTrader 5, like entering your predictive control room.

  2. Copy the code, compile with F5, and verify no errors—no analyst wants a faulty model!

  3. Attach the EA to your chart, enable AutoTrading, and watch it execute neural network trades.

  4. Monitor logs (e.g., “We have not enought weights to work with”) for signal tracking, like predictive diagnostics.

  5. Test on a demo account first—real capital deserves a trial run!

Conclusion

We’ve engineered a Deep Neural Network Trader that automates predictive trading with precision, like a master-crafted forecasting system. This MQL5 code is your strategic tool, brought to life with a seamless, professional narrative packed with clear explanations and vivid examples to fuel your trading ambition. Whether you’re a novice analyst or a seasoned market strategist, this EA empowers you to predict trends with confidence. Ready to forecast? Watch our video guide on the website for a step-by-step creation process. Now, shape your trading future with precision! 🔍

Disclaimer: Trading is like navigating complex markets—challenging and risky. Losses can exceed deposits. Test strategies on a demo account before going live.

Disclaimer: The ideas and strategies presented in this resource are solely those of the author and are intended for informational and educational purposes only. They do not constitute financial advice, and past performance is not indicative of future results. All materials, including but not limited to text, images, files, and any downloadable content, are protected by copyright and intellectual property laws and are the exclusive property of Forex Algo-Trader or its licensors. Reproduction, distribution, modification, or commercial use of these materials without prior written consent from Forex Algo-Trader is strictly prohibited and may result in legal action. Users are advised to exercise extreme caution, perform thorough independent research, and consult with qualified financial professionals before implementing any trading strategies or decisions based on this resource, as trading in financial markets involves significant risk of loss.

Recent Comments

Go to discussion to Comment or View other Comments

No comments yet. Be the first to comment!