0?(!keyword=+encodeURIComponent($(keyword).value)):)); dexOf(/en/search)

=0)setTimeout(function()document.location.reload(true),10);return false; id=main_search_form method=post

The world around us is changing rapidly, and we try to keep up with it. We do not have time to learn something new, and this is a normal attitude of a normal human being. Traders are people just like everyone else, they want to get maximum results for the minimum of effort. Specially for traders, MetaEditor 5 offers a wonderfulMQL5 Wizard.There are several articles describing how to create an automated trading system using the wizard, including a light versionMQL5 Wizard for Dummiesand a version from developers -MQL5 Wizard: New Version.

It all seems good – a trading robot is created in 5 mouse clicks, you can test it in the Strategy Tester andoptimize the parametersof a trading system, you can let the resulting robot trade on your account without the need to do anything else manually. But the problem arises when the a trader/MQL5 developer wants to create something of his own, something unique which has never been described anywhere, and is going to write his own module of trading signals. The trader opens the MQL5 documentation, gets to the Standard Library, and is horrified to see…

True, the MQL5 Wizard greatly simplifies the creation of Expert Advisors, but first you need to learn what will be used as input for it. Toautomaticallycreate an Expert Advisor using the MQL5 Wizard, make sure that its components adhere to five basic classes of the sectionBase Classes of Expert Advisors:

Here is the whole force of the great and terrible approach that is calledObject-oriented programming(OOP). But dont be afraid, now almost everyone has a cell phone with lots of function, and almost no one knows how it works. We do not need to study all this, we will only discuss some functions of theCExpertSignalclass.

In this article we will go through thestages of creating a module of trading signals, and you will see how to do this without having to learn OOP or the classes. But if you want, you can go a little further then.

We will not alter any existing module of trading signals to our needs, because its the way to get confused. Therefore, we will simply write our own class, but first we will use theNavigatorto create a new folder to store our signals inMQL5/Include/Expert/.

Right-click on the folder we have created, select New File and create a new class for our module of trading signals.

Class Name – the name of the class. This will be a module for generating signals at the intersection of two moving averages, so lets name it MA_Cross.

Click Finish and a draft of our module us ready. Its all east so far. We only need to add theincludedeclaration to the resulting file so that the compiler knows where to find the base class CExpertSignal










Check the resulting class (it must be free ofcompilation errors) and clickF7. There are no errors and we can move on.

Our class is completely empty, it has no errors and we can test it – lets try to create a new Expert Advisor in the MQL5 Wizard based on it. We reach the step of selecting a module of trading signals and see … that our module is not there.

And how can it be there? We do not add any indications for the MQL5 Wizard to understand that our class could be something useful. Lets fix this. If you look at the modules of the standard package, youll see that each of them contains a header at the beginning of the file. This is the handle of the module compiled according to certain rules. And the rules are very simple.

Open, for example, the source code of the module of AMA based trading signals (see the logic description inSignals of the Adaptive Moving Average.) And run the MQL5 Wizard choosing this module. Compare:

The last block in the handle refers to the module parameters, the first line contains the name of the module to be displayed in the MQL5 Wizard. As you can see, there is nothing complicated. Thus, the handle of each module contains the following entries:

– the module name to be shown in the MQL5 Wizard.

Type – the version of the module of signals. It must always be SignalAdvanced.

Name – the name of the module after its is selected in the MQL5 Wizard and is used in comments for describing internal parameters of the generated Expert Advisor (preferably specified).

ShortName – a prefix for automatic naming of external parameters in the generated Expert Advisor (in the form of Signal_ShortName_ParameterName).

Next comes the description of the parameters in the form of Parameter=list_of_values, in which the following is specified (comma-separated):

The name of the function to set the value of the parameter when starting the Expert Advisor.

The default value for the parameter, i.e. the value that will be set to the parameter, if you do not change it in the MQL5 Wizard.

Description of the parameter, which you see when you start the Expert Advisor generated in the MQL5 Wizard.

Now, knowing all this, lets create the handle of our module of trading signals. So, we are writing a module for getting trading signals at the intersection of two moving averages. We need to set at least four external parameters:

FastPeriod – the period of the fast moving average

FastMethod – the type of smoothing of the fast moving average

SlowPeriod – the period of the slow moving average

SlowMethod – the type of smoothing of the slow moving average

You could also add a shift and the type of prices to calculate each of the moving averages, but it does not change anything fundamentally. So the current version is as follows:


// Title=Signals at the intersection of two MAs

// Parameter=FastPeriod,int,13,Period of fast MA

// Parameter=FastMethod,ENUM_MA_METHOD,MODE_SMA,Method of fast MA

// Parameter=SlowPeriod,int,21,Period of slow MA

// Parameter=SlowMethod,ENUM_MA_METHOD,MODE_SMA,Method of slow MA


The module handle is ready, and we have described the following in it:

The name displayed in the MQL5 Wizard – Signals at the intersection of two moving averages.

Four external parameter to configure the trading signals.

FastPeriod – the period of the fast moving average with the default value of 13.

FastMethod – the type of smoothing of the fast moving average, simple smoothing by default.

SlowPeriod – the period of the slow moving average with the default value of 21.

SlowMethod – the type of smoothing of the slow moving average, simple smoothing by default.

Save the changes and compile. There should not be any errors. Run the MQL5 Wizard to check. You see, our module is now available for selection, and it shows all of our parameters!

Now it is time to work with the external parameters. Since our trading module is represented by the class MA_Cross, then its parameters must be stored within the same class asprivatemembers. Lets add four lines (equal to the number of parameters) to the class declaration. Weve already described the parameter in the handle and know the following:

But how do the values ​​of the external parameters of the module appear in theappropriatemembers of our class MA_Cross? Its all very simple, you only need to declare public methodsof the same namein the class, namely, to add four lines to thepublicsection:

When you generate an Expert Advisor on the basis of this module using the MQL5 Wizard and run it on the chart, these four methods are automatically called when initializing the Expert Advisor. So here is a simple rule:

The rule of parameter creation in the module -for each parameter that we have declared in the handle, we should create a private member in the class for storing its value and a public member for setting a value to it. The method name must match the name of the parameter.

And the last moment is to set default values ​​for our parameters that will be used in case the methods of value setting are not called. Each declared variable or class membermust be initialized. This technique allows to avoid many of hard-to-find errors.

For automatic initialization, the best suiting one is the class constructor; it is always the first one to be called when creating an object. For default values, we will use those written in the module handle.



Here the class members are initialized using theinitialization list.

As you can see, we havent used moving average indicators yet. We found a simple rule -as many parameters are stated in the handleof the module, so manymethods and members should be in the classthat implements the module. There is nothing complicated! However, dont forget to set default values of parameters on the constructor.

We have created parameters for our trading module, written methods for setting values ​​to them, and now comes the next important phase – the correctness of parameters must be checked. In our case, we must check the periods of moving averages and the type of smoothing for their calculation. For this purpose you should writeyour ownValidationSettings()method in the class. This method is defined in the parent classCExpertBase, and in all itschildrenit isobligatorilyredefined.

But if you do not know anything about object-oriented programming, just remember – in our class we should write the ValidationSettings() function, which requires no parameters and returns true or false.


// Checks input parameters and returns true if everything is OK


//— Check periods, number of bars for the calculation of the MA =1

Incorrect value set for one of the periods! FastPeriod=%d, SlowPeriod=%d

//— Slow MA period must be greater that the fast MA period

SlowPeriod=%d must be greater than FastPeriod=%d!

//— Fast MA smoothing type must be one of the four values of the enumeration

//— Show MA smoothing type must be one of the four values of the enumeration

//— All checks are completed, everything is ok

As you can see, in the public part of the MA_Cross class weve added declaration of the ValidationSettings() method, and then addedthe method bodyin the following form:

First comes the return type, then the class name, thenscope resolution operator::, and all this is followed by the name of the previously declared method. Do not forget that the name and type of parameters must match in the declaration and description of the class method. However, the compiler will warn you ofsuch an error.

Note that first the base class method is called, and then input parameters are checked.

If you do not add this line, the generated Expert Advisor will not be able to initialize our module of trading signals.

Its time to work with the indicators, since all the preparatory work with the parameters for them have been completed. Each module of trading signals contains theInitIndicators()method, which is automatically called when you run the generated Expert Advisor. In this method, we must provide indicators of moving averages for our module.

First, declare the InitIndicators() method in the class and paste its draft:

//— Creating indicators and timeseries for the module of signals


// Input:a pointer to a collection of indicators

// Output: true if successful, otherwise false


//— Standard check of the collection of indicators for NULL

//— Initializing indicators and timeseries in additional filters

//— Reached this part, so the function was successful, return true

So there is nothing complicated, we declare the method and then simply create the method body, as we havedone for the ValidationSettings() method. Above all, do not forget to insert theclass name and the operator ::in the function definition. We have a draft, which we can insert into a code to create moving averages. Lets do this properly – for each indicator we create a separate function in the class, which returns true if successful. The function can have any name, but let it reflect its purpose, so lets call the functions CreateFastMA() and CreateSlowMA().


// Input:a pointer to a collection of indicators

// Output: true if successful, otherwise false


MA_Cross::InitIndicators(CIndicators *indicators)

//— Standard check of the collection of indicators for NULL

//— Initializing indicators and timeseries in additional filters

//— Reached this part, so the function was successful, return true



MA_Cross::CreateFastMA(CIndicators *indicators)

//— Reached this part, so the function was successful, return true



MA_Cross::CreateSlowMA(CIndicators *indicators)

//— Reached this part, so the function was successful, return true

Thats all, we only need to write code that generates the MA indicators and somehow integrates the handles of these indicators into the trading module, so that the module can use the values ​​of these indicators. That is why a pointer to a variable of typeCIndicatorsis passed as a parameter. The following is written in Documentation about it:

The CIndicators is a class for collecting instances of timeseries and technical indicators classes. The CIndicators class provides creation of instanced of technical indicator classes, their storage and management (data synchronization, handle and memory management).

This means that we must create our indicators and place them in this collection. Since only indicators of theCIndicatorform and its children can be stored in the collection, we should use this fact. We will useCiCustom, which is the above mentioned child. For each moving average we declare an object of type CiCustom in the private part of the class:

Of course, you can create your own indicator class, which will be derived fromCIndicator, and implement all the necessary methods for use with the MQL5 Wizard. But in this case we want to show how you can useany customindicator in the module of trading signals usingCiCustom.



MA_Cross::CreateFastMA(CIndicators *indicators)

: Error initializing the object of the fast MA

//— Reached this part, so the function was successful, return true

In the CreateFastMA() method, first check the pointer of the collection of indicators, and then add a pointer of the fast MA m_fast_ma to this collection. Then declare theMqlParamstructure, which is especially designed for storing parameters of custom indicators, and fill it with values.

We useCustom Moving Averagefrom the standard terminal delivery pack as the custom MA indicator. The name of the indicator must be indicated relative to the folderdata_folder/MQL5/Indicators/. Since Custom Moving Average.mq5 from the standard package is located indata_folder/MQL5/Indicators/Examples/, we specify its path including the Examples folder:

If you look at the code for this indicator, you can see all the required data:

The values ​​of the structure contain the type-value pairs:

the name of the executable file of the custom indicator – Custom Moving Averages.exe

parameter type – int (enumeration value is an integer)

After filling the structure, the indicator is initialized by theCreate()method of all the required parameters: symbol name and the timeframe on which it is calculated, the type of the indicator from theENUM_INDICATORenumeration, the number of indicator parameters and the MqlParam structure with parameter values. And the last one is specifying the number of indicator buffers using theNumBuffers()method.

The CreateSlowMA() method for creating the slow moving average is simple. When using custom indicators in the module, do not forget that the Expert Advisor generated by the MQL5 Wizard will also run in the tester. So at the beginning of our file we add the propertyproperty tester_indicatorthat communicates to the tester the location of required indicators:

If we use several different indicators, we should add this line for each of them. So, we have added the indicators. For more convenience, lets provide two methods of receiving MA values:

As you can see, the methods are very simple, they used theGetData()method of the SIndicator parent class, which returns a value from the specified indicator buffer at the specified position.

If you need classes for working with classical indicators of the standard package, they are available in sectionClasses for working with indicators. We are ready to proceed to the final stage.

6. Define the LongCondition and ShortCondition Methods

Everything is ready to make our module work and generate trading signals. This functionality is provided by two methods that must be described in each child ofCExpertSignal:

If the function returns a null value, it means that there is no trading signal. If there are conditions for the signal, then you can estimate the strength of the signal and return any value not exceeding 100. Evaluation of the signal strength allows you to flexibly build trading systems based on several modules and market models. Read more about this inMQL5 Wizard: New Version.

Since we are writing a simple module of trading signals, we can agree that the buy and sell signals are valued equally (100). Lets add necessary methods in the class declaration.

Also, lets create the description of functions. This is how the buy signal is checked (its all the same with the sell signal):



//— For operation with ticks idx=0, for operation with formed bars idx=1

//— Values of MAs at the last but one formed bar

//—If the fast MA crossed the slow MA from bottom upwards on the last two closed bars

((last_fast_valuelast_slow_value) && (prev_fast_valueprev_slow_value)) signal=

Note that we have declare the idx variable, to which the value returned by theStartIndex()function of the parent class CExpertBase is assigned. TheStartIndex()function returns 0, if the Expert Advisor is designed to work on all ticks, and in this case the analysis starts with the current bar.If the Expert Advisor is designed to work at open prices,StartIndex()returns 1 and the analysis starts with the last formed bar.

By defaultStartIndex() returns 1, which means that theExpert Advisor generated by the MQL5 Wizard will only run at the opening of a new bar and will ignore incoming ticks during formation of the current bar.

How to activate this mode and how it can be used will be described later inthe finishing stroke.

The module is ready for use, so lets create a trading robot in the MQL5 Wizard based on this module.

To test the efficiency of our module, lets generate an Expert Advisor based on it in the MQL5 Wizard and run it on the chart. The Inputs tab of the appeared start window contains the parameters of the MA_Cross module.

All other parameters have also been added by the MQL5 Wizard while generating the EA based on the selected money management module and position maintenance module (Trailing Stop). Thus, we only had to write a module of trading signals and received a ready solution. This is the main advantage of using the MQL5 Wizard!

Now lets test the trading robot in the MetaTrader 5 Strategy Tester. Lets try to run a quick optimization of key parameters.

In these settings of input parameters, more than half a million of passes is required for full optimization. Therefore, we choosefast optimization(genetic algorithm) and additionally utilizeMQL5 Cloud Network to accelerate the optimization. The optimization has been done in 10 minutes and we have got the results.

As you can see, creating a trading robot in MQL5 and optimization of input parameters have taken much less time than would be required for writing the position management servicing logic, debugging and searching for the best algorithms.

You can skip this item or go back to it later when you are completely comfortable with the technique of writing a module of trading signals.

If you open the source code of the Expert Advisor generated by the MQL5 Wizard, you will find theglobal variableExpert_EveryTick with the false value. Based on this variable,the StartIndex() functionreturns its value. It communicates to the Expert Advisor the mode it should run in.





include Expert\MySignals\MA_Cross.mqh

include Expert\Trailing\TrailingNone.mqh

include Expert\Money\MoneyFixedLot.mqh



If you set Expert_EveryTick true and compile the code, the trading robot will analyze each incoming tick, and thus make decisions on the values ​​of the current incomplete bar. Do this only if you understand how it works. Not all trading systems are designed to work inside the bar.

You can also add a keywordinputfor the Expert_EveryTick parameter, and then you will have a newinput parameter of the Expert Advisor, which you can set at the EA startup on a chart or in the tester:

And now its time to summarize what we have done.

If you have mastered MQL5, then you no longer need to write an Expert Advisor from scratch. Just create a module of trading signals and, based on this module, automatically generate a trading robot with the enabled trailing and trade volume management modules. And even if you are not familiar with OOP or do not want to delve much into the structure of trade classes, you can just go through 6 steps:

Createa module handlethat describes the parameters, their type and default values.

Declaremodule parametersin the class and add methods for initialization in the constructor.

Each step is simple and requires little skill in MQL5 programming. You only need to write your module once, following the instructions, and further verification of any trade idea will take no more than an hour, without tiring hours of coding and debugging.

Remember that the trading strategy implemented by your trading robot created using the MQL5 Wizard, is as complex as the module of trading signals it uses. But before you start to build a complex trading system based on a set of rules for entry and exit, split it into several simple systems and check each one separately.

Based on simple modules you can create complex trading strategies using the ready-made modules of trading signals, but this is a topic for another article!

Translated from Russian by MetaQuotes Software Corp.

I do not have any experience (yet) with programming in MQL, but I do have some experience in programming in other languages. One of the easiest errors to make in programming (my specific class was Java, which is very similar in style to C++ and apparently MQL) is not closing the braces properly. It is one of the easiest errors to make, and conversely, also one of the harder ones to find. KJG, as far as the closing a long and heading right into a short, it is probably what this style of EA is designed to do. I have seen many trading styles with just that type of setup, I believe they were designed for a market that has a lot of volatility and wide price swings happening all the time, like something that would likely happen on a minute time frame chart.

Good article as well. I definitely will be making use of this one and many others here I am sure.

I followed the instructions in steps 1 and 2, but the signal doesnt appear in the Wizard list of available signals. I tried with other signals and none works. Maybe theres a limitation in the number of signals that can be displayed in the wizard. Anyone can help?

The different stages of construction are well explained. Its a clear and useful job, especially for those who have never developed a robot. Thank you

My robot dont work very well until yet but it is slowly getting better

I just had to restart MT5 and now my signal appears correctly!!!

Maybe this just worked for me, but hey, if you are into the same situation give it a try. Good luck!

The article is intended to get its readers acquainted with the Box-Cox transformation. The issues concerning its usage are addressed and some examples are given allowing to evaluate the transformation efficiency with random sequences and real quotes.

If we thoroughly examine any complex trading system, we will see that it is based on a set of simple trading signals. Therefore, there is no need for novice developers to start writing complex algorithms immediately. This article provides an example of a trading system that uses semaphore indicators to perform deals.

The technical analysis widely implements the indicators showing the basic quotes more clearly and allowing traders to perform analysis and forecast market prices movement. Its quite obvious that there is no sense in using the indicators, let alone applying them in creation of trading systems, unless we can solve the issues concerning initial quotes transformation and the obtained result credibility. In this article we show that there are serious reasons for such a conclusion.

Take a look at your trading terminal. What means of price presentation can you see? Bars, candlesticks, lines. We are chasing time and prices whereas we only profit from prices. Shall we only give attention to prices when analyzing the market? This article proposes an algorithm and a script for point and figure charting (naughts and crosses) Consideration is given to various price patterns whose practical use is outlined in recommendations provided.