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

 

MT4

What is this item and what does it do, I can't find a description anywhere?

How do I disable it by default?


 
void OnStart()
  {
string text="Hello man";
   string keystr="ABCDEFG";
   uchar src[],dst[],key[];
//--- подготовка ключа шифрования
   StringToCharArray(keystr,key);
//--- подготовка исходного массива src[]
   StringToCharArray(text,src);
//--- вывод исходных данных
   PrintFormat("Initial data: size=%d, string='%s'",ArraySize(src),CharArrayToString(src));
//--- шифрование массива src[] методом DES с 56-битным ключом key[]
   int res=CryptEncode(CRYPT_AES256,src,key,dst);
//--- проверка результата шифрования
   if(res>0)
     {
      //--- вывод шифрованных данных
      PrintFormat("Encoded data: size=%d %s",res,ArrayToHex(dst));
      //--- расшифровка данных массива dst[] методом DES с 56-битным ключом key[]
      res=CryptDecode(CRYPT_AES256,dst,key,src);
      //--- проверка результата
      if(res>0)
        {
         //--- вывод дешифрованных данных
         PrintFormat("Decoded data: size=%d, string='%s'",ArraySize(src),CharArrayToString(src));
        }
      else
         Print("Ошибка в CryptDecode. Код ошибки=",GetLastError());
     }
   else
      Print("Ошибка в CryptEncode. Код ошибки=",GetLastError());
  }
//+------------------------------------------------------------------+
string ArrayToHex(uchar &arr[],int count=-1)
  {
   string res="";
//--- проверка размера
   if(count<0 || count>ArraySize(arr))
      count=ArraySize(arr);
//--- преобразование в шестнадцатиричную строку
   for(int i=0; i<count; i++)
      res+=StringFormat("%.2X",arr[i]);
//---
   return(res);
  }

I'm trying to run the crypto example from the manual, butI use CRYPT_AES256 instead ofCRYPT_DES method. The result is error 4029 afterCryptEncode method

 
Dmitri Custurov:

I'm trying to run the crypto example from the manual, butI use CRYPT_AES256 instead ofCRYPT_DES method. As a result, error 4029 afterCryptEncode method

Figured it out. He needs more careful key.)

 

Hello!

I'm dumb and can't figure it out myself, please advise what the problem could be or at least point me in the right direction.

Different indicators are starting to show a different piece of history synchronously. It happens sometimes, not every day.

I thought the reason is that indicators do not correctly process dynamically loaded history. I tried everything that concerns the correct update of the indicator on the updating history, I don't know what else should be done to prevent this.

Alpari broker. MT5 build 2363 from 13.03.2020.

The screenshots show the "lost" version first.

Then the correct version after manual update.

//+------------------------------------------------------------------+
bool IsReadyForCalculate(const int rates_total,const int prev_calculated,const datetime &time[])
  {
   //--- подключение терминала и синхронизация данных
   if(TerminalInfoInteger(TERMINAL_CONNECTED))  
      if(!SymbolIsSynchronized(_Symbol) || 
         !SeriesInfoInteger(_Symbol,_Period,SERIES_SYNCHRONIZED))   return(false);
   //--- некорректное значение prev_calculated
   if(prev_calculated<0)                  return(false);
   //---
   if(prev_calculated==0)     prev_time = time[rates_total-1];
   //--- произошли изменения в данных, но prev_calculated не сброшен в 0
   //--- или изменение времени не соответствует одному бару
   if(  (rates_total!=prev_calculated+1 &&
         rates_total!=prev_calculated &&
         prev_calculated!=0) ||
        (time[rates_total-1]>prev_time &&
         time[rates_total-2]!=prev_time))
     {
      loc_prev_calculated = 0;    // чтобы индикатор не висел "голым" до следующей котировки, вычисляю индикатор из того, что есть
      return(true);
     }
   //--- корректный сценарий
   if(  (rates_total==prev_calculated   || rates_total==prev_calculated+1 || prev_calculated==0) &&
        (time[rates_total-1]==prev_time || time[rates_total-2]==prev_time))
     {
      loc_prev_calculated = prev_calculated;
      return(true);
     }
   //--- 
   return(false);       // верну false, пока не знаю, какие варианты ещё могут быть
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,const int prev_calculated,const datetime &time[],const double &open[],const double &high[],const double &low[],const double &close[],const long &tick_volume[],const long &volume[],const int &spread[])
  {
   if(!IsReadyForCalculate(rates_total,prev_calculated,time))     return(0);
//---
        // вызов функции зигзага
   
//--- return value of prev_calculated for next call
   prev_time = time[rates_total-1];
   return(rates_total);
  }
//+------------------------------------------------------------------+
 

Hello.

I have this question in MQL5. How can I force the OnChartEvent() function to start? Is there any standard way to do it?

For this purpose, I use ChartNavigate() function and run it from OnChartEvent(). But it works unstable - when a lot of ticks come in, often OnChartEvent() doesn't restart after calling ChartNavigate() for some reason. I can't understand how it's connected - ChartNavigate() and tick arrival rate, but it happens nevertheless.

Документация по MQL5: Основы языка / Функции / Функции обработки событий
Документация по MQL5: Основы языка / Функции / Функции обработки событий
  • www.mql5.com
В языке MQL5 предусмотрена обработка некоторых предопределенных событий. Функции для обработки этих событий должны быть определены в программе MQL5: имя функции, тип возвращаемого значения, состав параметров (если они есть) и их типы должны строго соответствовать описанию функции-обработчика события. Именно по типу возвращаемого значения и по...
 
inwinterborn:

Hello!

I'm dumb and can't figure it out myself, please advise what the problem could be or at least point me in the right direction.


      loc_prev_calculated = 0;    // чтобы индикатор не висел "голым" до следующей котировки, вычисляю индикатор из того, что есть
      return(true);

Maybe I added this recently for nothing...

Removed
loc_prev_calculated 

Replaced it with...

      return(false);

I'll keep an eye on it.


Please tell me about the standard indicators that come with the MT5, how do they work? Do they flop like I did in the screenshots above?

 

Good day all!
I am mastering double OnTester() function and TesterStatistics( ) function. I wrote a simple code for my tester in MT4, which opens one order every day at 10:00, at 16:00, at 20:00 and at 01:00. At the end of testing, the TesterStatistics( ) function returns the smallest balance value (i.e. relative drawdown).

PROBLEM

TesterStatistics( ) returns the smallest balance value for ALL open orders

QUESTION

What language construction can be used to make TesterStatistics() return the smallest balance value only for an order opened at some particular time, for example at 16:00. At this, all orders specified in the code should be tested simultaneously. It means, TesterStatistics should track the balance dynamics for only one order opened at 16:00 and at the end of testing, display the minimum balance value only for the order opened at 16:00.

I would be very grateful if you could insert the required language construct in my code. It will allow me to quickly understand the algorithm of solution of my problem.
Here is my code.

int H;
double  TesterStatistics( );
void OnTick()
{
if (H!=Hour( ))
if (Hour( )==10||Hour( )==16||Hour( )==20||Hour( )==1)
{
OrderSend(Symbol(),OP_SELL,0.1,Bid, 3,Ask+400*Point,Ask-200*Point,"C2",123 );
H=Hour( );
}
}
double OnTester()
{
TesterStatistics( STAT_BALANCEMIN  );
Print("-----------TesterStatistics( STAT_BALANCEMIN  )--------------",TesterStatistics( STAT_BALANCEMIN  )); 
}
 
ANDREY:

Good day to all!
I have mastered double OnTester() and TesterStatistics( ). I have written a simple code for my tester in MT4, which opens one order at 10:00, at 16:00, at 20:00 and at 01:00 every day. In the end of testing, the function TesterStatistics returns the smallest balance value (i.e. relative drawdown).

PROBLEM

TesterStatistics( ) returns lowest balance value for ALL open orders

QUESTION

What language construction can be used to make TesterStatistics() return the smallest balance value only for an order opened at some particular time, for example at 16:00. At this, all orders specified in the code should be tested simultaneously. I.e., TesterStatistics( ) should track the balance dynamics of only one order opened at 16:00 and return the minimum value of the balance for the order opened at 16:00 only.

I would be very grateful, if you could insert required language in my code. This will allow me very quickly to understand the algorithm to solve my problem.
Here is my code.

int H;
double  TesterStatistics( );
void OnTick()

What is it?

 
 Сергей Таболин
:

Is this what it is?

Thank you for your feedback. Thanks to you I realized that specifyingTesterStatistics( ); function together with declaration of global variable H ... was my mistake. I fixed it.

int H;
//double  TesterStatistics( );
void OnTick()
{
if (H!=Hour( ))
if (Hour( )==10||Hour( )==16||Hour( )==20||Hour( )==1)
{
OrderSend(Symbol(),OP_SELL,0.1,Bid, 3,Ask+400*Point,Ask-200*Point,"C2",123 );
H=Hour( );
}
}
double OnTester()
{
TesterStatistics( STAT_BALANCEMIN  );
Print("-----------TesterStatistics( STAT_BALANCEMIN  )--------------",TesterStatistics( STAT_BALANCEMIN  )); 
}
Документация по MQL5: Основы языка / Переменные / Глобальные переменные
Документация по MQL5: Основы языка / Переменные / Глобальные переменные
  • www.mql5.com
Глобальные переменные создаются путем размещения их объявлений вне описания какой-либо функции. Глобальные переменные определяются на том же уровне, что и функции, т. е. не локальны ни в каком блоке. Область видимости глобальных переменных - вся программа, глобальные переменные доступны из всех функций, определенных в программе...
 
Good morning! How can I implement displaying high and low bar data on a chart? And highlight the same colour.