EXP - THE XCUSTOMEA UNIVERSAL TRADE ADVISER ON USER INDICATORS. EXPERT ON THE INDICATOR!

EXP - THE XCUSTOMEA UNIVERSAL TRADE ADVISER ON USER INDICATORS. EXPERT ON THE INDICATOR!

13 October 2018, 09:29
Vladislav Andruschenko
2
3 685






Description

Exp - The xCustomEA Universal trading advisor on custom indicators.

Our new advisor  The xCustomEA is based on the adviser  The X - Universal EA

The functionality of the universal trading advisor  The xCustomEA exactly repeats all the parameters of our advisor  The X except for one thing:

The xCustomEA works on a custom indicator and has the ability to program its own trading strategy for the MT5 and MT4 terminals.

In other words:  The xCustomEA has a connection with custom indicators that can be downloaded from the Internet or the mql5 market.

 

Foreword

When programming advisors to order, we were not surprised that 90% of orders are based on strategies for indicators.

Therefore, our main work was to embed a custom indicator in our  template for writing an advisor .

But the cost of such work + template for writing + open source of such a template is too high. And not all traders agree to write a trading advisor for one custom indicator.

After all, if your indicator is not profitable enough, then you will have to order a new adviser on a new indicator for the same money.

 

We found a way out of this situation and developed a new universal trade advisor  The xCustomEA

This adviser does not have a pre-set strategy, it can trade on signals from other indicators. You can program your custom indicator, and our adviser  The xCustomEA will open positions on signals.

By purchasing Our Universal Trading Advisor  The xCustomEA , you can program advisors on indicators every day!

Attention : You are not required to buy an indicator to test the adviser in the strategy tester.

You can download the indicator in the strategy tester and check our adviser on this indicator in the strategy tester.

Only after getting profitable results in the strategy tester, you can buy a custom indicator and run an advisor on this indicator on a real or demo account!


Basic Functions and Parameter Description

We will not dwell on the detailed description of the main parameters of the adviser because 99% of the parameters correspond to our system The X.

A full description of all the basic parameters and functions is described in the instructions for The X.  Parameter Description Exp The xCustomEA

In  The xCustomEA there are such functions as:

  1. Autolot (calculation of the lot from the current balance), money management;
  2. Fixed lot;
  3. Work on time (limiting the work of an adviser on trading time);
  4. Trailing stop (standard, with the "Only profitable" algorithm);
  5. Parabolic SAR trailing stop
  6. Error handling functions for real accounts;
  7. Block closing on total profit and loss with the ability to disable the adviser on the account;
  8. Breakeven (set stop loss to break-even point) (set stop loss to zero);
  9. Martingale (increase in the next lot after a losing position);
  10. Work solely on indicator signals (Signal - opening, Signal - closing an opposite order - opening);
  11. Closing the opposite signal when changing the signal;
  12. The function "REVERSE", flipping the signals of your strategy;
  13. Function averaging unprofitable position.
  14. The function of the additional opening of positions on the trend and against the trend.
  15. Virtual stop loss, take profit and trailing stop functions.
  16. Work positions, pending orders, limit orders.
  17. Work with drawdown;
  18. Work with a limit of profit and loss;
  19. Work with test results;
  20. Work in semi-automatic mode without opening a position with the notice that the strategy received a signal to open, the ALERT is displayed on the screen;

A full description of all the basic parameters and functions is described in the instructions for The X.  Parameter Description Exp The xCustomEA  Descriptions of settings and inputs

Block connecting a custom strategy to our advisor

A new block of work with a custom strategy has been included in our new advisor.



Parameter Description
OWN Signal options
SignalNameIndicator

The name of the custom indicator from which the main signals for opening positions will be received.

Default: " Ind - The xCustomEA "

This is a standard empty indicator, into which you can program your strategy according to our example!

We also created an example of a custom indicator based on The X signals.

"Ind - The xCustomEA Example TheX"

SignalTypeIndicator

The type of indicator for signals.

There are two types of work advisor:

xCustomEA- Advisor's work on our indicator, in which you personally program your strategy.

xArrow- The EA worksdirectly with a custom indicator that has Arrow type buffers that can be used for the EA.

For example: Buffer with indicator signals to BUY and Buffer with indicator signals to SELL

Such buffers must be of the Arrow type.

Our Expert Advisor determines the signal by type: The buffer value is not equal to an empty value and above 0 .:

// --- we check the conditions and set the value for sig if (xCustom_SIGNAL_BUY_buffer [OWNSIGNAL_shift]! = EMPTY_VALUE && xCustom_SIGNAL_BUY_buffer [OWNSIGNAL_shift]> 0) sig = 1; else if (xCustom_SIGNAL_SELL_buffer [OWNSIGNAL_shift]! = EMPTY_VALUE && xCustom_SIGNAL_SELL_buffer [OWNSIGNAL_shift]> 0) sig = -1;

IndSigToTrade

Selection of the indicator and signal for opening the first and main positions.
Strategy number from custom indicator SignalNameIndicator

If the specified strategy is not found in the indicator, the Expert Advisor will be unloaded from the chart with an error!

If 0 is specified, then strategy signals are not used but filters are used!

TF_IndSigToTrade1 Timeframe for 1 main indicator. You can select the timeframe by which the indicator will receive signals.
Period_Current - current Timeframe
SIGNALStrategyInputs

External parameters for custom indicator, in SignalTypeIndicator = xArrow mode

You can specify the external variables of the indicator as they are written in the settings table , separated by commas!

Important: You must respect the order of variables and the type of variables.

Variable type Record Important Example
int x  

one

ten

777

double xx Be sure to specify through the point.

0.2

1.10

string "x" Be sure to specify the string (not numbers), you can simply write as "X"

In MT5: Be sure to specify the string (not numbers). You can write as "X"

In MT4: Attention! In the version for MetaTrader4, it is forbidden to transfer string parameters! When passing string parameters, the indicator may not load correctly!

 


"XXX"

"TEST SAME"

datetime D'year.month.day ' Mandatory indication of D and single quotes

D'2018.11.08 '

D'2015.01.01 '

color C'red / green / blue ' Mandatory indication of C and single quotes. Color enumeration through slash /

C'0 / 128/128 '

C'0 / 256/0 '

eg

input int InpCCIPeriod = 1;
input double InpCCIPeriod2 = 2.0;
input color InpCCIPeriod3 = clrGreen;
input string InpCCIPeriod6 = "text";
input datetime InpCCIPeriod4 = 2018.11.08;
input bool InpCCIPeriod5 = false;

written as:

SIGNALStrategyInputs = 1,2.0, C'0 / 128/0 ', "text ", D'2018.11.08', false


Signal_Reverse Reverse signals from this indicator. This option reverses the signals of the main indicator only.
ClosePositionifChangeOWNSignal Enable \ Disable closing of positions on the opposite signal of the main indicator, without the participation of other filters and other parameters
OWNSIGNAL_shift The bar number for the signal that the indicator will generate, 
1 = Last closed bar, signals on such a bar are considered complete.
0 = Current open bar, signals on such a bar are considered to be drawing.

SignalBuferforBUY

SignalBuferforSELL

Buffer number in custom indicator, for receiving a signal to BUY and SELL

Do not change for Ind - The xCustomEA and Ind - The xCustomEA Example TheX

Close options  
CloseNameIndicator

The name of the custom indicator from which the main signals for closing positions will be received.

CloseTypeIndicator

The type of indicator for signals.

There are two types of work advisor:

xCustomEA- Advisor's work on our indicator, in which you personally program your strategy.

xArrow- The EA worksdirectly with a custom indicator that has Arrow type buffers that can be used for the EA.

For example: Buffer with indicator signals for closing BUY and Buffer with indicator signals for closing SELL

Such buffers must be of the Arrow type.

Our Expert Advisor determines the signal by type: The buffer value is not equal to an empty value and above 0 .:

// --- we check the conditions and set the value for sig if (xCustom_SIGNAL_BUY_buffer [OWNSIGNAL_shift]! = EMPTY_VALUE && xCustom_SIGNAL_BUY_buffer [OWNSIGNAL_shift]> 0) sig = 1; else if (xCustom_SIGNAL_SELL_buffer [OWNSIGNAL_shift]! = EMPTY_VALUE && xCustom_SIGNAL_SELL_buffer [OWNSIGNAL_shift]> 0) sig = -1;

CloseTimeFrame  
Close_shift  
CloseStrategyInputs  
CloseBuferforBUY  
CloseBuferforSELL  
Close_IndSigToClose  
   
Filter options
FilterNameIndicator

The name of the custom indicator from which the filters will be obtained when opening positions.

Default: " Ind - The xCustomEA "

This is a standard empty indicator, into which you can program your strategy according to our example!

We also created an example of a custom indicator by filters. The X

"Ind - The xCustomEA Example TheX"

FilterTypeIndicator

The type of indicator for the filter.

There are two types of work advisor:

xCustomEA - Advisor's work on our indicator, in which you personally program your filter strategy.

xArrow - Expert Advisor working directly with a custom indicator that has Arrow type buffers (Arrow) or a non-empty buffer value that can be used for the advisor.

For example: Buffer with indicator filter on BUY and Buffer with indicator filter on SELL

Such buffers must be of the Arrow type.

Our Expert Advisor defines a filter by type: The buffer value is not equal to an empty value and above 0 .:

// --- we check the conditions and set the value for sig if (xCustom_FILTER_BUY_buffer [shift]! = EMPTY_VALUE && xCustom_FILTER_BUY_buffer [shift]> 0) sig = 1; else if (xCustom_FILTER_SELL_buffer [shift]! = EMPTY_VALUE && xCustom_FILTER_SELL_buffer [shift]> 0) sig = -1;

FILTER_IndSigToTrade

Selecting the indicator and filter to filter the main signal.
Strategy number from custom indicator FilterNameIndicator

If the specified strategy is not found in the indicator, the Expert Advisor will be unloaded from the chart with an error!

If IndSigToTrade is set to 0, then the adviser will work on filters!

FILTER_TF_IndSigToTrade The timeframe for the filter. You can choose the timeframe according to which the indicator will receive filter signals.
Period_Current - current timeframe.
For example: When using MA as the main signal with TF = M30, you can turn on filtering by older MA with TF = H4
Filter_Reverse Flip the signals of this filter. This option reverses the signals of this filter only.
For example: The main indicator of MA shows BUY, but the senior indicator of MA shows SELL. Using this function, we turn over the signals of the senior MA and get the cumulative signal BUY
FILTERSIGNAL_shift The bar number for the signal that the indicator will generate,
1 = Last closed bar, signals on such a bar are considered complete.
0 = Current open bar, signals on such a bar are considered to be drawing.

FilterBuferforBUY

FilterBuferforSELL

Buffer number in custom indicator, to get the filter on BUY and SELL

Do not change for Ind - The xCustomEA and Ind - The xCustomEA Example TheX

SLTP options  
SLTPNameIndicator

The name of the custom indicator from which Stop Loss and Take Profit will be obtained.

SLTPTypeIndicator

Type of indicator.

xPrice- Price value that will be passed to the corresponding variable (Stop Loss, Take Profit)

SLTPTimeFrame  
SLTP_shift  
SLTPStrategyInputs  
SLTPBuferforBUY_StopLoss The buffer number to get the StopLoss value for BUY, -1 means that this option does not work.
SLTPBuferforSELL_StopLoss The buffer number to get the StopLoss value for the SELL positions, -1 means that this option does not work.
SLTPBuferforBUY_TakeProfit The buffer number to get the TakeProfit value for BUY, -1 means that this option does not work.
SLTPBuferforSELL_TakeProfit The buffer number to get the TakeProfit value for SELL positions, -1 means that this option does not work.

Signal and Filter Definition

Signal

  1. Signal - occurs when there are all conditions for the signal, for example, the fact of crossing the MA lines. Or the appearance of a new point ZigZag.
  2. For example: The intersection of level 70 for the RSI indicator is a signal. And if the RSI is above level 70, then this is already a filter.
  3. The signal - this is what appears at the moment of receipt of quotations, is fixed on the bar. Advisor accepts the fact of making a signal.
  4. For example : Turned on the light. This is a signal because the light has just turned on. When you turn on the light, the man woke up. This is a signal.
  5. Opening positions occurs after the signal is made, the lines are crossed, then the position is opened. If the lines were crossed before, this is not a signal. The signal has passed.

Filter :

  1. Filter - This is the current position of the indicator, for example, the current position of the MA lines relative to each other. Or current last vertex ZIGZAG
  2. The filter is what the indicator is currently showing. This is not a signal fact. This is the current position of the indicator.
  3. For example : The light was burning. This is a filter because the light has already been turned on and it is already on. When the light is on, the person is no longer asleep. This is a filter.
  4. The signals are filtered by the current value of the indicator. If Fast MA is above a slow MA, then this is a filter that only BUY should open.


 

PipFinite example


 

Location of files and folders

If you buy our advisor in the Market mql5.com then our advisor is installed in the Experts folder.

For the advisor to work, you need to download indicators and examples of strategies from our site.

The location of our main indicator in the Indicators folder

Example of the location of files for the MQL5 terminal

  1. \ MQL5
  2. i \ Experts
  3. and Exp5 - The xCustomEA 20180929 DEMO.ex5
  4. i \ Indicators
  5. і і Ind - The xCustomEA Example TheX.ex5
  6. і і Ind - The xCustomEA Example TheX.mq5
  7. і і Ind - The xCustomEA PipFinite Trend PRO.ex5
  8. і і Ind - The xCustomEA PipFinite Trend PRO.mq5
  9. і і Ind - The xCustomEA.ex5
  10. і і Ind - The xCustomEA.mq5
  11. i \ Presets
  12. i Ind - The xCustomEA PipFinite Trend PRO CLEAN.set
  13. i Ind - The xCustomEA PipFinite Trend PRO.set
  14. i MT5 PipFinite Trend PRO MT5.set

 

Example of the location of files for the MQL4 terminal

  1. \ MQL4
  2. i \ Experts
  3. і і Exp4 - The xCustomEA 20180929 DEMO.ex4
  4. i \ Indicators
  5. і і Ind - The xCustomEA Example TheX.ex4
  6. і і Ind - The xCustomEA Example TheX.mq4
  7. і і Ind - The xCustomEA PipFinite Trend PRO.ex4
  8. і і Ind - The xCustomEA PipFinite Trend PRO.mq4
  9. і і Ind - The xCustomEA.ex4
  10. і і Ind - The xCustomEA.mq4
  11. i \ Presets
  12. i Ind - The xCustomEA PipFinite Trend PRO MT4 CLEAN .set
  13. i MT4 PipFinite Trend PRO.set

Indicator template file

For ease of use advisor:

When you first start the advisor, an indicator template file will be created in the folder of your terminal Files

This file can be used as a template for writing an indicator strategy.

In order to find a file, click in your terminal menu File - Open data directory


Open this file with your compiler

In the file you will see examples of the use and steps of programming a strategy.

After creating an indicator strategy, save this file in your terminal folder - Indicators /

After that, specify this file in the settings of the SignalNameIndicator advisor


 

Easy installation of custom indicator in signals and filters

There are two types of work advisor:

xCustomEA - Advisor's work on our indicator, in which you personally program your strategy.

If you need to program the work of the advisor on the indicator, go to the next section: Programming your strategy

xArrow - The EA works directly with a custom indicator that has Arrow type buffers that can be used for the EA.

For example: Buffer with indicator signals to BUY and Buffer with indicator signals to SELL

Such buffers must be of the Arrow type.

Our Expert Advisor determines the signal by type: The buffer value is not equal to an empty value and above 0 .:

 // --- we check the conditions and set the value for sig
 if (xCustom_SIGNAL_BUY_buffer [OWNSIGNAL_shift]! = EMPTY_VALUE && xCustom_SIGNAL_BUY_buffer [OWNSIGNAL_shift]> 0)
 sig = 1;
 else
 if (xCustom_SIGNAL_SELL_buffer [OWNSIGNAL_shift]! = EMPTY_VALUE && xCustom_SIGNAL_SELL_buffer [OWNSIGNAL_shift]> 0)
 sig = -1; 

 

If you do not want to program your strategy and your custom indicator allows you to work directly with the advisor, you can specify the name of the indicator and set buffers for its work on the signals on BUY and SELL

for example :

1. Indicate the name of the custom indicator! If this indicator was downloaded from the MQL5 market, then you need to specify from the Market folder:

Market \\ PipFinite Trend PRO

Be sure to write a double backslash \\

2. Specify the type of xArrow signals .

3. Specify the number of signal buffer for opening BUY (in this example, buffer number 8)

4. Specify the number of signal buffer for opening SELL (in this example, buffer number 9)

Thus, we do not need to program our indicator for the work of the advisor.

Our example of a custom indicator contains buffers for the work of the adviser and we can directly interact with it!

In our section The xCustomEA Strategy Examples we will post examples of programming strategies and advisers on indicators known in the market!

Programming your strategy

You should know the minimum programming rules in order to write your strategy Or add a ready-made strategy on indicators from a ready-made file (indicators from the Internet, for example)

Programming advisors for MetaTrader 5 is more difficult than programming for MetaTrader 4. But the MT5 terminal allows you to create more powerful strategies, and also has a more advanced strategy tester.

For ease of programming

  1. Open our indicator source code Ind - The xCustomEA or Ind - The xCustomEA Example TheX ,;
  2. Press the key combination Ctrl + F and you will see the search bar;
  3. Enter the name Step - For this word, in our source code, you can navigate and quickly write your strategy.
  4. Each step is commented and contains an example.
  5. In order to learn how to program your strategy, you can gradually uncomment the lines with an asterisk // *

We will analyze each step in detail!

MetaTrader 4 Programming your strategy using a custom indicator in MT4

Programming an advisor on the indicator in MT4 consists of 4 steps:

MetaTrader 4 Step 1: Step of loading indicators into resources!

 // Step 1 ####################################################################
// Эта часть кода для программирования своей стратегии в открытом коде
// This part of the code for programming your strategy in open source
// 
// Для того,чтобы при компиляции, индикатор был встроен в советник, Вам необходимо загрузить его в ресурсы советника
// In order for the indicator to be built into the Expert Advisor during compilation, you need to load it into the resources of the Expert Advisor
// ####################################################################
// for example:
//* #resource "\\Indicators\\MACD.ex4"
// ########################################################################### 

Here we are obliged to add the indicators we need to resources.

This will allow to compile the indicator for the market, as well as relieve us of unnecessary problems when the compiled adviser does not suddenly find the indicator on the other computer!

Rules for writing the name of the market: The full name of the folders, starting with Indicators!

Folder denoted by \\

For example:

If the path to your indicator looks like this:

C: \ ROBO MT4 \ MQL4 \ Indicators \ Examples \ MACD.ex4

then the path to this indicator in the programming language is written as:

"\\ Indicators \\ Examples \\ MACD.ex4"

MetaTrader 4 Step 2: The main step of creating strategies and signals for opening positions!

 // Step 2 ####################################################################
// Эта часть кода для программирования своей стратегии в открытом коде
// This part of the code for programming your strategy in open source
// 
// Здесь создаем наш сигнал для открытия позиций. Заполняем буферы данных
// Here we create our signal for opening positions. Fill in the data buffer
// ####################################################################
// for example:
//*   if(sigInd==1)
//*     {
//      
//      Заполняем данные, 
//      We fill in the data
//      
//
//*   double CustomMain=iCustom(StrategySymbol,StrategyTimeFrame,"::Indicators\\MACD",periodma1,periodma2,9,MAprice,
//*                             MODE_MAIN,StartCopyI+ShiftIndicator);
//*   double CustomSig=iCustom(StrategySymbol,StrategyTimeFrame,"::Indicators\\MACD",periodma1,periodma2,9,MAprice,
//*                            MODE_SIGNAL,StartCopyI+ShiftIndicator);
//
//*   double CustomMain2=iCustom(StrategySymbol,StrategyTimeFrame,"::Indicators\\MACD",periodma1,periodma2,9,MAprice,
//*                              MODE_MAIN,StartCopyI+ShiftIndicator+1);
//*   double CustomSig2=iCustom(StrategySymbol,StrategyTimeFrame,"::Indicators\\MACD",periodma1,periodma2,9,MAprice,
//*                             MODE_SIGNAL,StartCopyI+ShiftIndicator+1);
//
//
//      Здесь пишем нашу стратегию, в данном примере это пересечение двух линий, 
//      Here we write our strategy, in this example it is the intersection of two lines
//      
//*   if(CustomMain>CustomSig && CustomMain2<CustomSig2)
//      // Buy sig
//*      sig=1;
//*   if(CustomMain<CustomSig && CustomMain2>CustomSig2)
//      // Sell sig
//*      sig=-1;//      
//      Записываем данные, которые будут отображаться в журнале, при открытии позиций по сигналу 
//      We write down the data that will be displayed in the log, when you open positions on a signal
//      
//*   InfoAboutSignal=" InfoAboutSignal sigInd="+(string)sigInd+" sig="+(string)sig
//*                   +" CustomMain="+CustomMain
//*                   +" CustomSig="+CustomSig
//*                   +" CustomMain2="+CustomMain2
//*                   +" CustomSig2="+CustomSig2
//*                   ;
//      //--- возвращаем торговый сигнал
//*                      return(sig);

//*     }
Этот шаг очень важен для советника. Хотя и все о

Steel steps are required, otherwise the adviser will not work.

I have indicated my comments in the code!

  1. Programming code for strategy and signal individually. Depends on the chosen strategy and indicators. Getting buffers, strategies ........
  2. I want to note only that in this block you can specify any strategy.

  1. 1. Programming strategy. In this case, the intersection of two lines.
  2. Important: The signal for BUY is 1, and for SELL it is -1

Examples of strategies I will post on our forum!

MetaTrader 4 Step 3: Step for specifying filters from your indicators, or using your indicator as a filter for a strategy!

 // Step 3 ####################################################################
// Эта часть кода для программирования своей стратегии в открытом коде
// This part of the code for programming your strategy in open source
// 
// Здесь создаем наш фильтр для фильтрации сигналов. Заполняем буферы данных
// Here we create our filter for signal filtering. Fill in the data buffers
// ####################################################################
// for example:
//*   if(sigInd==1)
//*     {
//      
//      Заполняем данные, 
//      We fill in the data
//      
//
//*   double CustomMain=iCustom(StrategySymbol,StrategyTimeFrame,"::Indicators\\MACD",periodma1,periodma2,9,MAprice,
//*                             MODE_MAIN,shift);
//*   double CustomSig=iCustom(StrategySymbol,StrategyTimeFrame,"::Indicators\\MACD",periodma1,periodma2,9,MAprice,
//*                            MODE_SIGNAL,shift);
//
//      Здесь пишем нашу стратегию, в данном примере это пересечение двух линий, 
//      Here we write our strategy, in this example it is the intersection of two lines
//      
//*   if(CustomMain>CustomSig )
//      // Buy sig
//*      sig=1;
//*   if(CustomMain<CustomSig )
//      // Sell sig
//*      sig=-1;//      
//      Записываем данные, которые будут отображаться в журнале, при открытии позиций по сигналу 
//      We write down the data that will be displayed in the log, when you open positions on a signal
//      
//*   InfoAboutSignal=" InfoAboutSignal sigInd="+(string)sigInd+" sig="+(string)sig
//*                   +" CustomMain="+CustomMain
//*                   +" CustomSig="+CustomSig

//*                   ;
//      //--- возвращаем торговый сигнал
//*                       return(sig);

//*     } 

There is nothing complicated in programming the code in this step and it is similar to the previous step.

The only difference is that at this step you are programming your indicators as a Filter.

You can not specify the signals on the indicator, and specify only the filter. Or vice versa! It all depends on the strategy.

MetaTrader 5 Programming your strategy on a custom indicator in MT5 

MetaTrader 5 Step 1: Step of loading indicators into resources!

 // Step 1 ####################################################################
// Эта часть кода для программирования своей стратегии в открытом коде
// This part of the code for programming your strategy in open source
// 
// Для того,чтобы при компиляции, индикатор был встроен в советник, Вам необходимо загрузить его в ресурсы советника
// In order for the indicator to be built into the Expert Advisor during compilation, you need to load it into the resources of the Expert Advisor
// ####################################################################
// for example:
//* #resource "\\Indicators\\Examples\\MACD.ex5"
// ########################################################################### 

Here we are obliged to add the indicators we need to resources.

This will allow us to compile the advisor for the market, and also relieve us of unnecessary problems when the compiled adviser does not suddenly find the right indicator on another computer!

Rules for writing the name of the market: The full name of the folders, starting with Indicators!

Folder denoted by \\

For example:

If the path to your indicator looks like this:

C: \ ROBO MT5 \ MQL5 \ Indicators \ Examples \ MACD.ex5

then the path to this indicator in the programming language is written as:

"\\ Indicators \\ Examples \\ MACD.ex5"

MetaTrader 5 Step 2: Step of declaring variables for storing the handles of strategy indicators!

 // Step 2 ####################################################################
// Эта часть кода для программирования своей стратегии в открытом коде
// This part of the code for programming your strategy in open source
// 
// обьявите переменную массива хендлов
// Declare the variable of the handle array
// ####################################################################
// for example:
//* int h_custom;
//* int h_custom2;
// ########################################################################### 

Here we simply indicate the names of our handles that were created above!

There is nothing difficult here.

Handles are created in the form of arrays in order to use multicurrency in the advisor and use the ability to specify 6 signals or filters at once!

MetaTrader 5 Step 3: Variable declaration step for storing indicator data!

 // Step 3 ####################################################################
// Эта часть кода для программирования своей стратегии в открытом коде
// This part of the code for programming your strategy in open source
// 
// обьявите переменную массива значений индикатора
// Declare the variable of the handle array
// ####################################################################
// for example:
//* double custom1_buffer[];
//* double custom2_buffer[];
// ########################################################################### 

Here we just specify the names of our data for buffers!

There is nothing difficult here.

The data on the indicator values on each bar will be stored in these arrays. If you need to use multiple buffers, you can use multiple variables.

In our case, for example, we need 2 buffers, for the signal and main lines of the MACD indicator

MetaTrader 5 Step 4: Step of creating handles of indicators for downloading to the advisor!

 // Step 4 ####################################################################
      // Эта часть кода для программирования своей стратегии в открытом коде
      // This part of the code for programming your strategy in open source
      // 
      // Вам необходимо создать запись в массиве для того, чтобы советник присвоил хендл индикатора при инициализации
      // You need to create an entry in the array in order for the Expert Advisor to assign an indicator handle when initializing
      // ####################################################################
      // for example:
      //* case 1:h_custom=iCustom(StrategySymbolString,StrategyTimeFrame,"::Indicators\\Examples\\Moving Average\\Moving Average",MAFastPeriod,MAmethod,MAprice);
      //* h_custom2=iCustom(StrategySymbolString,StrategyTimeFrame,"::Indicators\\Examples\\Moving Average\\Moving Average",MASlowPeriod,MAmethod,MAprice);
      //*            if(h_custom==INVALID_HANDLE)
      //*              {
      //*               Print(" Не удалось получить хендл индикатора Moving Average");
      //*               return(INIT_FAILED);
      //*              }
      //* if(h_custom2==INVALID_HANDLE)
      //*              {
      //*               Print(" Не удалось получить хендл индикатора Moving Average");
      //*               return(INIT_FAILED);
      //*              }
      //*            break;
      // ########################################################################### 

This step is needed in order for our indicators to load 1 time during the initialization of the advisor. In MetaTrader 5, it is not necessary to constantly load the indicator on the chart.

When creating a handle, we remember the handle of an already open indicator and use it for further work.

Here you need to be very attentive. When creating a handle, we must specify all external variables of the indicator and specify the correct name, otherwise the adviser will not be able to load the indicator.

Remember that we uploaded the indicator to the resources of the advisor. Therefore, we will call the indicator from resources!

You can read help on calling indicators via iCustom

We also need the strategy number to write this code. If you have several indicators in one strategy, then you need to specify several indicators but with the same number. That the adviser correctly loaded your strategy.

In our examples above, we need to do this:

 case 1 :
      h_custom= iCustom (StrategySymbolString,StrategyTimeFrame, "::Indicators\\Examples\\Moving Average\\Moving Average" );
      h_custom2= iCustom (StrategySymbolString,StrategyTimeFrame, "::Indicators\\Examples\\Moving Average\\Moving Average" );
      if (h_custom== INVALID_HANDLE )
        {
         Print ( " Не удалось получить хендл индикатора Moving Average" );
         return ;
        }
      if (h_custom2== INVALID_HANDLE )
        {
         Print ( " Не удалось получить хендл индикатора Moving Average" );
         return ;
        }
      break ;

By analogy above, you can add several indicators and handles.

Also with other strategies that you want to insert into the adviser!

MetaTrader 5 Step 5: The main step of creating strategies and signals for opening positions!

 // Step 5 ####################################################################
// Эта часть кода для программирования своей стратегии в открытом коде
// This part of the code for programming your strategy in open source
// 
// Здесь создаем наш сигнал для открытия позиций. Заполняем буферы данных
// Here we create our signal for opening positions. Fill in the data buffer
// ####################################################################
// for example:
//*   if(sigInd==1)
//*     {
//      
//      Заполняем данные, 
//      We fill in the data
//      
//*      if(CopyBuffer(h_custom,0,0,3+ShiftIndicator,custom1_buffer)<3+ShiftIndicator) 
//*         return(0);
//*      if(!ArraySetAsSeries(custom1_buffer,true))
//*         return(0);
//*      if(CopyBuffer(h_custom2,0,0,2+ShiftIndicator,custom2_buffer)<2+ShiftIndicator) 
//*         return(0);
//*      if(!ArraySetAsSeries(custom2_buffer,true))
//*         return(0);
//      
//      Здесь пишем нашу стратегию, в данном примере это пересечение двух линий, 
//      Here we write our strategy, in this example it is the intersection of two lines
//      
//*      if(custom1_buffer[ShiftIndicator+1]<custom2_buffer[ShiftIndicator+1] && custom1_buffer[ShiftIndicator]>custom2_buffer[ShiftIndicator])
//*         sig=1;
//*      else if(custom1_buffer[ShiftIndicator+1]>custom2_buffer[ShiftIndicator+1] && custom1_buffer[ShiftIndicator]<custom2_buffer[ShiftIndicator])
//*         sig=-1;
//*      else sig=0;
//      
//      Записываем данные, которые будут отображаться в журнале, при открытии позиций по сигналу 
//      We write down the data that will be displayed in the log, when you open positions on a signal
//      
//*      InfoAboutSignal=InfoAboutSignal+" "+"sigInd="+(string)sigInd+" TF="+(string)TF+" Symbol="+symToWork3+" sig="+(string)sig+" "+__FUNCTION__+" "
//*                      +" custom1_buffer[ShiftIndicator+1]="+(string)custom1_buffer[ShiftIndicator+1]
//*                      +" custom2_buffer[ShiftIndicator+1]="+(string)custom2_buffer[ShiftIndicator+1]
//*                      +" custom1_buffer[ShiftIndicator]="+(string)custom1_buffer[ShiftIndicator]
//*                      +" custom2_buffer[ShiftIndicator]="+(string)custom2_buffer[ShiftIndicator];
//      //--- возвращаем торговый сигнал
//*      return(sig);
//*     }
// ########################################################################### 

This step is very important for the adviser. Although all other steps are required, otherwise the adviser will not work.

I have indicated my comments in the code!

Our strategy number is the same as in the first steps!

  1. Programming code for strategy and signal individually. Depends on the chosen strategy and indicators. Getting buffers, strategies ........
  2. I want to note only that in this block you can specify any strategy.
  3. All indicators that we declared in handles will be loaded into memory and used to build a strategy.

This step can be divided into 2 substeps:

  1. 1. We must copy the data buffers into our data arrays. In the copy settings, we must specify the line numbers (In our case, these are the MACD indicator lines)
  2. We use two lines MAIN and SIGNAL
  3. You can read the CopyBuffer help.
  4. 2. Programming strategy. In this case, the intersection of two lines.
  5. Important: The signal for BUY is 1, and for SELL it is -1

MetaTrader 5 Step 6: Step for specifying filters from your indicators, or using your indicator as a filter for a strategy!

 // Step 6 ####################################################################
// Эта часть кода для программирования своей стратегии в открытом коде
// This part of the code for programming your strategy in open source
// 
// Здесь создаем наш фильтр для фильтрации сигналов. Заполняем буферы данных
// Here we create our filter for signal filtering. Fill in the data buffers
// ####################################################################
// for example:
//*   if(sigInd==1)
//*     {
//      
//      Заполняем данные, 
//      We fill in the data
//      
//*      if(CopyBuffer(h_custom,0,0,3+ShiftIndicator,custom1_buffer)<3+ShiftIndicator) 
//*         return(0);
//*      if(!ArraySetAsSeries(custom1_buffer,true))
//*         return(0);
//*      if(CopyBuffer(h_custom2,0,0,2+ShiftIndicator,custom2_buffer)<2+ShiftIndicator) 
//*         return(0);
//*      if(!ArraySetAsSeries(custom2_buffer,true))
//*         return(0);
//      
//      Здесь пишем нашу стратегию, в данном примере это пересечение двух линий, 
//      Here we write our strategy, in this example it is the intersection of two lines
//      
//*      if(custom1_buffer[ShiftIndicator]!=0 && custom2_buffer[ShiftIndicator]!=0)
//*      {
//*       Alert(" Поздравляем! Вы сделали урок, который показывает программирование своей стратегии!");
//*       Alert(" Congratulations! You have done a lesson that shows the programming of your strategy!");
//*      }

//*      if(custom1_buffer[ShiftIndicator]>custom2_buffer[ShiftIndicator])
//*         sig=1;
//*      else if( custom1_buffer[ShiftIndicator]<custom2_buffer[ShiftIndicator])
//*         sig=-1;
//*      else sig=0;
//      
//      Записываем данные, которые будут отображаться в журнале, при открытии позиций по сигналу 
//      We write down the data that will be displayed in the log, when you open positions on a signal
//      
//*      InfoAboutSignal=InfoAboutSignal+" "+"sigInd="+(string)sigInd+" TF="+(string)TF+" Symbol="+symToWork3+" sig="+(string)sig+" "+__FUNCTION__+" "
//*                      +" custom1_buffer[ShiftIndicator+1]="+(string)custom1_buffer[ShiftIndicator+1]
//*                      +" custom2_buffer[ShiftIndicator+1]="+(string)custom2_buffer[ShiftIndicator+1]
//*                      +" custom1_buffer[ShiftIndicator]="+(string)custom1_buffer[ShiftIndicator]
//*                      +" custom2_buffer[ShiftIndicator]="+(string)custom2_buffer[ShiftIndicator];
//      //--- возвращаем торговый сигнал
//*      return(sig);
//*     } 

There is nothing complicated in programming the code in this step and it is similar to the previous step.

The only difference is that at this step you are programming your indicators as a Filter.

You can not specify the signals on the indicator, and specify only the filter. Or vice versa! It all depends on the strategy.




Share it with friends: