Self-learning the MQL5 language from scratch - page 11

 
Aliaksandr Hryshyn:

You have the wrong study plan, you are starting from the wrong place.

Here you are learning a function:

This is not simple, relatively, and requires basic knowledge already.

To confirm this, try to answer the questions on this function, you probably won't be able to answer, which indicates the wrong direction of learning:

Why is "My_line_2" in quotes and OBJ_VLINE without?

What does int, double mean here, and how are they different?

Why is sub_window written and not the other way around, what's the point?

You don't need to learn the functions from the help, you need the basic elements of the language, the basic principles of working with the trading environment, with files, all sorts of data, and others, depending on the task at hand.

Thank you, Alexander, for your advices! I will take them into account.

Regards, Vladimir.

 
MrBrooklin:

That's right, but just taking a ready-made example or writing your own code is two big differences. At least for me. And thank you very much for the tip!

Sincerely, Vladimir.

If you're not going to study C++ & MQL completely, but are seeking for a simpler variant, you may take a ready-made code and organize it in the explanatory mode, try to understand the MQL5 Reference, as recommended by the author.

Aliaksandr Hryshyn:

You have the wrong study plan, you are starting from the wrong place.

You may write a similar or even better.)

But start with the purpose -> why do you want to study and what exactly you need to study to reach your goal, so that you may forget unnecessary things and concentrate on the essentials.)

 
The MQL4 textbook is the best option. Everything is easy to understand, even for absolute beginners. Correct and up to date selection of material. In ~4 months you will be able to write your own EAs.

Do not draw up a syllabus yourself as you do not understand this area of knowledge (programming) at all. Consequently, trust a competent textbook.
 
VVT:

If you're not going to learn C++ & MQL completely, but are looking for a simpler version, take ready-made code, decompose it, try to understand what for and why, using MQL5 Reference Guide, as recommended

If you understand all that you are interested in, you may write a similar or even better.)

But begin with the purpose -> why do you study and what you need to study to reach your goal, so that you eliminate unnecessary things and focus on the essentials.)

I am studying C++ and MQL5 programming languages step by step as questions appear. I am writing scripts to reinforce the material I have learned. Step by step I am getting rid of my inner fear of the unknown. I am beginning to understand some things. I hope I have the patience and strength to learn not only the basics of programming, but to do even more. Thank you for sharing your advices. They are all taken into account! But as the saying goes - Moscow was not built at once!

Regards, Vladimir.

 
Реter Konow:
The MQL4 tutorial is the best. Everything is understandable even for absolute beginners. You have an accurate and up-to-date selection of material for our industry. In ~4 months you will be able to write your own EAs.

Do not draw up a syllabus yourself as you do not understand this area of knowledge (programming) at all. Hence, trust a competent textbook.

Thank you, Peter! I hope I am correct in your name? I will definitely find this book to study. Just now, there is a point at which a stupor may come from an overload of information. For now, according to my self-study plan, I have a few more scripts in the queue to fix the material I have already learned.

Once again, thank you for your advice!

Regards, Vladimir.

 

I continue studying the MQL5 programming language. The new script New5.mq5 sets the trend line between two time intervals. As I promised earlier, I tried to describe everything in this script for a 1st class student of the programming school.

Regards, Vladimir.

//+------------------------------------------------------------------+
//|                                                         New5.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//---
#property script_show_inputs
//---
/* Ранее в скриптах New2.mq5, New3.mq5 и New4.mq5 мы научились создавать горизонтальную
   и вертикальную линию на текущем графике главного окна терминала MetaTrader 5.
   Теперь мы немного усложним задачу и попробуем создать линию, но уже с привязкой двух точек по
   временнОй и ценовой координатам. Кроме того, в данном скрипте мы реализуем возможность
   изменять входные параметры нужных нам координат. Снова воспользуемся информацией имеющейся 
   в Справочнике MQL5.
   Для начала необходимо сделать так, чтобы перед установкой новой линии, у нас было место, 
   где мы могли устанавливать или менять нужные нам координаты привязки. Для этого мы должны
   воспользоваться препроцессором – специальной подсистемой компилятора MQL5, которая занимается 
   предварительной подготовкой исходного текста программы непосредственно перед ее компиляцией.
   Препроцессор позволяет также определять специфические параметры mql5-программ:
   - Объявлять константы
   - Устанавливать свойства программы
   - Включать в текст программы файлы
   - Импортировать функции
   - Использовать условную компиляцию
   В нашем случае интересен раздел "Устанавливать свойства программы", поэтому жмем на эту ссылку
   и переходим во вкладку "Свойства программ (#property)". Если внимательно просмотреть все константы, то
   можно найти "script_show_inputs" (дословный перевод - показать входы скрипта), а если быть точнее, 
   то вывести окно со свойствами перед запуском скрипта и запретить вывод окна подтверждения. Запишем
   #property script_show_inputs чуть ниже шаблона шапки скрипта.
   Движемся дальше. Создадим входные параметры скрипта. Для этого нам понадобится класс памяти input 
   который определяет внешнюю переменную. Модификатор input указывается перед типом данных. 
   Изменять значение переменной с модификатором input внутри mql5-программы нельзя, такие переменные 
   доступны только для чтения. Изменять значения input-переменных может только пользователь из окна 
   свойств программы. Простыми словами input нам нужен для того, чтобы задавать свои значения в диалоговом 
   окне скрипта в момент его запуска.   
*/

// ПИШЕМ КОД СКРИПТА
input datetime inp_time1=D'2020.10.01 14:00'; //Превая точка привязки по временнОй координате
input double inp_price1=1.17693;              //Первая точка привязки по ценой координате
input datetime inp_time2=D'2020.10.02 10:00'; //Вторая точка привязки по временнОй координате
input double inp_price2=1.17412;              //Вторая точка привязки по ценой координате
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   ObjectCreate(0,"Моя_линия_3",OBJ_TREND,0,inp_time1,inp_price1,inp_time2,inp_price2);
   
  }
//+------------------------------------------------------------------+

/* Теперь расшифруем, что именно мы создали в программном коде скрипта.
1. Первым делом мы создали четыре входных параметра, по два на каждую точку привязки. В данном скрипте
   каждая точка привязки линии имеет 2-а параметра - price и time. Каждый входной параметр начинается
   с input (переводится как "ввод").
2. После input пишется тип переменной. Например, для ценовых координат присваивается тип переменной double,
   т.к. она (цена) имеет дробную часть, а для временнЫх координат присваивается тип переменной datetime.
   Все эти сведения мы берем из уже известного нам Справочника MQL5.
3. Чтобы мы смогли вводить свои данные, нам необходимо создать четыре собственные переменные созвучные с
   price и time. Ими станут inp_time1, inp_time2, inp_price1 и inp_price2. Каждой новой переменной зададим
   конкретные значения (константы), например, input datetime inp_time1=D'2020.10.01 14:00' и т.д.
4. Дальше для создания новой линии, нам также потребуется ObjectCreate, только с некоторыми поправками.
   Во-первых, зададим для линии новое уникальное имя "Моя_линия_3". Во-вторых, зададим новый тип объекта 
   OBJ_TREND, т.к. будем создавать линию, которая может располагаться на торговом терминале в
   произвольном положении. В-третьих, там где в предыдущих скриптах мы записывали конкретные 
   величины price и time, а именно, time1, price1, time2 и price2, теперь мы должны записать вновь
   созданные нами переменные inp_time1, inp_price1, inp_time2 и inp_price2. Всё! Наш новый скрипт готов.
5. Компилируем и запускаем скрипт. Как компилировать и запускать скрипт мы уже узнали, когда создавали скрипт New2.mq5.
*/
 
MrBrooklin:

Thank you, Peter! I hope I am using your name correctly? I will definitely find this book to study. It's just that right now I'm at a point where I can get overwhelmed by the overload of information. So far, according to my self-study plan, I have a few more scripts in the queue to fix the material I've already studied.

Once again, thank you for your advice!

Regards, Vladimir.

MQL4 tutorial
Учебник по MQL4
Учебник по MQL4
  • book.mql4.com
В настоящее время персональный компьютер стал незаменимым помощником в жизни каждого человека. Благодаря развитию Интернета и увеличению мощности современных компьютеров открылись новые возможности во многих областях деятельности. Ещё десять лет назад торговля на финансовых рынках была доступна только банкам и узкому кругу специалистов. Сегодня...
 
Alekseu Fedotov:
MQL4 Tutorial

Thanks, Alexey, for the link!!!

Sincerely, Vladimir.

 
MrBrooklin:

Thank you, Peter! I hope I am using your name correctly? I will definitely find this book to study. It's just that right now I'm at a point where I can get overwhelmed by the overabundance of information. So far, according to my self-study plan, I have a few more scripts in the queue to fix the material I've already studied.

Once again, thank you for your advice!

Sincerely, Vladimir.

Peter is good too. :)

Now, in all seriousness: leave this premature "fiddling" with lines. It's better not to just jump into programming - it's too complicated. You need a base. Start with the first lessons of the MQL4 tutorial and do not worry about the learning curve, it is well thought out for you.

Read and take notes. Until you master at least the beginning - do not even try to program, this will only lead you astray. Patience and work will help you to gain valuable knowledge, which you won't get in a chaotic self-study. It is like going to school, choosing classes and subjects at random every day. Your head will be in mush. :)

P.S. First you need to go through types of variables, arrays, learn how to work with loops, write the simplest functions and only then draw lines. If vice versa, you will be tied to other people's codes, and will not be able to write your own program, according to your idea.Writing a program is the finale, not the beginning of textbook learning.
 
Реter Konow:
... First you need to go through types of variables, arrays, learn how to work with loops, write the simplest functions and only then draw lines. If vice versa, you will be tied to other people's codes, and will not be able to write your own program, according to your idea.Writing a program is the final, not the beginning of learning from a textbook.

Thanks Peter, I took your advice to heart!

Regards, Vladimir.

Reason: