About coding style - page 2

 

Here you have to choose one of two things:

1) Ease of writing and easy readability of the code.

2) The speed of program execution.

Personally, I have always preferred the second option, so I try to declare all variables globally and, if possible, not to use functions (I noticed its effect on computational speed long ago). You have to realize that the Expert Advisor will run on your computer for 24 hours a day, sometimes it needs optimization and so on. Therefore, the speed of calculations and low consumption of resources are very important.

And now let's look from the outside at different programming languages. For example, Basic is easy to code and easy to read, but the calculation speed... Now let's compare C++ with it. Here the poles have already changed - it's harder to code (code readability has become worse) but calculation speed has greatly risen. And if you take Assembler, the code is nearly unreadable.

Another thing is that it is strange when a program written in the same language also falls under these criteria and must choose - either the readability of code or speed of execution of the program (although there is nothing strange, to declare a variable - time consuming; to call a function and pass parameters to it - time consuming). But it's a fact, which, by the way, was noticed not only in mql4...

 

I prefer the former - perhaps because in MQL4 I haven't yet encountered cases where my calculations are so vast that I have to choose between readability and speed. I'm not playing with ticks, so I don't need any crazy calculation speed.

On the other hand, it's hard to imagine an EA which I don't have to modify later.

 
Mathemat >> :

I don't play ticks.

Here, some features are starting to emerge. I absolutely agree - if you play at opening prices, then program architecture must change. For example, when playing at opening prices it doesn't make sense to declare variables on global level and keep them in memory until the next bar appears.

The coding style of a program must be appropriate for its intended use. Although coding rules are the same everywhere (functions, variables, etc.), the frequency and style of using these rules in the program code depends on the specific end tasks - for what calculations the program will be used. Each case of using coding rules requires a different approach.

 

highly recommended: http://astyle.sourceforge.net/ is a C-text formatter, but does a great job with MQ4.

just one command: AStyle.exe -b -t -p before.mq4 turns "packed" text into candy


 

A similar utility was offered here a long time ago by the forum owners, either here or on metaquotes. But now you don't have to look for it, thanks Sergey. And the design style is the same as I prefer myself.

 

At one time I wondered "which programming style to choose". As I had little experience, I solved the problem simply by opening up the FreeBSD source code and looking closely at what style Old School programmers were using. At the time, some things seemed inconvenient to me, but now I understand why they chose such solutions.

So, here are the rules by which I write:

int main()

{

int sum;

for(int i=0;i<100;i++){

sum+=i;

Print("Число равно:", i);

}

return(0);

}

1. In functions, I always give separate lines for curly brackets. In loops/conditions, I put the first curly bracket in the first line.

2. I hate very common style of putting curly brackets this way:

//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----

//----

return(0);
}
//+------------------------------------------------------------------+

Comments //---- - I don't understand it at all.

3. I try to declare a variable for iterations in the loop itself

4. I like to use functions, I try to divide a program into many parts. But there's no rigid binding of 20 lines per function. I believe that a function must perform a local task. Tasks are sometimes big, sometimes not so big, so the function is different.

5. I use functions within a function:

res=OrderSend(Symbol(),OP_BUY,GetVolume(GetPrice(OP_BUY),GetStopLossLevel(GetPrice(OP_BUY))),GetPrice(OP_BUY),3,GetStopLossLevel(GetPrice(OP_BUY)),GetTakeProfitLevel(GetPrice(OP_BUY)),"",GetMagicNumber(OP_BUY),0,Blue);


6. I use the timing() function:

void Timing()
{
//Здесь вызываем функции которые необходимо вызывать каждый тик
//...
//Здесь вызываем функции которые необходимо вызывать каждую минуту
if(IsNewMinute()==true){
}
//Здесь вызываем вункции которые достаточно вызывать каждый новый бар
if(IsNewBar()==true){
CheckForClosed();
CheckForOpen();
}
//Здесь вызываем функции которые необходимо вызывать каждый новый день, например функцию для расчета свопов
if(IsNewDay()==true){
}
}

As you can see, even with the tickwise modelling method, the whole block of calculations is not set every tick, but is only called when it is really needed.

7. I don't know why, but almost always use the for() loop instead of while().

8. I hate using nested conditions:

if(param1==1){

if(param2==2){

if(param3==3){

if(param4==4){

if(param5==5){

Print("Наконец-то дошли!");

}

}

}

}

}

I use code like this instead:

if(param1!=1)return;

if(param2!=2)return;

...

if(param5!=5)return;

Print("Наконец-то дошли!");

I find this way much more convenient.
 

if(param1!=1)return;

if(param2!=2)return;

...

if(param5!=5)return;

Print("Наконец-то дошли!");

Basically, it's normal code that performs the same calculations as the nested if construction. But somewhere I've heard that return in the function should be one. Probably, it's done in order not to get mixed up in them. I do not strictly follow this rule.

As for the rest my approach is very close to yours, C-4, except for a couple of details.

 
C-4 >> :

2. I hate the very common style of putting braces like this:

//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+

Comments //---- - I don't understand it at all.

I, on the other hand, prefer this style: you don't have to look for curly brackets at the end of a line. Many people lose braces for this very reason (forgetting to put a closing parenthesis), or on the contrary, they make extra closing braces. But in general, it is a matter of taste - everyone has different handwriting on paper. And everyone writes notes differently (someone makes a footnote, someone underlines, someone indents) - the main thing that the author of the notebook was easy to perceive information at a glance. Language syntax allows you to put curly braces anywhere - even in one line. But for some reason no one puts closing curly braces like this:

if( param1==1){

   if( param2==2){

      if( param3==3){

         if( param4==4){

            if( param5==5){

               Print("Наконец-то дошли!");}}}}}
That's why I don't save space for a separate line of code - all brackets (both opening and closing) are on the left side of each other (with indents for every following enclosed block, herringbone style) and at a glance you can estimate the beginning and the end of a compound operator (block), no matter how smart and sophisticated a part of the program it is. :)

--------

After all, brackets are used just to designate a compound operator (block) and not to designate the loop's body. I do not use parentheses where the operator is not compound:
//--Например, так:

if( param5==5) Print("Наконец-то дошли!");


//--Или так:

if( param5==5)
  Print("Наконец-то дошли!");

            

And if you select a compound operator with an opening bracket somewhere on the right, but put closing brackets on the left, then

//---Вот так многие поступают выделяя блок:

if( param5==5){
   Print("Наконец-то дошли!");
}


//--Т.е. блок выделяют вот так:

             {
   Print("Наконец-то дошли!");
}

---------------

How to code, where to put brackets, etc. - is a matter of everyone's taste. The main thing is that the program should be readable, error-free, not load the system (the algorithm must be optimal) and meet the criteria for which it is written.

 
Mathemat >> :

The similar tool was offered here by forum owners long time ago - either here or on metaquotes. But now you don't have to look for it. And the style of design is the same, as I prefer it.

Yeah, there is one. :)


For code cleanup I use MetaQuotes Styler from two files which you can download from this link and place in /Windows/System32 directory.

You can run the styler by the command:

mqstyler.exe /file:filename.mq4
mqstyler.exe /file: "long filename with spaces.mq4" (If there are spaces in the name)

 

I personally take Visual Studio (VC++), copy MQL code there and format it according to Microsoft convention, without tools. As a code editor VS is also cooler (code folding?). It may be possible to screw in a compile command, but I haven't tried it yet.

Reason: