How To Backtest Binary Options

Tabular array of Contents

1. Introduction
2. Installation
3. Binary Options strategy example
three.1. Ascertain Binary Options strategy
3.two. Create Binary Options strategy
iii.2.1. Input parameters
three.ii.2. Include Binary-Options-Strategy-Library
3.2.3. Add together CallStrategy()
3.2.4. Implement CheckMyRules() and helper-function
3.2.v. Print out debug values
3.2.half dozen. Apply of external Indicators (ex4 files)
3.3. The complete lawmaking
4. Run a backtest (video)
5. Run a forward test
six. FAQ
7. Miscellaneous


1. Introduction

This article shows how to build a Binary Options strategy and examination it in Strategy-Tester of Metatrader 4 with Binary-Options-Strategy-Tester utility. By default Strategy-Tester of Metatrader four can test Proficient Advisors and Indicators confronting historical data, but information technology cannot handle Binary Options with expire times. As I need a possibility to test Binary Options strategies automated in Strategy-Tester of MetaTrader 4, the Binary-Options-Strategy-Tester was build as a utility to fit those needs.

The concept contains the following parts:

Binary Options Strategy Tester Concept

This is a pace by stride instance how to build a Binary Options strategy stored in an Indicator (marked every bit red in image above) to communicate through Binary-Options-Strategy-Library (marked as green in epitome to a higher place) with the Binary-Options-Strategy-Tester (marked as blue in image in a higher place), to place virtual orders and count their results with backtests and forwards tests.

Please keep in listen:
Backtesting with historical data will never represent the real future, but it might requite you an guess value to become your strategy more than stable.
The quality of your backtest volition depends on your historical information. Therefore information technology is strongly recommended to use a set of hight quality data!


2. Installation

Download and purchase Binary-Options-Strategy-Tester utility from marketplace:
Test-Framework to exam Binary Options strategies in Strategy-Tester of MetaTrader iv.

Why a purchased version of Binary-Options-Strategy-Tester utility is needed?

A Binary-Options strategy has to call a part of the Binary-Options-Strategy-Tester (via Binary-Options-Strategy-Library) to place the virtual trades. Related to the license concept of MQL4 this only works if the production has a working license. Therefore you have to purchase the production to test Binary Options strategies or this example.

Download free BinaryOptionsStrategyLibrary.mqh and place it in into folder \Include ([path to your MetaTrader iv]\MQL4\Include):
The free library will provide several functions to build your Binary Options strategy easily and to communicate with the Binary-Options-Strategy-Tester. See Binary-Options-Strategy-Library for more details of the library.

Download free KVO.mq4 indicator and place it (and the compiled KVO.ex4 file) into binder \Indicators\Downloads ([path to your MetaTrader four]\MQL4\Indicators\Downloads):
The KVO indicator is used as an example to show the access of external indicators and there ex4 files in department “3.2.6 Utilize of external Indicators (ex4 files)”. Meet https://www.mql5.com/en/code/8677 for more details of the indicator.

Now y’all can go further with section “iii. Binary options strategy example” and build the case code past yourself or just download the lawmaking of this case below.

Optional download BinaryOptionsStrategyExample.mq4 and place it (and the compiled BinaryOptionsStrategyExample.ex4 file) into folder \Indicators ([path to your MetaTrader 4]\MQL4\Indicators):
Download the code of this Binary Options strategy case to allow information technology run without building it past yourself.

To compile the needed .ex4 files open up the .mq4 files (KVO.mq4 and BinaryOptionsStrategyExample.mq4 – Non Binary-Options-Strategy-Library.mqh) in MetaQuotes Language Editor and click on button “Compile” or simply restart your MetaTrader 4 after these files are stored in the described folders and MetaTrader iv will do this automatically for you.


three. Binary Options strategy instance

The post-obit steps will guide you throgh an instance how to build an example Binary Options strategy stored in an Indicator to communicate with Binary-Options-Strategy-Tester. You can build information technology past yourself or simply download the code of the BinaryOptionsStrategyExample.mq4.

Please note:This strategy is non a profitable Binary Options strategy! It is just an example how to build a strategy in an indicator to communicate with the Binary-Options-Strategy-Tester utility. Of grade you have to build a profitable strategy by yourself. Only as you will see, this utility will assist you to test and improve your Binary Options strategy.


three.1 Define Binary Options strategy

Outset of all we have to define the strategy and the changable values (input parameters). MQL4 documentation shows all technical indicators, which can be adressed over the iCustom interface: https://docs.mql4.com/indicators.

Let us say we like to create a simple Moving Boilerplate cross strategy with 1 “fast” and one “tiresome” Moving Boilerplate to trade on adjacent candle after they have crossed each other. Documentation tells, how we can become the value of a single Moving Average: https://docs.mql4.com/indicators/ima.

Let us further say, we like to choose values for “MA averaging catamenia” (fast and slow) and for “applied price” too equally for the “averaging method”. Other values (like symbol, timeframe and shift) depends on the testcase (east.g. the symbol the tester runs on) and should be set automatically. Therefore we basically need the following variables for a Moving Boilerplate:

int
ma_period
int
ma_method
int
applied_price

Equally we need 2 Moving Averages to bank check their crosses, we need the following input parameters for the strategy example with some default values:

int
period_fast        =  5;
int
period_slow        = 10;
int
method_both        =0;
int
applied_price_both =0;

Baca juga:  When To Sell Binary Options


three.2 Create Binary Options strategy

Y’all need to build an indicator which stores your Binary Options strategy to drag it on the nautical chart where Binary-Options-Strategy-Tester is running on.

Open up MetaQuotes Linguistic communication Editor (in MetaTrader 4 click on “Tools” -> “MetaQuotes Language editor” or simply press F4) and click on “New”:

Language Editor New

The MQL Sorcerer will announced. Select “Custom Indicator” to create an empty indicator and click on “Next”:

Language Editor Custom Indicator

Enter the proper name, copyright and link of the strategy equally well every bit the input parameters with their types and default values (initial values) by clicking “Add together”-Button and press “Next”:

Language Editor Custom Indicator Values

On tab event handlers select checkbox “OnCalculate” as we need this event to check for our strategy on every tick. Press “Next”:

Language Editor Custom Indicator Events

On tab drawing backdrop select checkbox “Indicator in seperate window” as nosotros need a seperate window to print out the debug values. Printing “Finish”:

Language Editor Custom Indicator Drawing Properties

The initial lawmaking of your indicator will announced:

#holding

copyright
“Copyright 2016, __martin__”

#property

link“https://www.mql5.com/en/users/__martin__”

#property

version
“i.00”

#property

strict

#property

indicator_separate_window

input
int      period_fast=five;
input
int      period_slow=x;
input
int      method_both=0;
input
int      applied_price_both=0;

int
OnInit()
{

  

return(INIT_SUCCEEDED);
}

int
OnCalculate(const
int
rates_total,
const
int
prev_calculated,
const
datetime
&time[],
const
double
&open up[],
const
double
&loftier[],
const
double
&depression[],
const
double
&shut[],
const
long
&tick_volume[],
const
long
&book[],
const
int
&spread[])
{

return(rates_total);
}


3.2.1 Input parameters

The initial input parameters are created with the MQL Wizard (run into 3.ii Create Binary Options strategy) and we will heighten them with the following steps.

To avoid to have to enter int-values for practical cost and averaging method of the Moving Averages for input parameters, the type for method_both and applied_price_both is inverse from int to type of enumeration with a default value.

ENUM_MA_METHOD: https://docs.mql4.com/constants/indicatorconstants/enum_ma_method
ENUM_APPLIED_PRICE: https://docs.mql4.com/constants/indicatorconstants/prices#enum_applied_price_enum

In addition comments for the input parameters are added to prove the comments as labels instead of variable names:

inputint                period_fast        =v;
inputint                period_slow        =10;
inputENUM_MA_METHOD     method_both        =
MODE_SMA;

inputENUM_APPLIED_PRICE applied_price_both =
PRICE_CLOSE;

With this modifications the input parameters provides a dropdown with the available values to select likewise as “labels” for the input parameters:

Binary Options Strategy Input Paremeters


3.2.two Include Binary-Options-Strategy-Library

If y’all have downloaded and stored the library (run into 2. Installation) into \Include folder ([path to your MetaTrader 4]\MQL4\Include), yous are able to include the library like this:

#property

copyright
“Copyright 2016, __martin__”

#property

link“https://www.mql5.com/en/users/__martin__”

#property

version
“1.00”

#property

strict

#property

indicator_separate_window

#include

<BinaryOptionsStrategyLibrary.mqh>

The library will but be bachelor like described in the instance above if you placed it in \Include folder of your MetaTrader 4.
Changing the content of the library is not needed!

Binary-Options-Strategy-Library will raise the input parameters with ii new parameters:

  • Place only one SELL or one BUY trade per candle
  • Check just at the first of a new candle for the strategy

Binary Options Strategy Input Parameters Enhanced


3.2.3 Add CallStrategy()

Add a call to CallStrategy()-function in OnCalculate() of your strategy indicator to call the strategy on every new tick. CallStrategy() is provided by Binary-Options-Strategy-Library you take inlcuded like discribed above:

intOnCalculate(constint rates_total,
constint prev_calculated,
constdatetime &fourth dimension[],
constdouble &open up[],
constdouble &high[],
constdouble &low[],
constdouble &close[],
constlong &tick_volume[],
constlong &book[],
constint &spread[])
{

CallStrategy();

return
(rates_total);
}

CallStrategy()-role in Binary-Options-Strategy-Library will telephone call a part named CheckMyRules() in your indicator where yous tin identify your weather for your Binary Options strategy.
Therefore
yous take to implement the function CheckMyRules() in your Binary Options strategy indicator.


3.2.iv Implement CheckMyRules() and helper-function

In CheckMyRules()-part, which is called through the Binary-Options-Strategy-Library, the conditions for the strategy are implemented and trades are placed through PlaceTrade()-role of the library. Values of both Moving Averages are temporarilly stored in variables to compare them in if-weather condition while the values of the Moving Averages are taken from the helper-function GetValuesForMA():

inputint                period_fast        =5;
inputint                period_slow        =10;
inputENUM_MA_METHOD     method_both        = MODE_SMA;
inputENUM_APPLIED_PRICE applied_price_both = PRICE_CLOSE;


void
CheckMyRules()


{


double
emaSlow_Current = GetValueForMA(period_slow,
0);



double
emaFast_Current = GetValueForMA(period_fast,
0);


double
emaSlow_Past = GetValueForMA(period_slow,
one);



double
emaFast_Past = GetValueForMA(period_fast,
1);


if(emaFast_Past > emaSlow_Past


&& emaFast_Current < emaSlow_Past)

{

PlaceTrade(OP_SELL);

}


if(emaFast_Past < emaSlow_Past


&& emaFast_Current > emaSlow_Past)

{

PlaceTrade(OP_BUY);

}

  }


double
GetValueForMA(int
_period,int
_shift)


{


return
iMA(Zippo,0,_period,0,method_both,applied_price_both,_shift);


}


3.2.5 Print out debug values

The function PrintDebugValue() privides a possibility to impress out debug values while the tester is running. In the example below the values of the Moving Averages are printed out with their variable names equally labels:

inputint                period_fast        =v;
inputint                period_slow        =10;
inputENUM_MA_METHOD     method_both        = MODE_SMA;
inputENUM_APPLIED_PRICE applied_price_both = PRICE_CLOSE;

Baca juga:  Trading Platforms In Usa: Everything You Need To Know

void
CheckMyRules()
{

double
emaSlow_Current = GetValueForMA(period_slow,
0);
double
emaFast_Current = GetValueForMA(period_fast,
0);

double
emaSlow_Past = GetValueForMA(period_slow,
1);
double
emaFast_Past = GetValueForMA(period_fast,
1);

PrintDebugValue(“emaSlow_Current: “,(string)emaSlow_Current,0);

PrintDebugValue(“emaFast_Current: “,(string)emaFast_Current,one);

PrintDebugValue(“emaSlow_Past: “,(cord)emaSlow_Past,2);
PrintDebugValue(“emaFast_Past: “,(string)emaFast_Past,3);

if(emaFast_Past > emaSlow_Past
&& emaFast_Current < emaSlow_Past)

{
PlaceTrade(OP_SELL);

}

if(emaFast_Past < emaSlow_Past
&& emaFast_Current > emaSlow_Past)

{
PlaceTrade(OP_BUY);

}

     }

double
GetValueForMA(int
_period,int
_shift)
{
return
iMA(Zip,0,_period,0,method_both,applied_price_both,_shift);
}


3.2.half dozen Use of external Indicators (ex4 files)

In addition an external indicator which stores its values in buffers can be accessed for the Binary Options strategy, even if only the compiled ex4-file exists.

Permit us say we like to include the signal line of the KVO indicator https://www.mql5.com/en/lawmaking/8677 to place trades merely if the signal line is over 0 for Purchase trades and under 0 for SELL trades. Download the KVO.mq4 indicator and place the compiled (ex4 file) into binder \Indicators\Downloads ([path to your MetaTrader 4]\MQL4\Indicators\Downloads).

To compile the needed .ex4 file open KVO.mq4 in MetaQuotes Language Editor and click on button “Compile” or just restart your MetaTrader iv after the file is stored in the described binder and MetaTrader 4 will practice this automatically for you.

Starting time we have to identify the relevant buffers which stores the relevant values to access. Therefore nosotros printing the button “Data Window” in MetaTrader 4 to show all available buffers of the used indicators and elevate the KVO indicator on a chart. Past hovering the cross over the chart (press mouse-wheel on nautical chart to bring up the cantankerous) the buffer values of the indicator of the hovered timeperiod will be shown in information window:

External Indicator Buffers And Values

The data window labels tells united states of america the second buffer value of the indicator stores the signal line. If buffers of indicators did not have labels, we tin discover the right one past comparing the buffer values with the displayed value nether the cantankerous in the nautical chart and indicator. Buffers of an indicator starts with 0, so we have buffer value ane = buffer 0, buffer value 2 = buffer i and then on and nosotros take to access buffer one to get the signal value.

Next we have to know all input parameters of the external indicator we like to access. By draging the indicator on a chart, nosotros meet all input paremeters:

Input Parameters KVO

Let united states further say, we like to access the indicator with (its default) values: 34, 55 and 13. We use a helper function (based on iCostum), wich provides usa the possibility to go the values of the indicator with parameters for buffer and shift, while shift 0 will exist the value of the current candle, shift 1 the value of the last candle, shift ii the value of the second to terminal candle and then on. In addition we temporarilly store the values of the indicator buffer and enhance the if-condition of the strategy:

inputint                period_fast        =five;
inputint                period_slow        =10;
inputENUM_MA_METHOD     method_both        = MODE_SMA;
inputENUM_APPLIED_PRICE applied_price_both = PRICE_CLOSE;

void
CheckMyRules()
{

double
emaSlow_Current = GetValueForMA(period_slow,
0);
double
emaFast_Current = GetValueForMA(period_fast,
0);

double
emaSlow_Past = GetValueForMA(period_slow,
1);
double
emaFast_Past = GetValueForMA(period_fast,
i);


double kvoSignal = GetValuesFromIndicator__KVO__(1,0);

   PrintDebugValue(“emaSlow_Current: “,(string)emaSlow_Current,0);

PrintDebugValue(“emaFast_Current: “,(cord)emaFast_Current,one);

PrintDebugValue(“emaSlow_Past: “,(string)emaSlow_Past,2);
PrintDebugValue(“emaFast_Past: “,(string)emaFast_Past,3);

if(emaFast_Past > emaSlow_Past
&& emaFast_Current < emaSlow_Past

&& kvoSignal <
0)


{
PlaceTrade(OP_SELL);

}

if(emaFast_Past < emaSlow_Past
&& emaFast_Current > emaSlow_Past

&& kvoSignal >
0)


{
PlaceTrade(OP_BUY);

}

     }

double
GetValueForMA(int
_period,int
_shift)
{
return
iMA(NULL,0,_period,0,method_both,applied_price_both,_shift);
}


double GetValuesFromIndicator__KVO__(int
_buffer,
int
_shift=0)

{


return (



iCustom
(



NULL,


0,


“\\Downloads\\KVO.ex4”,


34,



55,



xiii,

_buffer,
_shift
)

);

}

Information technology is too possible to enhance the input parameters of our strategy indicator with the values for the used KVO indicator and ready the values in helper function past variables. Every bit this tutorial should be just an case and “as unproblematic as possible”, this variant is not shown.


three.three The complete code

Below you will find the consummate lawmaking of the Binary-Options-Strategy-Example from all the steps above, fix to drag on the Binary-Options-Strategy-Tester to examination and see the results on nautical chart:

#property

copyright
“Copyright 2016, __martin__”

#belongings

link“https://world wide web.mql5.com/en/users/__martin__”

#belongings

version
“1.00”

#property

strict

#property

indicator_separate_window

#include
<BinaryOptionsStrategyLibrary.mqh>

input
int                period_fast        =5;

input
int                period_slow        =
ten;

input
ENUM_MA_METHOD     method_both        =
MODE_SMA;

input
ENUM_APPLIED_PRICE
applied_price_both =
PRICE_CLOSE;

int
OnInit()
  {


return(INIT_SUCCEEDED);
  }

int
OnCalculate(const
int
rates_total,
const
int
prev_calculated,
const
datetime
&fourth dimension[],
const
double
&open[],
const
double
&high[],
const
double
&low[],
const
double
&close[],
const
long
&tick_volume[],
const
long
&volume[],
const
int
&spread[])
  {

Baca juga:  Blockfi Withdrawals: A Comprehensive Guide For Domain_10

   CallStrategy();


return(rates_total);
  }

void
CheckMyRules()
  {

  

double
emaSlow_Current = GetValueForMA(period_slow,
0);
double
emaFast_Current = GetValueForMA(period_fast,
0);

double
emaSlow_Past = GetValueForMA(period_slow,
1);
double
emaFast_Past = GetValueForMA(period_fast,
i);

  

double
kvoSignal = GetValuesFromIndicator__KVO__(1,0);

      PrintDebugValue(“emaSlow_Current: “,(cord)emaSlow_Current,0);

   PrintDebugValue(“emaFast_Current: “,(cord)emaFast_Current,one);

   PrintDebugValue(“emaSlow_Past: “,(string)emaSlow_Past,2);

   PrintDebugValue(“emaFast_Past: “,(cord)emaFast_Past,iii);

if(emaFast_Past > emaSlow_Past
   && emaFast_Current < emaSlow_Past
   && kvoSignal <
0)
     {
      PlaceTrade(OP_SELL);
     }

  
if(emaFast_Past < emaSlow_Past
   && emaFast_Current > emaSlow_Past
   && kvoSignal >
0)
     {
      PlaceTrade(OP_BUY);

     }

    }

double
GetValueForMA(int
_period,int
_shift)
  {
return
iMA(Nix,0,_period,0,method_both,applied_price_both,_shift);
  }

double
GetValuesFromIndicator__KVO__(int
_buffer,
int
_shift=0)

  {
render
(

iCustom
(
NULL,
0,

                  
“\\Downloads\\KVO.ex4”,

34,
55,
13,

                                         _buffer,

                      _shift

                    )
          );
  }


4. Run a backtest (video)

The post-obit video shows how to run a backtest of your Binary Options strategy in Strategy-Tester of MetaTrader iv:

  • Start Binary-Options-Strategy-Tester in Strategy-Tester of MetaTrader 4 and set the input parameters
  • Drag your Binary Options strategy indicator on the chart, set the input parameters and
    check “Allow external adept imports” on the “mutual” tab
  • Drag your used indicators with their used input parameters on the nautical chart to run into their values while tester is running (optional)
  • Relieve all settings in a template to run the test with all settings again – using the pause push button of the Strategy-Tester (optional)
  • See the results of your Binary Options strategy on the Strategy-Tester chart


5. Run a forward examination

To do a forwards test simply drag the Binary-Options-Strategy-Tester utility and your strategy indicator on your demo or alive chart of your broker instead of using information technology in Strategy-Tester:

  • Drag Binary-Options-Strategy-Tester utility on demo or live chart and set the input parameters
  • Drag your Binary Options strategy indicator on the nautical chart, set the input parameters and
    check “Let external expert imports” on the “common” tab
  • Drag your used indicators with their used input parameters on the chart to encounter their values while frontwards test is running (optional)
  • Save all settings in a template to run the test again with all settings (optional)
  • Come across the results of your Binary Options strategy on demo or live chart


6. FAQ

Question: Why do y’all show an example of a non assisting Binary Options strategy?
Answere: This is just an instance how to build a strategy in an Indicator to communicate with the Binary-Options-Strategy-Tester utility in marketplace to test and ameliorate your strategy.

Question: Binary-Options-Strategy-Tester stops later on the exact amount of losses with error “Array out of range”. Why?
Answere: Binary-Options-Strategy-Tester can ascent an mistake later on x losses to finish Tester and to analyse the situaion on the chart. If you exercise not want to, merely switch off the choice in settings.

Question: No arrows announced on chart later I draged my indicator with a working strategy on it. What happened?
Answere: Yous accept to enable “Allow external expert imports” on the “mutual” tab while you drag your strategy-indicator on the nautical chart (log message will show an fault in this case).

Question: No arrows appear on nautical chart later on I draged my indicator with a working strategy on information technology with “Allow external practiced imports” enabled. Why?
Answere: A strategy has to call a role of Binary-Options-Strategy-Tester to place virtual trades. Related to the MQL4 license concept this simply works if the product has a working license. Therefore you have to purchase the product.

Question: No arrows appear on chart after I dragged my indicator with a working strategy on it and I got errors like “Cannot call ..” or “Cannot load ..” in the log of MetaTrader 4. What can I practice?
Answere: Utilise the latest version (greater v1.00) of BinaryOptionsStrategyLibrary.mqh. Check version tag in code of your BinaryOptionsStrategyLibrary.mqh and see changelog v1.01 of BinaryOptionsStrategyLibrary.

Question: I see no results on Strategy-Tester tabs “Results”, “Graph”, “Report”. Where I can run across the results?
Answere: Strategy-Tester of MetaTrader iv can not handle Binary Options then these tabs con not be used. Therefore this utility calculates all wins and losses and prints the results on the chart.


7. Miscellaneous

As I need a possibility to test Binary Options strategies automated in Strategy-Tester of MetaTrader 4 for long time periods in a short time and to exercise foward tests on the nautical chart of the banker, this utility was build. I accept spent a lot of time for the concept and the implementation of the Binary-Options-Strategy-Tester as well as for the documentation. Maybe there is a meliorate manner to practise it and maybe some improvements will bring it closer to fit the needs of you. So please experience complimentary to contact me for ideas for improvements!

Source: https://www.mql5.com/en/articles/2820

You May Also Like