Watch how to download trading robots for free

Interesting script?
So post a link to it -
let others appraise it

You liked the script? Try it in the MetaTrader 5 terminal


Stochastic Net - library for MetaTrader 4

Denis | English 日本語 Русский 中文 Español Deutsch Português

votes: 7
2008.11.28 09:48
2014.04.21 14:53
dpnn.dll (68 KB)

This stochastic neuro net is created in the form of a library specially for the expert advisors written on MQL4. The library is able to contain several nets simultaneously. I tried to make the net maximum independent, however soon I decided to take some of the functions to the external management for more controlling at first. I represent it in this form. The feature of this net is the fact that its size is changed dynamically depending on the situation. The net can pass the primary training and then be trained during the process of working. At that the new neurons will be born independently and be tuned and also die. The new net should be created for each class. For example, for the production of the overbuying and overselling signals you should create one net for the first case and the separate one for the second case.


The normalized to unity vector is inputted to the net. The output will be a number [0..1] that denotes the belonging of the inputted vector to the class of the net. At the same time if the net didn't find the pattern with the specified probability during the training then it will automatically add it to its memory by the dint of the new neuron. In case of the primary training, I recommend to run 2-3 repetiotions. Any way the moment when the net learns well the primary information occurs. Usually it comes after not more than 5 repetitions.

Prediction, or Classification to Be More Exact

The aim of the classification is the submission of the inputted pattern for matching the class of the net. If the net has learned to classify the signals of the reverse of the bearish trend to the bullish then these situations must be accompanied with the high outputted value that is close to 1. I leave the further actions with the responses obtained from the net and their integration with the EA to the opinion of the expert writer.

Main Necessary Fucntions for Working with Net

The CreateNet function is used for creation of the net.

double CreateNet(string NN, // We create the net named <NN>
int InputVectorSize, // with the number of neurons in the inputted vector <InputVectorSize>
double MinTV, // the threshold of the neuron conflicts
double MaxTV, // the threshold of the individuality
double MW, // the criterion of the neurons weakness
int NL); // the lifetime of the neurons (in bars), if 0 then they will live forever

For the convenience I decided to advert to nets by their names. I remind you that you can work with the whole set of neuro nets. The settings of each net are specified during its creation and stay unnoticed till they are deleted.

The individuality threshold is necessary for making the decisions about the birth of new neurons during the process of training. Usually it is equal to 0.95. If the lower value is specified (the lesser degree of the individuality) the net will try to modernize itself so that not a big amount of neurons would correspond the greater number of variants. In this case the accuracy of prediction decreases. If the value of MaxTV is high the net will strive to create a new neuron for almost every vector and the net may become very big. The net is constantly modernized so that the neurons would not conflict with each other (the patterns should not be analogous with each other). MinTV is implemented for this purpose, I have it equal to 2 usually. It is enough to define the MaxTV, MinTV and MW parameters once. Further the application of optimization for finding better values of the parameters is not necessary.

The strongest survives! This principle is used here as well. The weak neurons are those which weight has dropped below the minimum value of MW. Such neurons carry most likely the harmful information and should die not to generate an odd signal.

If necessary, you can kill older neurons and so get rid of the "old stereotypes". To do it you should specify the lifetime of the neurons in bars (NL). When a new neuron is created the time of its creation is memorized and in future this mark will allow you to delete it. So the specification of the time factor is obligatory when inputting any kind of data to the net.

We use the DestroyNet function to delete the net. It is very simple. Do not forget to delete the unnecessary nets, otherwise they will stay living in the memory of the PC until the MetaTrader is closed.

int DestroyNet(string NN); // Deletes the <NetName> net, returns the number of remaining nets

I didn't implement the checking of the unicity of the names, and you can create a lot of nets of the same name. Nevertheless the nets will differ from each other with a serial number.

string NetName(int i); // Returns the name of the net by the specified serial number
int GetNetsNumber(); // Returns the total number of the nets in the library
int NetNumber(string NetName); // Returns the serial number of the <NetName> net in the library

You should train the net using the TrainNet function. The right answer is probably necessary for introducing the order. For example, we accept 1 for the BUY signals, and -1 for the SELL signals. As far as for the BUY and SELL different nets are used its is not taken into the account inside the net. We take the current time or the time of bar creation.

double TrainNet(string NetName,
double& iX[], // the inputted normalized vector of the InputVectorSize size
int T, // true answer
datetime sT); // time of vector creation

During the process of training you can determine if the net has recognized the pattern and modernized or it has added it as a new one. Use the SizeOfNet function for this purpose.

int SizeOfNet(string NetName); // Returns the number of the Gauss neurons

You should read the response using the GetPredict function. Its parameters are the same with the TrainNet. If you input the same vector as the net was thaught then the answer will be 1.

double GetPredict(string NetName, // Delivers the probability [0..1] of belonging of the input vector to the class
double& iX[],
datetime sT);

And these functions are necessary for the internal working of the net. Just use them as is shown in the example.

void Shrink(string NetName);
void WReset(string NetName);
void AEqual(string NetName);
void CW(string NetName);
void KillWeaks(string NetName);
void KillOlds(string NetName,datetime sT);

The examples of usage

The example of init() function code

Print("Net Created with number: ",CreateNet("OverBought",24,0.2,0.95,0.001,Period()*60*1000)); // Create a net for the Sell signals
Print("Net Created with number: ",CreateNet("OverSold",24,0.2,0.95,0.001,Period()*60*1000)); // Create a net for the Buy signals

Print("Initial training started ...");
for (int R = 1; R <= Repetitions; R++) // Process of the primary training
{ // on the history data
WReset("OverBought"); // Zeroise the values of the weights
InitialTraining("OverBought",HistoryBars,-1); // Run the training
Shrink("OverBought"); // Modernize the net
AEqual("OverBought"); // Set all weights equal to 1
CW("OverBought"); // Calculate the weights
KillWeaks("OverBought"); // Kill the weak neurons
CW("OverBought"); // Calculate the weights

WReset("OverSold"); // Zeroise the values of the weights
InitialTraining("OverSold",HistoryBars,1); // Run the training
AEqual("OverSold"); // Set all weights equal to 1
Shrink("OverSold"); // Modernize the net
CW("OverSold"); // Calculate the weights
KillWeaks("OverSold"); // Kill the weak neurons
CW("OverSold"); // Calculate the weights
FlushReport("OverSold",R); // Output the reports to the file


The example of the start() function code

KillOlds("OverBought",iTime(Symbol(),0,1)); // Kill the old neurons
PostTraining("OverBought",-1); // Continune training during the process
Shrink("OverBought"); // Modernize the net
AEqual("OverBought"); // Set all weights equal to 1
CW("OverBought"); // Calculate the weights
KillWeaks("OverBought"); // Kill the old neurons
CW("OverBought"); // Calculate the weights

PostTraining("OverSold",1); // Continue training during the process
AEqual("OverSold"); // Set all weights equal to 1
Shrink("OverSold"); // Modernize the net
CW("OverSold"); // Calculate the weights
KillWeaks("OverSold"); // Kill the old neurons
CW("OverSold"); // Calculate the weights

double OverBought = Predict("OverBought");
double OverSold = Predict("OverSold");
Out = (OverBought - OverSold)/(OverBought+OverSold);

The example of the deinit() function code

Print("Destroying net=>",Destroy ("OverBought")); // Kill what we have prolonged
Print("Destroying net=>",Destroy ("OverSold")); // Kill what we have prolonged

The working capacity of the net is successfully checked. The good results depend on the method of creation of the input vector. It is important to understand that the vectors, that are preliminary known to be answering the class conditions, should be inputted during the training. In a simple language, if a net is created for the SELL signals then the bar the training vector is taken from should have the SELL signal indeed. In other case the net will gather the contradictive signals and you won't get the desired result.

I invite you to discuss the following questions:

1. The forming of the input vector - At present I use 24 parameters (the difference between the moving averages), normalized to unity for the range of 24 bars. I.e. I calculate the 24x24 matrix. Then I normalize it and take the last values.

2. The determinations of the "right answer" - i.e. when the outputted vector is the signal. I use the AMA at present. So I get to know if there was a signal only after two bars.

That's all.

Translated from Russian by MetaQuotes Software Corp.
Original code:

AudioPrice Revision 1 AudioPrice Revision 1

Have audio output of latest price in stereo! Revised to cater for fractional pips as now offered by some brokers to MT4.

Supertrend Supertrend

Indicator Supertrend. It displays the buying and selling with the colors.

A System: Championship 2008 Final Edit A System: Championship 2008 Final Edit

Automatic Trading System

RSI_Test RSI_Test

It is based on the RSI indicator.