Independent modification of programs for MetaTrader4 (part 1)

В процессе повседневной торговли большинство из нас регулярно сталкивается с различными программами, написанными для терминала MetaTrader 4. Скрипты, indicators, советники – их суть – помочь нам принять решение о выставлении или закрытии ордера (а то и вообще полностью автоматизировать этот процесс). 90% времени они работают абсолютно нормально, и нас это устраивает. Однако в оставшиеся 10% возникают ситуации, когда программы не передают полностью ситуацию на рынке. В такие моменты возникает непреодолимое желание заняться их оптимизацией (читай – улучшением): добавить новое условие входа или выхода, немного подправить поведение, в конце концов, просто вывести предупреждающее сообщение – вот лишь некоторые примеры из большого числа тех различных мелких правок, которые иногда так хочется (или даже необходимо) внести.

metatrader 4

It's not as complicated as it seems

However, most traders are completely unfamiliar with programming. They often think that it is a complex and completely impossible skill, learning which will require a lot of effort and money, and the return on it will not bring the desired benefits. As a result, they are forced to outsource (paying money for it, of course), on forums (where often novice programmers instead of competent modification only add another "crutch", which sooner or later will lead to the drain of the entire deposit), or simply give up the idea of changing something.

Well, I will not dissuade you. I'll tell you right away: programming in general is a very complicated science, and writing something like MS Word, let alone MS Windows, is a difficult task for a large team of developers, requiring a huge number of man-hours of experienced programmers. However большинство программ для MT4 не настолько сложныand one, even a novice programmer, can easily understand them.

To develop programs for the MetaTrader 4 terminal, an application called средой разработки, MetaEditor. You can run it either from the terminal folder or by clicking the yellow exclamation mark icon on the MetaTrader 4 toolbar. In order to transfer your thoughts to the computer (i.e. to write a program), a special language called programming language is used. In the MetaTrader 4 terminal it is MQL4. It is a C-like functional compilable language.

Let's break down a bit more in detail what all these words mean. "C-like" means that it is very similar to the C programming language (not to be confused with C++), invented by Dennis Ritchie and Ken Thompson in 1969 - 1973. For novice programmers, though, it's more of an entertaining fact than some sort of instruction manual. "Functional" means that. It is based on the principle of dividing the task into subtasksand this division is realized through a special language construct called "function". However, we will not discuss it within the framework of this paper.

"Compilable"This is probably the most important word for us. It means that after we have written a program, before we can run it, we need to "compile" it, i.e., "compile" it. turn text in a programming language directly into a program. To do this, the "compile" command of the "File" menu item of the MetaEditor program (or just the hot key F5) is used.

Despite the fact that MQL4 language is quite simpleIt is impossible to cover all its possibilities in one article. We will try to concentrate on the basic concepts and ideas. I leave it up to the readers to explore the details.

An important step to understanding the program in MQL 4

So, we have a program that we want to modify. We are already "itching" and want to do something. Where should we start?

First, it's worth making sure the program has a source code. Many programs that you download from the Internet come ready-made (i.e., after compilation), the files with them have a extension ".ex4". Modification of such programs is impossible. Source code files have extension ".mq4"and for most programs they can be found on the Internet. Search Keywords "Program name + sources", "Program name + sources", "Program name + mq4".

For programs included in the MT4 starter kit (i.e. what is available immediately after installation), the sources are already available and can be found in the appropriate subfolders of the installation directory.

Once you have downloaded the source code file, you need to place it in the the right folder. Otherwise it will not be picked up by your terminal. Experts должны располагаться в папке experts, скрипты в папке experts\scripts, а indicators в папке experts\indicators. Папка experts расположена в каталоге установки клиентского терминала.

Having located the file in the right place, you can try to open it in MetaEditor program and compile it. If everything is OK, the compiled program will will be automatically added to your client terminal and will become available, for example, in the "Navigator" window.

Warning! To avoid various conflicts, I recommend renaming files with source code by adding the word "My" to the beginning, for example, "MovingAverage.mq4" to "MyMovingAverage.mq4".

If compilation fails, a message about it will appear in the "Errors" tab of the "Toolbox" window in MetaEditor. The text of the error (or errors) will be written in English, indicating the line where the error occurred.

Once you run it and make sure that everything works as it should, you can proceed to the hard part... And no, it's not fixing the source code. The most difficult thing is to fully, thoroughly understand the algorithm of the program's operation. You should be crystal clear about the principle of how it works, what it does, what its principle steps are.

Например, если мы говорим о MACD, то принципиальные этапы – это расчет скользящего среднего с длинным периодом, расчет скользящего среднего с коротким периодом и построение сигнальной линии. Вы должны отлично понимать, что и на каком этапе происходит.

The study of materials found using the keywords "program name + algorithm" helps a lot.

Understanding the algorithm is one of the most important steps to understanding the program!

Structure of scripts, indicators and Expert Advisors written in MQL 4

Once we've figured out the algorithm - we're faced with the next task - relate the text description to what is written in the programming language. However, this requires at least a rough idea of the program structure. And that is what we will talk about in this section.

There are 3 types of programs for MT4 - Expert Advisors, indicators and scripts. The simplest structure is that of scripts. They have some header information, followed by a start function. It looks like this in the code:

int start()


   And this is where some of the teams are located


When the script is started, the header information is initialized, after which the start function is started. It starts sequential execution of the lines from the first line after the opening curly brace to the closing curly brace (or the function interrupt operator - return(...)).

Expert Advisors and indicators work according to a slightly more complicated scheme. They have three functions - init, deinit and start. They look exactly the same as the script's start function, but they work a bit differently. The init function is called when the program is attached to the chart, here the initial initialization of program resources is usually performed (it is most pronounced in the case of a script), then the start function is called. It is called every time a new tick arrives. This allows dynamically update indicators and Expert Advisors. When the program is disconnected from the graph, the deinit function is called to deinitialize the program. Warning! The init and/or deinit functions may not be present in the program. In this case, it is assumed that they do nothing.

Thus, the structure of the program is already beginning to take some, albeit blurred, shape.

Comments are a sign of a smart programmer

In this article, I would like to touch upon one more topic. A good source code written by competent programmers contains special elements that make it easier to understand what this or that code section does. These elements are called "Comments." They can look two ways:

1). «//» – Двойная наклонная черта. Все, что расположено после нее и до конца строчки считается комментарием

2) «/*» и «*/» – Все, что расположено между этими символами так же считается комментарием. При этом такой комментарий может быть многострочным.


// One-line commentary

/* Multiline

commentary */

In code, comments are usually highlighted in gray.

Comments can contain absolutely any text - it is not compiled and is not included in the resulting program anyway. However a competent commentary always makes it easier to read and understand the program. You will see for yourself that a couple of lines of comments sometimes saves several hours of trying to understand "why this code is needed?".

So rule number 1: when you undertake to modify the program, don't be lazy and put a comment describing what you really want to do. This will greatly simplify your further work with this program!

В the next issue of the magazine we will start to understand the basics of the MQL 4 programming language. Don't miss it!

Leave a Reply

Back to top button