This what i need help with
-
//+------------------------------------------------------------------+
//| neuro-example.mq5 |
//| Copyright 2012, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh> //include the library for execution of trades
#include <Trade\PositionInfo.mqh> //include the library for obtaining information on positions//--- weight values
input double w0=0.5;
input double w1=0.5;
input double w2=0.5;
input double w3=0.5;
input double w4=0.5;
input double w5=0.5;
input double w6=0.5;
input double w7=0.5;
input double w8=0.5;
input double w9=0.5;int iRSI_handle; // variable for storing the indicator handle
double iRSI_buf[]; // dynamic array for storing indicator valuesdouble inputs[10]; // array for storing inputs
double weight[10]; // array for storing weightsdouble out; // variable for storing the output of the neuron
string my_symbol; // variable for storing the symbol
ENUM_TIMEFRAMES my_timeframe; // variable for storing the time frame
double lot_size; // variable for storing the minimum lot size of the transaction to be performedCTrade m_Trade; // entity for execution of trades
CPositionInfo m_Position; // entity for obtaining information on positions
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int OnInit()
{
//--- save the current chart symbol for further operation of the EA on this very symbol
my_symbol=Symbol();
//--- save the current time frame of the chart for further operation of the EA on this very time frame
my_timeframe=PERIOD_CURRENT;
//--- save the minimum lot of the transaction to be performed
lot_size=SymbolInfoDouble(my_symbol,SYMBOL_VOLUME_MIN);
//--- apply the indicator and get its handle
iRSI_handle=iRSI(my_symbol,my_timeframe,14,PRICE_CLOSE);
//--- check the availability of the indicator handle
if(iRSI_handle==INVALID_HANDLE)
{
//--- no handle obtained, print the error message into the log file, complete handling the error
Print("Failed to get the indicator handle");
return(-1);
}
//--- add the indicator to the price chart
ChartIndicatorAdd(ChartID(),0,iRSI_handle);
//--- set the iRSI_buf array indexing as time series
ArraySetAsSeries(iRSI_buf,true);
//--- place weights into the array
weight[0]=w0;
weight[1]=w1;
weight[2]=w2;
weight[3]=w3;
weight[4]=w4;
weight[5]=w5;
weight[6]=w6;
weight[7]=w7;
weight[8]=w8;
weight[9]=w9;
//--- return 0, initialization complete
return(0);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- delete the indicator handle and deallocate the memory space it occupies
IndicatorRelease(iRSI_handle);
//--- free the iRSI_buf dynamic array of data
ArrayFree(iRSI_buf);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- variable for storing the results of working with the indicator buffer
int err1=0;
//--- copy data from the indicator array to the iRSI_buf dynamic array for further work with them
err1=CopyBuffer(iRSI_handle,0,1,10,iRSI_buf);
//--- in case of errors, print the relevant error message into the log file and exit the function
if(err1<0)
{
Print("Failed to copy data from the indicator buffer");
return;
}
//---
double d1=0.0; //lower limit of the normalization range
double d2=1.0; //upper limit of the normalization range
double x_min=iRSI_buf[ArrayMinimum(iRSI_buf)]; //minimum value over the range
double x_max=iRSI_buf[ArrayMaximum(iRSI_buf)]; //maximum value over the range//--- In the loop, fill in the array of inputs with the pre-normalized indicator values
for(int i=0;i<ArraySize(inputs);i++)
{
inputs[i]=(((iRSI_buf[i]-x_min)*(d2-d1))/(x_max-x_min))+d1;
}
//--- store the neuron calculation result in the out variable
out=CalculateNeuron(inputs,weight);
//--- if the output value of the neuron is less than 0.5
if(out<0.5)
{
//--- if the position for this symbol already exists
if(m_Position.Select(my_symbol))
{
//--- and this is a Sell position, then close it
if(m_Position.PositionType()==POSITION_TYPE_SELL) m_Trade.PositionClose(my_symbol);
//--- or else, if this is a Buy position, then exit
if(m_Position.PositionType()==POSITION_TYPE_BUY) return;
}
//--- if we got here, it means there is no position; then we open it
m_Trade.Buy(lot_size,my_symbol);
}
//--- if the output value of the neuron is equal to or greater than 0.5
if(out>=0.5)
{
//--- if the position for this symbol already exists
if(m_Position.Select(my_symbol))
{
//--- and this is a Buy position, then close it
if(m_Position.PositionType()==POSITION_TYPE_BUY) m_Trade.PositionClose(my_symbol);
//--- or else, if this is a Sell position, then exit
if(m_Position.PositionType()==POSITION_TYPE_SELL) return;
}
//--- if we got here, it means there is no position; then we open it
m_Trade.Sell(lot_size,my_symbol);
}
}
//+------------------------------------------------------------------+
//| Neuron calculation function |
//+------------------------------------------------------------------+
double CalculateNeuron(double &x[],double &w[])
{
//--- variable for storing the weighted sum of inputs
double NET=0.0;
//--- Using a loop we obtain the weighted sum of inputs based on the number of inputs
for(int n=0;n<ArraySize(x);n++)
{
NET+=x[n]w[n];
}
//--- multiply the weighted sum of inputs by the additional coefficient
NET=0.4;
//--- send the weighted sum of inputs to the activation function and return its value
return(ActivateNeuron(NET));
}
//+------------------------------------------------------------------+
//| Activation function |
//+------------------------------------------------------------------+
double ActivateNeuron(double x)
{
//--- variable for storing the activation function results
double Out;
//--- sigmoid
Out=1/(1+exp(-x));
//--- return the activation function value
return(Out);
} -
All i want is to add sl and tp and trading times to be conected with this strategy
-
This is a machine that gathers all the info from history and places a trade Neural Network
-
and i need to have sl&tp and trading times that i decide,cause without those it only places a trade but without guidance
-
I hope someone understands what i mean, its not a indicator that places a trade based of candle id or cross over or below is a strategy that gathers info and i need to have control and i ask if someone can code and i pay
-
@Domas1988 Only add TP or SL system ?
-
@Domas1988 Sir i have added take profit and stop loss in it but tell me how it works ?
-
@Domas1988 Here is the source code of Gup and I have added take profit and stop Loss 1.mq5

-
@ItzShahzad-X ```
//+------------------------------------------------------------------+
//| neuro-example.mq5 |
//| Copyright 2012, MetaQuotes Software Corp. |
//| http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MetaQuotes Software Corp."
#property link "http://www.mql5.com"
#property version "1.02"#include <Trade\Trade.mqh> // Include the library for trade execution
#include <Trade\PositionInfo.mqh> // Include the library for position info//--- Input parameters
input double w0 = 0.5; // Weight 0
input double w1 = 0.5; // Weight 1
input double w2 = 0.5; // Weight 2
input double w3 = 0.5; // Weight 3
input double w4 = 0.5; // Weight 4
input double w5 = 0.5; // Weight 5
input double w6 = 0.5; // Weight 6
input double w7 = 0.5; // Weight 7
input double w8 = 0.5; // Weight 8
input double w9 = 0.5; // Weight 9input double TakeProfit = 50; // Take Profit in pips
input double StopLoss = 50; // Stop Loss in pips//--- Variables
int iRSI_handle; // RSI indicator handle
double iRSI_buf[10]; // Buffer for RSI valuesdouble inputs[10]; // Array for normalized inputs
double weight[10]; // Array for weightsdouble out; // Output of the neuron
string my_symbol; // Trading symbol
ENUM_TIMEFRAMES my_timeframe; // Timeframe
double lot_size; // Lot size for tradesCTrade m_Trade; // Trade object
CPositionInfo m_Position; // Position info object//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
my_symbol = Symbol(); // Current chart symbol
my_timeframe = PERIOD_CURRENT; // Current timeframe
lot_size = SymbolInfoDouble(my_symbol, SYMBOL_VOLUME_MIN); // Minimum lot size// Apply RSI indicator iRSI_handle = iRSI(my_symbol, my_timeframe, 14, PRICE_CLOSE); // Check if RSI handle is valid if (iRSI_handle == INVALID_HANDLE) { Print("Failed to get the indicator handle, Error: ", GetLastError()); return INIT_FAILED; } // Add RSI indicator to chart and set buffer as time series ChartIndicatorAdd(ChartID(), 0, iRSI_handle); ArraySetAsSeries(iRSI_buf, true); // Initialize weights weight[0] = w0; weight[1] = w1; weight[2] = w2; weight[3] = w3; weight[4] = w4; weight[5] = w5; weight[6] = w6; weight[7] = w7; weight[8] = w8; weight[9] = w9; return INIT_SUCCEEDED;}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
IndicatorRelease(iRSI_handle); // Release RSI handle
// No dynamic memory to free for iRSI_buf
}//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Copy latest 10 RSI values into the buffer
if (CopyBuffer(iRSI_handle, 0, 0, 10, iRSI_buf) <= 0)
{
Print("Failed to copy data from the indicator buffer, Error: ", GetLastError());
return;
}double d1 = 0.0, d2 = 1.0; double x_min = iRSI_buf[ArrayMinimum(iRSI_buf)]; double x_max = iRSI_buf[ArrayMaximum(iRSI_buf)]; // Normalize RSI values for (int i = 0; i < ArraySize(inputs); i++) { inputs[i] = (((iRSI_buf[i] - x_min) * (d2 - d1)) / (x_max - x_min)) + d1; } out = CalculateNeuron(inputs, weight); // Calculate neuron output double currentPrice = SymbolInfoDouble(my_symbol, SYMBOL_BID); double tpPrice, slPrice; if (out < 0.5) { // Close any existing Sell position if (m_Position.Select(my_symbol)) { if (m_Position.PositionType() == POSITION_TYPE_SELL) m_Trade.PositionClose(my_symbol); if (m_Position.PositionType() == POSITION_TYPE_BUY) return; // Do nothing if a Buy position exists } // Buy setup tpPrice = currentPrice + (TakeProfit * _Point); slPrice = currentPrice - (StopLoss * _Point); m_Trade.Buy(lot_size, my_symbol, slPrice, tpPrice); } else if (out >= 0.5) { // Close any existing Buy position if (m_Position.Select(my_symbol)) { if (m_Position.PositionType() == POSITION_TYPE_BUY) m_Trade.PositionClose(my_symbol); if (m_Position.PositionType() == POSITION_TYPE_SELL) return; // Do nothing if a Sell position exists } // Sell setup tpPrice = currentPrice - (TakeProfit * _Point); slPrice = currentPrice + (StopLoss * _Point); m_Trade.Sell(lot_size, my_symbol, slPrice, tpPrice); }}
//+------------------------------------------------------------------+
//| Neuron calculation function |
//+------------------------------------------------------------------+
double CalculateNeuron(double &x[], double &w[])
{
double NET = 0.0;
for (int n = 0; n < ArraySize(x); n++)
{
NET += x[n] * w[n]; // Calculate weighted sum
}return ActivateNeuron(NET); // Activation function}
//+------------------------------------------------------------------+
//| Activation function |
//+------------------------------------------------------------------+
double ActivateNeuron(double x)
{
return 1.0 / (1.0 + exp(-x)); // Sigmoid function
} -
@ItzShahzad-X thanks for trying it does not not work tester shows 0.00 on all pairs i will try on live
-
That is the problem that i tried to resolve SL/TP and trading times to be incorporated with that source, i have no idea what code do i need for add this,i put that indicator to my fxdreema but whatever i do is always show 0.00 on all pairs if i use a natural source it shows the trades and drawdowns and actually the drawdown is really low as it a neural network it knows all, just a control isn't not functional and that is important i see that mql5 somehow have a control over it so i was really amazed about it, and brought he source to modify as i say i pay for it if someone can actually help me out
-
@Domas1988 Sir I have invested a lot of time in your project but I have not found any error in it, I have tried a lot but can't find the error. If you like it, you can share the strategy with me so that I can Code again
-
Do you tested?
-
You can use the source that i shared if you can manage to incorporate those settings that it needs
-
@Domas1988 yes
-
@Domas1988 Sir, your point is fine, but tell us what strategy we should use
-
Brief theory of Neural Networks:
Neural network is an adjustable model of outputs as functions of inputs. It consists of several layers:
input layer, which consists of input data
hidden layer, which consists of processing nodes called neurons
output layer, which consists of one or several neurons, whose outputs are the network outputs.
All nodes of adjacent layers are interconnected. These connections are called synapses. Every synapse has an assigned scaling coefficient, by which the data propagated through the synapse is multiplied. These scaling coefficient are called weights (w[i][j][k]). In a Feed-Forward Neural Network (FFNN) the data is propagated from inputs to the outputs. Here is an example of FFNN with one input layer, one output layer and two hidden layers:The topology of a FFNN is often abbreviated as follows: <# of inputs> - <# of neurons in the first hidden layer> - <# of neurons in the second hidden layer> -...- <# of outputs>. The above network can be referred to as a 4-3-3-1 network.
The data is processed by neurons in two steps, correspondingly shown within the circle by a summation sign and a step sign:
All inputs are multiplied by the associated weights and summed
The resulting sums are processed by the neuron's activation function, whose output is the neuron output.
It is the neuron's activation function that gives nonlinearity to the neural network model. Without it, there is no reason to have hidden layers, and the neural network becomes a linear autoregressive (AR) model.Enclosed library files for NN functions allow selection between three activation functions:
sigmoid sigm(x)=1/(1+exp(-x)) (#0)
hyperbolic tangent tanh(x)=(1-exp(-2x))/(1+exp(-2x)) (#1)
rational function x/(1+|x|) (#2)The activation threshold of these functions is x=0. This threshold can be moved along the x axis thanks to an additional input of each neuron, called the bias input, which also has a weight assigned to it.
The number of inputs, outputs, hidden layers, neurons in these layers, and the values of the synapse weights completely describe a FFNN, i.e. the nonlinear model that it creates. In order to find weights the network must be trained. During a supervised training, several sets of past inputs and the corresponding expected outputs are fed to the network. The weights are optimized to achieve the smallest error between the network outputs and the expected outputs. The simplest method of weight optimization is the back-propagation of errors, which is a gradient descent method. The enclosed training function Train() uses a variant of this method, called Improved Resilient back-Propagation Plus (iRProp+). This method is described here
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.1332
The main disadvantage of gradient-based optimization methods is that they often find a local minimum. For chaotic series such as a price series, the training error surface has a very complex shape with lots of local minima. For such series, a genetic algorithm is a preferred training method.
Enclosed files:
BPNN.dll - library file
BPNN.zip - archive of all files needed to compile BPNN.dll in C++
BPNN Predictor.mq4 - indicator predicting future open prices
BPNN Predictor with Smoothing.mq4 - indicator predicting smoothed open prices
File BPNN.cpp has two functions: Train() и Test(). Train() is used to train the network based on supplied past input and expected output values. Test() is used to compute the network outputs using optimized weights, found by Train().Here is the list of input (green) и output (blue) parameters of Train():
double inpTrain[] - Input training data (1D array carrying 2D data, old first)
double outTarget[] - Output target data for training (2D data as 1D array, oldest 1st)
double outTrain[] - Output 1D array to hold net outputs from training
int ntr - # of training sets
int UEW - Use Ext. Weights for initialization (1=use extInitWt, 0=use rnd)
double extInitWt[] - Input 1D array to hold 3D array of external initial weights
double trainedWt[] - Output 1D array to hold 3D array of trained weights
int numLayers - # of layers including input, hidden and output
int lSz[] - # of neurons in layers. lSz[0] is # of net inputs
int AFT - Type of neuron activation function (0:sigm, 1:tanh, 2:x/(1+x))
int OAF - 1 enables activation function for output layer; 0 disables
int nep - Max # of training epochs
double maxMSE - Max MSE; training stops once maxMSE is reached.Here is the list of input (green) и output (blue) parameters of Test():
double inpTest[] - Input test data (2D data as 1D array, oldest first)
double outTest[] - Output 1D array to hold net outputs from training (oldest first)
int ntt - # of test sets
double extInitWt[] - Input 1D array to hold 3D array of external initial weights
int numLayers - # of layers including input, hidden and output
int lSz[] - # of neurons in layers. lSz[0] is # of net inputs
int AFT - Type of neuron activation function (0:sigm, 1:tanh, 2:x/(1+x))
int OAF - 1 enables activation function for output layer; 0 disablesWhether to use the activation function in the output layer or not (OAF parameter value) depends on the nature of outputs. If outputs are binary, which is often the case in classification problems, then the activation function should be used in the output layer (OAF=1). Please, pay attention that the activation function #0 (sigmoid) has 0 and 1 saturated levels whereas the activation functions #1 and 2 have -1 and 1 levels. If the network outputs is a price prediction, then no activation function is needed in the output layer (OAF=0).
Examples of using the NN library:
BPNN Predictor.mq4 - predicts future open prices. The inputs of the network are relative price changes:x[i]=Open[test_bar]/Open[test_bar+delay[i]]-1.0
where delay[i] is computed as a Fibonacci number (1,2,3,5,8,13,21..). The output of the network is the predicted relative change of the next price. The activation function is turned off in the output layer (OAF=0).
Indicator inputs:
extern int lastBar - Last bar in the past data
extern int futBars - # of future bars to predict
extern int numLayers - # of layers including input, hidden & output (2..6)
extern int numInputs - # of inputs
extern int numNeurons1 - # of neurons in the first hidden or output layer
extern int numNeurons2 - # of neurons in the second hidden or output layer
extern int numNeurons3 - # of neurons in the third hidden or output layer
extern int numNeurons4 - # of neurons in the fourth hidden or output layer
extern int numNeurons5 - # of neurons in the fifth hidden or output layer
extern int ntr - # of training sets
extern int nep - Max # of epochs
extern int maxMSEpwr - sets maxMSE=10^maxMSEpwr; training stops < maxMSE
extern int AFT - Type of activ. function (0:sigm, 1:tanh, 2:x/(1+x))The indicator plots three curves on the chart:
red color - predictions of future prices
black color - past training open prices, which were used as expected outputs for the network
blue color - network outputs for training inputsBPNN Predictor.mq4 - predicts future smoothed open prices. It uses EMA smoothing with period smoothPer.
Setting all up:
Copy enclosed BPNN.DLL to C:\Program Files\MetaTrader 4\experts\libraries
In metatrader: Tools - Options - Expert Advisors - Allow DLL imports
You can also compile your own DLL file using source codes in BPNN.zip.Recommendations:
A network with three layers (numLayers=3: one input, one hidden and one output) is enough for a vast majority of cases. According to the Cybenko Theorem (1989), a network with one hidden layer is capable of approximating any continuous, multivariate function to any desired degree of accuracy; a network with two hidden layers is capable of approximating any discontinuous, multivariate function:
The optimum number of neurons in the hidden layer can be found through trial and error. The following "rules of thumb" can be found in the literature: # of hidden neurons = (# of inputs + # of outputs)/2, or SQRT(# of inputs * # of outputs). Keep track of the training error, reported by the indicator in the experts window of metatrader.
For generalization, the number of training sets (ntr) should be chosen 2-5 times the total number of the weights in the network. For example, by default, BPNN Predictor.mq4 uses a 12-5-1 network. The total number of weights is (12+1)5+6=71. Therefore, the number of training sets (ntr) should be at least 142. The concept of generalization and memorization (over-fitting) is explained on the graph below.
The input data to the network should be transformed to stationary. Forex prices are not stationary. It is also recommended to normalize the inputs to -1..+1 range.
The graph below shows a linear function y=bx (x-input, y-output) whose outputs are corrupted by noise. This added noise causes the function measured outputs (black dots) to deviate from a straight line. Function y=f(x) can be modeled by a feed forward neural network. The network with a large number of weights can be fitted to the measured data with zero error. Its behavior is shown as the red curve passing through all black dots. However, this red curve has nothing to do with the original linear function y=b*x (green). When this over-fitted network is used to predict future values of function y(x), it will result in large errors due to randomness of the added noise.