Self-learning the MQL5 language from scratch - page 75

 

Good day and good mood everyone!

I continue studying the MQL5 programming language. I made a small change to Vasiliy Sokolov's code to open only one position per day, as originally intended in the algorithm of the Expert Advisor. The change is highlighted in yellow.

Best regards, Vladimir.

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Зададим условия для открытия позиций BUY и SELL
   double price=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
   double point=SymbolInfoDouble(Symbol(),SYMBOL_POINT);
   int digits=(int)SymbolInfoInteger(Symbol(),SYMBOL_DIGITS);
   price=NormalizeDouble(price,digits);

   if(IsMainPositionOpen() == false && IsTimeForOpen())
     {
      if(TickUP()==(price+point))
         OpenBUY();
      else
        {
         if(TickDOWN()==(price-point))
            OpenSELL();
        }
     }
   if(IsTimeForClose())
      CloseALL();
 
Vasiliy Sokolov:

The OnInit block is also overthought and still not written quite correctly. First of all, you should try to write identifiers, not numbers. Return INIT_SUCCEEDED instead of -1. Second, switch is excessive here. This code should contain either if or switch. First you have to write one and then the other - just oil.

Thirdly, we need to monitor all of the account types. We have Demo and then we have Real. And then there is Contest. But even if there were no third account, there should be a stub that would catch all the other variants:

Probably it would be more reasonable to explain how exceptions work, otherwise there will be no understanding of why there should be any control at all over something you don't know about.

In the most exaggerated sense, it should be as follows:

1. starting a program to run

2. working through the algorithm and exiting from it in two directions:

a) True - the algorithm worked out correctly

b) False - the algorithm has not worked

At the same time, working out on a) means that here are fulfilled all the options that the programmer wants to implement, and on b) all the rest, and it doesn't matter, if it's needed or not. I.e., the programmer implements only that functionality he/she wants and everything else should be excluded.

 
Konstantin:

It probably makes more sense to explain the workings of exceptions, otherwise there is no understanding of why you should even control something you don't know about.

At its most exaggerated, it should be as follows:

1. starting a program to run

2. working through the algorithm and exiting from it in two directions:

a) True - the algorithm worked out correctly

b) False - the algorithm has not worked

At the same time, working out on a) means that here are fulfilled all the options that the programmer wants to implement, and on b) all the rest, and it doesn't matter, if it's needed or not. I.e. the programmer implements only that functionality he or she inserts, and everything else should be thrown out as an exception.

Hello Konstantin! Thank you for your clarification.

Dear participants of this thread! Once again I would like to thank all of you for constructive suggestions and advice that have helped me in learning the MQL5 programming language.

For now I have pause because my main work does not allow me to devote much time and attention to self-study, but for now the main result is achieved - I understand programming basics, read third-party codes and write my own functions.

I will publish the version of Trailing_Stop (v.1).mq5 Expert Advisor with detailed comments on each code line, in a form accessible for a 1st grade student of a programming school, as I promised earlier, but a bit later.

Regards, Vladimir.

 

Good day and good mood everyone!

I continue studying the MQL5 programming language. Finally I have enough time to write a version of the Expert Advisor with detailed comments on each code line, in a form accessible for 1st year students of a programming school. Since the code of the Expert Advisor is quite bulky, I am publishing it as a file called Trailing_Stop_gv.22.mq5.

Before publishing the code, we checked the Expert Advisor in the strategy tester. No problems were found. The netting system of position accounting is used in the Expert Advisor. This system of accounting means that at one point in time on the account, there can be only one open position for one and the same symbol (security).

At this point in time, the Expert Advisor has implemented the ability to:

  1. Check the trading account, on which you plan to install it. If the Expert Advisor will be installed on a demo account, then in the message box will appear permission to continue working. If an attempt is made to install the Expert Advisor to a real account, the message window will show a warning that it cannot continue working, and then it will be automatically deleted from the work window of the trading terminal.
  2. Once a trading day, at 9 am Moscow time sharp, automatically open one position in the direction in which the first tick is directed. For example, if the first tick is directed upwards at 9 a.m. Moscow time, then BUY position will be opened; if the first tick is directed downwards, then SELL position will be opened.
  3. Set the lot size.
  4. Set stop loss size.
  5. Specify the level relative to the opening price, at which the Stop Loss is moved to Breakeven.
  6. Set the trailing step of the stop loss.

This version of the Expert Advisor implements the majority of hints, previously suggested by Vasily Sokolov.

WARNING!!!

This Expert Advisor was developed according to the self-study plan for demo accounts, and it is intended for training purposes only! It is not intended for trading on a real account and making profit!

Sincerely, Vladimir.

Files:
 
MrBrooklin:

Good day and good mood everyone!

I continue studying the MQL5 programming language. Finally I have enough time to write a version of the Expert Advisor with detailed comments on each code line, in a form accessible for 1st year students of a programming school. Since the code of the Expert Advisor is quite cumbersome, I am publishing it as a file called Trailing_Stop (v.2).mq5.

Before publishing the code, we checked the Expert Advisor in the strategy tester. No problems were found. The netting system of position accounting is used in the Expert Advisor. This system of accounting means that at one point in time on the account, there can be only one open position for the same symbol (financial instrument).

At this point in time, the Expert Advisor has implemented the ability to:

  1. Check the trading account, on which you plan to install it. If the Expert Advisor will be installed on a demo account, then in the message box will appear permission to continue working. If an attempt is made to install the Expert Advisor to a real account, the message window will show a warning that it cannot continue working, and then it will be automatically deleted from the work window of the trading terminal.
  2. Once a trading day, at 9 am Moscow time sharp, automatically open one position in the direction in which the first tick is directed. For example, if the first tick is directed upwards at 9 a.m. Moscow time, then BUY position will be opened; if the first tick is directed downwards, then SELL position will be opened.
  3. Set the lot size.
  4. Set stop loss size.
  5. Specify the level relative to the opening price, at which the Stop Loss is moved to Breakeven.
  6. Set the trailing step of the stop loss.

This version of the Expert Advisor implements the majority of hints, previously suggested by Vasily Sokolov.

WARNING!!!

This Expert Advisor was developed according to the self-study plan for demo accounts, and it is intended for training purposes only! It is not intended for trading on a real account and making profit!

Sincerely, Vladimir.

Hello! - It does not compile.

Trailing_Stop_gv.22.mq5

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

figured it out - name without brackets to create Trailing_Stop (v.2) Expert Advisor

 
SanAlex:

Hello! - it doesn't compile.

Hello! Just downloaded the file from the website and checked in my MetaEditor, everything compiles fine.

Regards, Vladimir.

 
MrBrooklin:

Hello! Just downloaded the file from the website and checked in my MetaEditor, everything compiles fine.

Regards, Vladimir.

Thank you! for the work. i did not enter the name correctly when creating the Expert Advisor. everything works.

 
SanAlex:

Thank you! for the work. i didn't enter the name correctly when creating the expert. everything works.

My pleasure!

Regards, Vladimir.

 

Dear participants of this thread!

Once again I would like to thank all of you for your constructive suggestions, tips and advice, which helped me in learning the basics of the MQL5 programming language. Special thanks to Vasily Sokolov! God bless you all!

With great respect to everyone, Vladimir.

 

Good day and good mood everyone!

I continue studying the MQL5 programming language. I am currently writing code for a new EA. I have faced with one point, which I do not fully understand how to solve. The task seems to be simple - I want my Expert Advisor to work on the chart of the currency pair, which is set in the input parameters of the EA. If an attempt is made (eg, by mistake) to install it on the chart of another currency pair, the Expert Advisor should make a warning about the inability to continue work.

Here is the outline of the program code:

input string Symbol_Main="GBPUSDrfd";  //Валютная пара, на которую ставим советник

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   /* Определим график валютной пары, на который будем устанавливать советник*/
   string currency_chart=SymbolInfoString(Symbol(),SYMBOL_DESCRIPTION);
   if(currency_chart==Symbol_Main) //если график валютной пары совпадает со входным параметром
     {
      /* выводим окно сообщений на торговом терминале и продолжаем работу советника */
      MessageBox("Работа советника на данной валютной паре разрешена!");
      return(INIT_SUCCEEDED); //возвращаем для функции OnInit значение означающее "удачная инициализация"
     }
   else //в противном случае, если график валютной пары не совпадает со входным параметром
     {
      /* выводим окно сообщений на торговом терминале и закрываем советник */
      MessageBox("Работа советника на данной валютной паре запрещена! Выходим!");
      return(INIT_FAILED); //возвращаем для функции OnInit значение означающее "неудачная инициализация"
     }
  }

The compiler does not show any errors. The code that does not work is highlighted in yellow. Maybe that's because I don't quite understand the meaning of the SYMBOL_DESCRIPTION identifier - string description of the character. I tried to use other identifiers but the result is the same. Maybe, the SymbolInfoString() function is not needed here at all? I wrote the name of the currency pair GBPUSDrfd only because I plan to use the Expert Advisor on Alpha-Forex, while all symbols of this broker have the ending rfd.

Dear Expert Advisor, please advise me in what direction to think!

Regards, Vladimir.