• Overview
  • Reviews (1)
  • Comments (3)

This is an easy-to-use tool for implementing Support Vector Machine Learning in your Expert Advisors, Indicators and other MetaTrader 5 projects.

Until now, the use of support vector machine classification has been limited only by advanced coders via external java and c++ dll libraries. This tool has been developed using only the standard MetaTrader 5 tools and provides advanced support vector machine functionality using a very simple interface.

Please note: this product is not an Expert Advisor or Indicator. This is a library that allows users to implement support vector machine classification in their own Expert Advisors and Indicators.

What is a Support Vector Machine?

Support vector machines (svm) are a form of machine learning that use a supervised learning algorithm to analyze data and recognize patterns to be used for classification. They are used most prominently in fields such as bioinformatics and mathematics, however this library has been specifically developed with the intention to use support vector machine learning to analyze historical price data and extract patterns that can be used to generate signals.

If you want to find out more about the support vector machines' mechanics and how they work, I suggest you start with the Wikipedia page http://en.wikipedia.org/wiki/Support_vector_machine. The article provides good overview and further links if you are interested in looking into it further.

How the Library Works:

The basic process for any support vector machine is as follows:

  • Gather historical market price and indicator data;
  • Use historical data to generate a set of training inputs and outputs;
  • Use these historical inputs and outputs to train the support vector machine;
  • Use the trained support vector machine to analyze current market price and indicator data to signal new trades.

A support vector machine is basically an input/output machine. The user passes input(s) to the machine and it produces an output of either true or false. If the support vector machine has not yet been trained, it will usually give only a random output for any given input. To have the support vector machine produce a useful output, it must first be trained.

The training of a support vector machine is done by passing in a set of inputs with a set of corresponding desired outputs. The support vector machine algorithm will then use this combined dataset to extract patterns. In the case of this tool, the inputs used are indicators (inputs can be any combination of standard or custom indicators selected by the user) and the outputs are either true or false (corresponding to whether a new trade should be opened).

Once the indicators (to be used as inputs) have been selected by the user along with the parameters for determining outputs, the tool will generate a set of inputs and outputs to be used for training the support vector machine. Once this is done, training can be commenced. Once the support vector machine has been successfully trained, it can be used to take current indicator values as inputs and signal the Expert Advisor to either make a new trade, or not.

Advanced Users: additional functions have been included to allow users to manually create and set your training inputs and outputs. This can be used for more complex applications such as signalling when to exit a trade or for money management. To do this, see details below on the setInputs() and setOutputs() functions.

A variety of functions have been included for both basic and advanced users. These are outlined below:

Function

Description

#import "svMachineTool.ex5"

<function signatures>

#import

This statement is called to at the top of your Expert Advisor/indicator project to import the svMachineTool functions. If you don’t call this, you won’t be able to use any of the svMachineTool functions

int initSVMachine(void);

This function initializes a new support vector machine and returns a function handle that can be used for further computation.

bool setParameters(int handle, ENUM_OPTION option,double value)

This method passes your parameters to the new support vector machine that has been created. Parameters need to be passed one at a time using this method. If no parameters are passed to the object, then the parameters will assume their default values (for the default values refer to the parameter table).

bool setIndicatorHandles(int handle, int& indicatorHandles[],int offset, int N)

This function allows you to pass in the handles of initialized indicators to the support vector machine. This is done by passing and int array with the handles. The offset value corresponds to the last candle (on the current chart timeframe) that you wish to use for your training data and the value for N sets the number of training points.

bool genInputs(int handle, int N)

This function generates the support vector machine inputs to be used for training. To generate the inputs, it uses the indicators handles passed in via the previous setIndicatorHandles function and generates N training points starting from the current time and generating indicator values using the current chart timeframe. This function will either return true or false based on whether the inputs are successfully generated. Any errors will be printed to the error log.

bool setInputs(int handle, double& Inputs[], int nInputs)

This function can be used to manually set the input values used for training your support vector machine. The inputs must be passed in as an array of double values in this format.

Inputs[] = | A1 | B1 | C1 | A2 | B2 | C2 | A3 | B3 | C3 |

nInputs denotes the number of inputs per training point. In the example above, a single training point consists of an A B & C value, therefore the value of nInputs would be 3. The function returns either true or false depending on whether the Inputs are set successfully.

bool genOutputs(int handle, ENUM_TRADE trade, int StopLoss, int TakeProfit, double duration)

This function can be used to automatically generate your output array for training your support vector machine. The output array is generated by looking at the historical minute candle data and taking ‘hypothetical’ trades based on the variable passed to it and determines whether or not each of these trades would have been successful.

ENUM_TRADE = This variable sets the type of ‘hypothetical’ trade you want your svm to train for. This can be either BUY or SELL

StopLoss = sets the stop loss of ‘hypothetical’ in pips

TakeProfit  = sets the take profit of ‘hypothetical’ in pips

Duration = sets a maximum duration of the ‘hypothetical’ trade [in hours] to be deemed successful. (i.e. if duration is set to 2, then only ‘hypothetical’ trades that close within 2hrs will be considered successful in the training outputs).

This function will either return true or false based on whether the inputs are successfully generated. Any errors will be printed to the error log.

bool setOutputs(int handle, bool& Outputs)

This function can be used to manually set the Output values used for training your svm. The Outputs must be passed in as an array of boolean values. The function returns either true or false depending on whether the Inputs are successfully set. Any errors will be printed to the error log.

bool training(int handle)

This function is used to initialize training of your support vector machine using the initialized training inputs and outputs. This function will generally take the longest to execute. The support vector machine must be trained before you can use it to classify new inputs.

bool classify(void)

bool classify(int offset)

bool classify(double& Input)

The classify function uses the trained support vector machine to assess new inputs and return a value of true or false.

Void = If no variables are passed to the classify method, then inputs will be generated using the latest indicator data.

Offset = used to generate inputs from old data. The offset specifies how many bars offset from the current bar (using the current time frame).

Input = used to manually set the input to classify (note: this classify method must be used if input data has been manually set using setInputs())

void  deinitSVMachine(void)

This function is intended to be called at the end of your Expert Advisor/Indicator. This function deletes all of the unused variables to avoid taking up space.

void setIndicatorHandles(int handle,int& indicatorHandles[],int& Offsets[], int startBar,int N)

This function works in a similar way to the original setIndicatorHandles() function however it also has the ability to pass specific offsets corresponding to each of the indicator handles passed to it. As with the previous version the indicatorHandles[]  array stores the indicator handles for your selected inputs while the Offsets[] array stores the corresponding indicator offset (i.e. offset value of 0 will use the current bar when generating inputs, whereas an offset value of 1 will use the previous bar…and so on). For example, assume the following scenario:

indicatorHandles[5] = [ 1 | 2 | 3 | 3 | 3 ] = {1,2,3,3,3};
Offsets[5]             = [ 0 | 0 | 0 | 1 | 2 ] = {0,0,0,1,2};

In this scenario, input 1 and 2 are calculated using the current bar of two individual indicators, whereas inputs 3, 4 & 5 are calculated based on the past 3 bars of the same indicators. This function can be used to pass in a snapshot of an indicator to the support vector machine (i.e. a couple of bars).

The remaining variables required for this function are the startBar value and the N value. startBar corresponds to the last candle (on the current chart timeframe) that you wish to use for your training data and the value for N sets the number of training points. For example, a startBar value of 4 and an N value of 6 will tell the support vector machine to only bars 4 to 9 when generating training inputs and outputs.

bool getTrainingData(int handle, double& Inputs[], bool& Outputs[])

This function allows users to access the training data that is generated when calling the genInputs() and the genOutputs() function. The first variable required for this function is the handle of the support vector machine. The following two variables required are an int-array and a double-array. When called, the function will populate these two arrays with the training data generated for the support vector machine. Note that if this function is called before the genInputs() or the genOutputs() functions are called, it will return arrays of zeros length.

Certain parameters of your support vector machine can be set using the setParameters() function call. These parameters are explained below:

Option Field

Default Value

Description

OP_MEMORY

1000

Training the support vector machine can consume a significant amount of memory. This option sets the maximum memory footprint you want the support vector machine to take. The value given is measured in MB. If a memory value of 1000 MB is set, then the training algorithm will manage its memory to keep its foot print below this level. This should be considered particularly if you choose to perform back testing across multiple cores. For example, if I have a quad core computer (corresponding to 4 local testing agents) and I have 8 GB RAM, I will generally set my memory value to about 1250 MB. This will mean that when training is being executed in parallel across all local agents, only a maximum of 5000 MB (4 x 1250 MB) will be used leaving 3000 MB for the operating system and other programs without causing problems.

OP_MAXCYCLES

1000000

This will limit the maximum number of training cycles that will occur. The reason for this is to avoid the scenario where training never stops. This can occasionally happen because it is trying to achieve an impossible solution. Unless you have a specific reason, I recommend you don’t manually change this value.

OP_ TOLERANCE

0.1

This value sets the maximum error you are willing to accept from the final support vector machine. The input for this is a percentage (i.e. 0.1 is 10% error, 0.15 is 15% error). If you are finding that your training doesn’t converge on a solution, I recommend you increase the acceptable error tolerance value.


Example: How to Use the Support Vector Machine Tool to Signal Trades

An example of Expert Advisor (“svmTrader”) has been written to show a typical use of the support vector machine learning tool. You can download it for free from Code Base.

JasperFu
22
2012.12.18 12:38 

Very useful product!!! I previously needed to used c++ libraries to get support vector machine functionality in my breakout indicators. This library has a far simpler interface and avoids having to use dll files

Rash
59
rushid 2013.06.30 14:14

Dear Cubix,

I had 2 mt5 terminals on my PC, your library works at one terminal and does not at another (.ex5 not found). The problem when i bought your product it automatically was downloaded to the terminal with the futures only (where i dont need it), but wanted to have it working/testing at my FX Mt5 terminal, i do all instructions as discribed in http://www.metatrader5.com/en/terminal/help/interface/toolbox/toolbox_market to transfer your code from one terminal to another but without success. I did not install it more then two diffent PCs, only in one. I dont understand now what to do whether my license expired or what else ? Can you kindly help or advise how to resolve my problem. Thank you in advance!

Josh Readhead
1407
Cubix 2013.07.01 14:28
rushid:

Dear Cubix,

I had 2 mt5 terminals on my PC, your library works at one terminal and does not at another (.ex5 not found). The problem when i bought your product it automatically was downloaded to the terminal with the futures only (where i dont need it), but wanted to have it working/testing at my FX Mt5 terminal, i do all instructions as discribed in http://www.metatrader5.com/en/terminal/help/interface/toolbox/toolbox_market to transfer your code from one terminal to another but without success. I did not install it more then two diffent PCs, only in one. I dont understand now what to do whether my license expired or what else ? Can you kindly help or advise how to resolve my problem. Thank you in advance!

Hi Rush

I will forward your query to metaquotes - if there is a problem, it seems to be with the metaquotes market system and licenses - so I cant solve this for you. I just developed the library and posted it to the market. If there is a specific problem with the product - I can help you with that, otherwise this needs to be solved with metaquotes market. I will forward it for you. Thanks

Regards

Cubix

Vlad Minkov
8
VladMinkov 2014.03.12 16:39

Глупости это всё.

Нужно использовать разработки профессионалов. Я имею ввиду язык R. Тема SVM там разработана досконально. Но должен заметить, из опыта применения в классификации, этот метод не выделяется по полученным результатам. Есть более надежные ( ADA например).

Иначе как результат рукоделия наверное хорош. 

Удачи