Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1188

 
Ivan_Invanov:
Generally, judging by your response, you do not really understand how the program works. So it seems like a stupid question. Just like the previous commenter thinks it stops. Just from programming experience in other languages I think it executes its body in a loop, and when an event comes, it dives into it. If the program executes its body in a loop, that explains why the program is written that way.

When a new tick occurs, the program is started in the OnTick() handler, executed to completion and stopped. With the arrival of a new tick everything repeats from the beginning. If a new tick has come during the program execution, and the program hasn't finished processing the previous tick (it is still running), then this tick is skipped.

Programs in MQL are not looped. They have three entry points - OnInit(), OnDeinit() and OnTick().

At startup, OnInit() is executed, then when a tick is received - OnTick(), when operation is finished - OnDeinit().

There are other handlers as well. But you'd better just open the help rather than ask someone to duplicate it here.

Документация по MQL5: Программы MQL5
Документация по MQL5: Программы MQL5
  • www.mql5.com
Для того чтобы mql5-программа могла работать, она должна быть скомпилирована (кнопка "Компилировать" или клавиша F7). Компиляция должна пройти без ошибок (допускаются предупреждения, которые необходимо проанализировать). При этом в соответствующей директории Эксперты, пользовательские индикаторы и скрипты прикрепляются к одному из открытых...
 

Hello. While working on my indicator I found a bug when restarting the terminal. On the basis of this bug I made a small source code for its testing:

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

class Loader {
private:
  string symbol;
  ENUM_TIMEFRAMES timeframe;

public:  
  Loader(): symbol(Symbol()), timeframe(Period()) 
  {
    Print(__FUNCTION__ + " symbol: " + symbol + " timeframe: " + EnumToString(timeframe));
    ResetLastError();
    Print(__FUNCTION__ + " bars: " + (string)iBars(symbol, timeframe)); // Данный вызов iBars() даёт 0 при перезапуске терминала
    Print(__FUNCTION__ + " Error: " + (string)GetLastError());
    Print(__FUNCTION__ + " bars (2): " + (string)iBars(Symbol(), Period())); // Этот же вызов iBars() работает нормально
  }
};

Loader * loader;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit() {
//--- indicator buffers mapping
  loader = new Loader();
//---
  return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
  delete loader;
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const int begin,
                const double &price[]
) {
  return(rates_total);
}

If this example is thrown on a chart (or it is the first terminal start after system startup) everything works fine. In the log it says the following:

2020.06.24 21:05:50.773 Loader::Loader symbol: EURUSD timeframe: PERIOD_H1

2020.06.24 21:05:50.773 Loader::Loader bars: 140433

2020.06.24 21:05:50.773 Loader::Loader Error: 0

2020.06.24 21:05:50.773 Loader::Loader bars (2): 140433


But if I restart terminal with this indicator I get error:

2020.06.24 21:07:34.963 Loader::Loader symbol: EURUSD timeframe: PERIOD_H1

2020.06.24 21:07:34.963 Loader::Loader bars: 0

2020.06.24 21:07:34.963 Loader::Loader Error: 4401

2020.06.24 21:07:34.964 Loader::Loader bars (2): 140433

Symbol and timeframe initialized ok

2020.06.24 21:07:34.963 Loader::Loader symbol: EURUSD timeframe: PERIOD_H1

But iBars(symbol, timeframe) gives 0 for some reason

2020.06.24 21:07:34.963 Loader::Loader bars: 0

In this case error 4401 appears.

But iBars(Symbol(), Period()) works fine.

2020.06.24 21:07:34.964 Loader::Loader bars (2): 140433

At least symbol = Symbol() and timeframe = Period() according to log messages (even during lag, when terminal restarts). How can iBars(symbol, timeframe), with absolutely correct symbol and timeframe, give zero, while iBars(Symbol(), Period()) works fine, if the parameters in functions are the same, according to the log?

Запуск платформы - Для продвинутых пользователей - Справка по MetaTrader 5
Запуск платформы - Для продвинутых пользователей - Справка по MetaTrader 5
  • www.metatrader5.com
По завершении установки в меню "Пуск" создается группа программ торговой платформы, а на рабочем столе дополнительно помещается ярлык программы. Используйте их для запуска. Нельзя запускать одновременно две копии платформы из одной директории. Чтобы одновременно запустить несколько копий, установите соответствующее количество программ в разные...
Files:
Test.mq5  7 kb
 
Who knows the moderator of this thread?
 

How do I open a MT4 demo account on MetaQuotes Demo? It used to work without any problems, now on the last page of the dialog it says: Registration, Wait a little, please, and in this state it remains idle indefinitely, fields with login and password remain empty. No messages in log. Tried both "demo" and "real" and different types of accounts.

UPD Tried one broker demo - same thing.

 
Artyom Trishkin:

When a "new tick" event occurs, the program is started in the OnTick() handler, executed to completion and stopped. With the arrival of a new tick everything repeats from the beginning. If a new tick has come during the program execution, and the program hasn't finished processing the previous tick (it is still running), then this tick is skipped.

Programs in MQL are not looped. They have three entry points - OnInit(), OnDeinit() and OnTick().

At startup, OnInit() is executed, then when a tick is received - OnTick(), when operation is finished - OnDeinit().

There are other handlers as well. But you'd better just open the help rather than ask someone to duplicate it here.

Thank you. Yes I understand that, it's just that the function is written in the body of the program. Maybe I didn't notice it being called somewhere.
 
Ivan_Invanov:
Thank you. Yes I understand that, it's just that the function is written in the body of the program. Maybe I didn't notice it being called somewhere.

How can we see what you are talking about? Give us an example.

 
Artyom Trishkin:

How can we see what you are talking about? Give us an example.

Thanks again, yes, I didn't notice the call, I looked it up now , and it was called by the function that opens the trades.
 
Ivan_Invanov:
Thank you. Yes, I understand it, it's just the function is written in the body of the program. Maybe I must have missed a call for it somewhere.

In mql4 functions are written in any order, above below it doesn't matter, it may seem to work earlier or later. There is no such thing in C++ where all functions can work only in order of writing and if you want to call it, it must be defined before the place of call otherwise the program crashes. The man showed me how to write functions in different order but I don't remember how to do it in C++.

 
Ivan_Invanov:

Greetings. Please help me out. I have this question. Do I understand correctly. The program is executed from the beginning to the end, but stops when an event occurs, e.g. a tick, the ontick function starts to execute, then it finishes its execution and the program is executed again from the beginning? This question is related to the following, where do I write for example the size of the trading lot, in the program body or in the ontick function?

I look at the official bot, which is an example in the terminal, there lot calculation is performed in the program body, and I do not understand why so.

My lot is calculated like this

#property link      "http://www.mql5.com"
input double CheckLots = 0.01;
input int    Persent   = 5;
   double Lots=NormalizeDouble(AccountBalance()*CheckLots/1000-0.005,2);  

it's at the beginning of the Expert Advisor...and I put it at the very end of the code

When OnTick function calls to Lots variable, then EA finds and recalculates it.

 

@Artyom Trishkin

Are you a moderator in this thread?

Reason: