I want to learn the programming language for the MT5 terminal. Where do I start as a beginner ? - page 6

 
Vasiliy Kolesov:

It is not convenient to learn from Kovalev's textbook from scratch, as it is outdated. You start to do some exercises and they don't compile. And simply reading, without practice, makes it harder to remember things.

I don't think we are talking about any simple examples. It's probably already at the end of a textbook. And it is probably a matter of syntax, which, if you understand the basics, is easily corrected. In any case, TC can always ask why this or that example does not compile.

Can you give an example from the tutorial that does not compile? For an example, let's break it down.

 
Ilya Malev:

You were rightly advised to learn C++, because it is MQL, and there are much more materials on C++.

If you know C++, then study MQL from help, parsing other people's EAs.

This is if one plans one's activities outside of MT. But one cannot plan such a thing in advance. Right now the goal is to learn to write for MT. And if a person starts in C or C++, he will be stuck there for such things that are absent in MQL from the beginning. After all, even a simple value printing cannot be done with cout. In this respect MQL is much easier - Print or Alert.

So it's better to start learning what you need. And later, if you like it and want to continue, you can switch to C++.

 

Learn C++ if you are a beginner. Here is a good resourcehttps://foxford.ru/wiki/informatika/otlichiya-yazykov-programmirovaniya-si-i-s

Avoid non-professionals, their language is too dry to remember anything at all. Use mnemonics techniques, there are a lot of books on this topic on the Internet.

Personally, to memorize something, you have to imagine a function, for example, as a real world object, adding more brightness and humor, sex, and surrealism.

 
multiplicator:

it is better to

6 more parameters must be entered in PositionOpen.


The other parameters do not need to be prescribed

 
Ihor Herasko:

These are hardly any simple examples. It is probably already at the end of a textbook. And it is probably about syntax, which, if you understand the basics, can be easily fixed. In any case, TC can always ask why this or that example does not compile.

Can you give an example from the tutorial that does not compile? Let's take an example.

Yes, from the beginning, for example there is no Start function, now it'sOnInit().

I've found a good description here, if you start from scratchhttps://sgr-tradeinvest.ru/mql4

 
Vasiliy Kolesov :

yes from the very beginning, for example there is no Start function, now it's OnInit()


Compiled. There are no errors. Only one warning, which is easily corrected with an elementary understanding of the term "function".

I even took a slightly larger example:

 //--------------------------------------------------------------------
// tradingexpert.mq4 
// Предназначен для использования в качестве примера в учебнике MQL4.
//--------------------------------------------------------------------
#property copyright "Copyright © Book, 2007"
#property link        "http://AutoGraf.dp.ua"
//--------------------------------------------------------------- 1 --
                                   // Численные значения для М15
extern double StopLoss   = 200 ;     // SL для открываемого ордера
extern double TakeProfit = 39 ;       // ТР для открываемого ордера
extern int     Period_MA_1= 11 ;       // Период МА 1
extern int     Period_MA_2= 31 ;       // Период МА 2
extern double Rastvor    = 28.0 ;     // Расстояние между МА 
extern double Lots       = 0.1 ;     // Жестко заданное колич. лотов
extern double Prots      = 0.07 ;     // Процент свободных средств
 
bool Work= true ;                     // Эксперт будет работать.
string Symb;                       // Название финанс. инструмента
//--------------------------------------------------------------- 2 --
int start()
  {
   int
   Total,                           // Количество ордеров в окне 
   Tip=- 1 ,                           // Тип выбран. ордера (B=0,S=1)
   Ticket;                           // Номер ордера
   double
   MA_1_t,                           // Значен. МА_1 текущее
   MA_2_t,                           // Значен. МА_2 текущее 
   Lot,                             // Колич. лотов в выбран.ордере
   Lts,                             // Колич. лотов в открыв.ордере
   Min_Lot,                         // Минимальное количество лотов
   Step,                             // Шаг изменения размера лота
   Free,                             // Текущие свободные средства
   One_Lot,                         // Стоимость одного лота
   Price,                           // Цена выбранного ордера
   SL,                               // SL выбранного ордера 
   TP;                               // TP выбранного ордера
   bool
   Ans  = false ,                     // Ответ сервера после закрытия
   Cls_B= false ,                     // Критерий для закрытия  Buy
   Cls_S= false ,                     // Критерий для закрытия  Sell
   Opn_B= false ,                     // Критерий для открытия  Buy
   Opn_S= false ;                     // Критерий для открытия  Sell
//--------------------------------------------------------------- 3 --
   // Предварит.обработка
   if ( Bars < Period_MA_2)                       // Недостаточно баров
     {
       Alert ( "Недостаточно баров в окне. Эксперт не работает." );
       return ;                                   // Выход из start()
     }
   if (Work== false )                               // Критическая ошибка
     {
       Alert ( "Критическая ошибка. Эксперт не работает." );
       return ;                                   // Выход из start()
     }
//--------------------------------------------------------------- 4 --
   // Учёт ордеров
   Symb= Symbol ();                               // Название фин.инстр.
   Total= 0 ;                                     // Количество ордеров
   for ( int i= 1 ; i<= OrdersTotal (); i++)           // Цикл перебора ордер
     {
       if ( OrderSelect (i- 1 , SELECT_BY_POS )== true ) // Если есть следующий
        {                                       // Анализ ордеров:
         if ( OrderSymbol ()!=Symb) continue ;       // Не наш фин. инструм
         if ( OrderType ()> 1 )                     // Попался отложенный
           {
             Alert ( "Обнаружен отложенный ордер. Эксперт не работает." );
             return ;                             // Выход из start()
           }
         Total++;                               // Счётчик рыночн. орд
         if (Total> 1 )                           // Не более одного орд
           {
             Alert ( "Несколько рыночных ордеров. Эксперт не работает." );
             return ;                             // Выход из start()
           }
         Ticket= OrderTicket ();                   // Номер выбранн. орд.
         Tip   = OrderType ();                     // Тип выбранного орд.
         Price = OrderOpenPrice ();               // Цена выбранн. орд.
         SL    = OrderStopLoss ();                 // SL выбранного орд.
         TP    = OrderTakeProfit ();               // TP выбранного орд.
         Lot   = OrderLots ();                     // Количество лотов
        }
     }
//--------------------------------------------------------------- 5 --
   // Торговые критерии
   MA_1_t= iMA ( NULL , 0 ,Period_MA_1, 0 , MODE_LWMA , PRICE_TYPICAL , 0 ); // МА_1
   MA_2_t= iMA ( NULL , 0 ,Period_MA_2, 0 , MODE_LWMA , PRICE_TYPICAL , 0 ); // МА_2
 
   if (MA_1_t > MA_2_t + Rastvor* Point )         // Если разница между
     {                                           // ..МА 1 и 2 большая
      Opn_B= true ;                               // Критерий откр. Buy
      Cls_S= true ;                               // Критерий закр. Sell
     }
   if (MA_1_t < MA_2_t - Rastvor* Point )         // Если разница между
     {                                           // ..МА 1 и 2 большая
      Opn_S= true ;                               // Критерий откр. Sell
      Cls_B= true ;                               // Критерий закр. Buy
     }
//--------------------------------------------------------------- 6 --
   // Закрытие ордеров
   while ( true )                                   // Цикл закрытия орд.
     {
       if (Tip== 0 && Cls_B== true )                 // Открыт ордер Buy..
        {                                       //и есть критерий закр
         Alert ( "Попытка закрыть Buy " ,Ticket, ". Ожидание ответа.." );
         RefreshRates ();                         // Обновление данных
         Ans= OrderClose (Ticket,Lot, Bid , 2 );       // Закрытие Buy
         if (Ans== true )                         // Получилось :)
           {
             Alert ( "Закрыт ордер Buy " ,Ticket);
             break ;                               // Выход из цикла закр
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
 
       if (Tip== 1 && Cls_S== true )                 // Открыт ордер Sell..
        {                                       // и есть критерий закр
         Alert ( "Попытка закрыть Sell " ,Ticket, ". Ожидание ответа.." );
         RefreshRates ();                         // Обновление данных
         Ans= OrderClose (Ticket,Lot, Ask , 2 );       // Закрытие Sell
         if (Ans== true )                         // Получилось :)
           {
             Alert ( "Закрыт ордер Sell " ,Ticket);
             break ;                               // Выход из цикла закр
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
       break ;                                     // Выход из while
     }
//--------------------------------------------------------------- 7 --
   // Стоимость ордеров
   RefreshRates ();                               // Обновление данных
   Min_Lot= MarketInfo (Symb, MODE_MINLOT );         // Миним. колич. лотов 
   Free   = AccountFreeMargin ();                 // Свободн средства
   MarketInfo (Symb, MODE_MARGINREQUIRED ); // Стоимость 1 лота
   Step   = MarketInfo (Symb, MODE_LOTSTEP );       // Шаг изменен размера
 
   if (Lots > 0 )                                 // Если заданы лоты,то 
      Lts =Lots;                                 // с ними и работаем 
   else                                          // % свободных средств
      Lts= MathFloor (Free*Prots/One_Lot/Step)*Step; // Для открытия
 
   if (Lts < Min_Lot) Lts=Min_Lot;               // Не меньше минимальн
   if (Lts*One_Lot > Free)                       // Лот дороже свободн.
     {
       Alert ( " Не хватает денег на " , Lts, " лотов" );
       return ;                                   // Выход из start()
     }
//--------------------------------------------------------------- 8 --
   // Открытие ордеров
   while ( true )                                   // Цикл закрытия орд.
     {
       if (Total== 0 && Opn_B== true )               // Открытых орд. нет +
        {                                       // критерий откр. Buy
         RefreshRates ();                         // Обновление данных
         SL= Bid - New_Stop(StopLoss)* Point ;     // Вычисление SL откр.
         TP= Bid + New_Stop(TakeProfit)* Point ;   // Вычисление TP откр.
         Alert ( "Попытка открыть Buy. Ожидание ответа.." );
         Ticket= OrderSend (Symb, OP_BUY ,Lts, Ask , 2 ,SL,TP); //Открытие Buy
         if (Ticket > 0 )                         // Получилось :)
           {
             Alert ( "Открыт ордер Buy " ,Ticket);
             return ;                             // Выход из start()
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
       if (Total== 0 && Opn_S== true )               // Открытых орд. нет +
        {                                       // критерий откр. Sell
         RefreshRates ();                         // Обновление данных
         SL= Ask + New_Stop(StopLoss)* Point ;     // Вычисление SL откр.
         TP= Ask - New_Stop(TakeProfit)* Point ;   // Вычисление TP откр.
         Alert ( "Попытка открыть Sell. Ожидание ответа.." );
         Ticket= OrderSend (Symb, OP_SELL ,Lts, Bid , 2 ,SL,TP); //Открытие Sel
         if (Ticket > 0 )                         // Получилось :)
           {
             Alert ( "Открыт ордер Sell " ,Ticket);
             return ;                             // Выход из start()
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
       break ;                                     // Выход из while
     }
//--------------------------------------------------------------- 9 --
   return ;                                       // Выход из start()
  }
//-------------------------------------------------------------- 10 --
int Fun_Error( int Error)                         // Ф-ия обработ ошибок
  {
   switch (Error)
     {                                           // Преодолимые ошибки            
       case    4 : Alert ( "Торговый сервер занят. Пробуем ещё раз.." );
         Sleep ( 3000 );                           // Простое решение
         return ( 1 );                             // Выход из функции
       case 135 : Alert ( "Цена изменилась. Пробуем ещё раз.." );
         RefreshRates ();                         // Обновим данные
         return ( 1 );                             // Выход из функции
       case 136 : Alert ( "Нет цен. Ждём новый тик.." );
         while ( RefreshRates ()== false )           // До нового тика
             Sleep ( 1 );                           // Задержка в цикле
         return ( 1 );                             // Выход из функции
       case 137 : Alert ( "Брокер занят. Пробуем ещё раз.." );
         Sleep ( 3000 );                           // Простое решение
         return ( 1 );                             // Выход из функции
       case 146 : Alert ( "Подсистема торговли занята. Пробуем ещё.." );
         Sleep ( 500 );                             // Простое решение
         return ( 1 );                             // Выход из функции
         // Критические ошибки
       case    2 : Alert ( "Общая ошибка." );
         return ( 0 );                             // Выход из функции
       case    5 : Alert ( "Старая версия терминала." );
         Work= false ;                             // Больше не работать
         return ( 0 );                             // Выход из функции
       case 64 : Alert ( "Счет заблокирован." );
         Work= false ;                             // Больше не работать
         return ( 0 );                             // Выход из функции
       case 133 : Alert ( "Торговля запрещена." );
         return ( 0 );                             // Выход из функции
       case 134 : Alert ( "Недостаточно денег для совершения операции." );
         return ( 0 );                             // Выход из функции
       default : Alert ( "Возникла ошибка " ,Error); // Другие варианты   
         return ( 0 );                             // Выход из функции
     }
  }
//-------------------------------------------------------------- 11 --
int New_Stop( int Parametr)                       // Проверка стоп-прик.
  {
   int Min_Dist= MarketInfo (Symb, MODE_STOPLEVEL ); // Миним. дистанция
   if (Parametr < Min_Dist)                     // Если меньше допуст.
     {
      Parametr=Min_Dist;                         // Установим допуст.
       Alert ( "Увеличена дистанция стоп-приказа." );
     }
   return (Parametr);                             // Возврат значения
  }
//-------------------------------------------------------------- 12 --

It also compiles. 12 warnings, but none of them affect the performance of the program. They are also corrected. Therefore, to start the Tutorial - that's it.

 
BillionerClub:

Learn C++ if you are a beginner. Here is a good resourcehttps://foxford.ru/wiki/informatika/otlichiya-yazykov-programmirovaniya-si-i-s

The man needs a ride and you are giving him the runaround. At the stage of mastering MQL the question of whether the programmer needs programming in principle, whether he can pull it off. MQL is easier than C++. Why bother with complicated things?

Especially, that the above link includes everything that MQL does not have: standard library (MLQ has, but its own, not C++), namespace, input and output via cout and cin.

 
Ihor Herasko:

Compiled. There are no errors. Only one warning, which is easily corrected with a basic understanding of the term "function".

I even took a bit bigger example:

It compiles too. There are 12 warnings, but none of them affects operability of the program. They can be easily fixed, too. That's why the Tutorial is a good starting point.

I tried it for some reason and it didn't work. I thought it was because of the name change. Thank you for trying it. Maybe we should go back to it.

 
Vitaly Muzichenko:

Yuri, well, everyone starts somewhere.

I started with .php, then I studied .js because without it, writing something normal is simply not realistic. When .js was supplemented with jquery library, it was a joy, but you had to learn it. Many people wrote then that it was nonsense and you should only use pure .js, later everyone moved to using jquery, because libraries are cool.

When I touched forex, I studied .mql because I needed to, even though it was hard, it's not the same as php and js.

So all that matters is the desire.

Now, to be a cool kid, jquery is not enough, you have to study ***teen more frameworks... That's how the average programmer lives his whole life as an unfinished programmer - he learns one framework and three more appear at once.

 
Anastasia Vasilenko:
What did you study?

If only you knew what you already know and what you can do. In general - just take the Expert Advisor from the terminal kit, open it in the editor and see if something in the code is highlighted in a different colour - put the cursor there, press f1 and read the help.

If you are not at all familiar with programming, do not know what for, if, etc. - You may start with any language book for dummies or children's books.

Reason: