MetaTrader 5 build 2121: New design of the Strategy Tester - page 8

 
A100:

The executionresults show that the compiler acts contrary to logic:

  • For a constant string, more memory is allocated than needed (its length cannot be increased in principle)
  • No additional memory is allocated for a non-constant string (if its length increases, a new memory allocation will be required)
  • If the user initializes a string with StringInitInit, more memory is allocated than necessary, because the buffer size is explicitly set by the user and in most cases it won't be increased (the user has already thought what final buffer he needs and set its size explicitly)

For a pure constant string, the size of the buffer by StringBufferlen=0, which means that the string is constant:

        string s1 = "_";            // исходное "чистое" присвоение константной строки
        Print(StringBufferLen(s1)); // показывает 0 верно, не должно быть 260


Re-assigning a "supposedly" constant string is not working with a constant, but rather creating exactly a dynamic variable with a preallocation of 260 characters:

        const string s2 = s1;       // динамическое создание переменной копированием данных из другой переменной (не константной строки)
        Print(StringBufferLen(s2)); // показывает 260 верно
 
Renat Fatkhullin:

For a pure constant string, the buffer size by StringBufferlen=0, which means that the string is constant:


Reallocating a "supposedly" constant string is not working with a constant, it's creating a dynamic variable with a preallocation of 260 characters:

it's time to introduce allocators )))

 

As a reminder, there is a bug with the string buffer:

#import "Shlwapi.dll"
int PathFileExistsW(string &pszPath);
#import

class CTest
{
protected:
   string bufstr;

public:
   CTest()
   {
      StringInit(bufstr, 1000111);
   }
   string getString()
   {
      PathFileExistsW(bufstr);
      Print(StringBufferLen(bufstr), " ", StringLen(bufstr));   
      return bufstr;
   }
};

CTest dll;

int OnInit()
{
   dll.getString(); // 1000111 0 - OK
   dll.getString(); // 260 0 - ???
   dll.getString(); // 260 0 - ???
   return INIT_SUCCEEDED;
}
void OnTick()
  {
  }
//+------------------------------------------------------------------+
The function from the DLL can be anything.
 

I suggest adding an extended version ofStringToTime function to MQL in the form:

bool StringToTime(string timeString, datetime &time);

Because in the current version the function always returns valid time, even if the string contains rubbish, and the current date is returned, which is particularly strange:

StringToTime("aaabbbccc") returns "2019.09.05 01:00:00" Is this normal? In this implementation, the function is dangerous for health at all. Therefore, a version with correctness checks is needed.

So far we have to parse with our own function,but the problem is that the time can be specified in different formats.And I don't really want to code all those formats re-inventing the wheel when the time has already been implemented in MQL.

Basically, this also applies to other string conversion functions : StringToInteger, StringToDouble. No validity check is provided for them too.

p.s. Hmm, it turns out thatGetLastError() generates errors in these cases. I didn't know that. The documentation for these functions doesn't say anything like that. That removes the problem, although it would be easier with a bool.
 
Alexey Navoykov:


I support Alexey's suggestion, safe handling of strings is key to avoiding hidden errors.

 
#property tester_no_cache true

error "property already exists with different value and will be skipped".

Used it for the first time. No other files have it. Does not depend on value. Build 2136.

 

Please bring back the old style styler.

Now I can't figure out what's supposed to run here:

   int size=ArraySize(prices);
   if(size>1)
     {
      if(size>2)
         return(true);
      if(extrema[1]<0.0 && extrema[0]<0.0)
        {
         if(extrema[1]>extrema[0])
            if(prices[1]<prices[0])
              {
               int d=0;
              }
        }
      else
         if(extrema[1]>0.0 && extrema[0]>0.0)
           {
            if(extrema[1]<extrema[0])
               if(prices[1]>prices[0])
                 {
                  int d=0;
                 }
           }
         else
           {
            return(true);
           }
     }
   else
     {
      int d=0;
     }

This piece used to look like this:

   int size=ArraySize(prices);
   if(size>1)
     {
      if(size>2)
         return(true);
      if(extrema[1]<0.0 && extrema[0]<0.0)
        {
         if(extrema[1]>extrema[0])
            if(prices[1]<prices[0])
              {
               int d=0;
              }
        }
      else if(extrema[1]>0.0 && extrema[0]>0.0)
        {
         if(extrema[1]<extrema[0])
            if(prices[1]>prices[0])
              {
               int d=0;
              }
        }
      else
        {
         return(true);
        }
     }
   else
     {
      int d=0;
     }
 
Edgar:
#property tester_no_cache true

error "property already exists with different value and will be skipped".

Used it for the first time. No other files have it. Does not depend on value. Build 2136.

This error occurs while working with projects if the value of the property specified in the source code conflicts with the value in the project settings.

Project Properties

Programme properties in the project file take precedence over properties specified in the source code. If you specify properties in both the project and the source code, the properties from the project will be used.
Создание и работа с проектом - Проекты и MQL5 Storage - MetaTrader 5
Создание и работа с проектом - Проекты и MQL5 Storage - MetaTrader 5
  • www.metatrader5.com
MetaEditor позволяет удобно работать над большими проектами: объединять множество файлов в одну структуру, управлять настройками проекта и вести совместную разработку с командой программистов через версионное онлайн-хранилище MQL5 Storage. Что такое проект Проект — это отдельный файл с расширением "MQPROJ", в котором хранятся настройки...
 
Vladimir Karputov:

Please bring back the old style styler.

Now I can't figure out what's supposed to run here:

This piece used to look like this:

Multiple nested ifs can't be saved by any alignment. We need to change the code to make it readable.

bool Sample()
  {
//---
   double prices[], extrema[];
   int size=ArraySize(prices);
   if(size>2)
      return(true);

   if(size<=1)
     {
      int d=0;
      return(false);
     }

   if(extrema[1]<0.0 && extrema[0]<0.0)
     {
      if(extrema[1]>extrema[0])
         if(prices[1]<prices[0])
           {
            int d=0;
           }
      return(false);
     }

   if(extrema[1]>0.0 && extrema[0]>0.0)
     {
      if(extrema[1]<extrema[0])
         if(prices[1]>prices[0])
           {
            int d=0;
           }
      return(false);
     }
//---     
   return(true);
  }
 
Rashid Umarov:

Multiple nested ifs cannot be saved by any alignment. You have to change the code to make it readable.

There is no multiple nesting - top level is if, then if else.

I'm asking for the old style back when if else looked like this:

      else if

- Was on a single line and there was no offset of the subsequent text to the right.


Here's an example from theConditional if-else statement help ( the old styler)

//--- Вложенные операторы
if(x=='a')
  {
   y=1;
  }
else if(x=='b')
  {
   y=2;
   z=3;
  }
else if(x=='c')
  {   
   y=4;
  }
else Print("ERROR");

and this is what the new styler does:

//--- Вложенные операторы
   if(x=='a')
     {
      y=1;
     }
   else
      if(x=='b')
        {
         y=2;
         z=3;
        }
      else
         if(x=='c')
           {
            y=4;
           }
         else
            Print("ERROR");
Стилизатор - Разработка программ - MetaTrader 5
Стилизатор - Разработка программ - MetaTrader 5
  • www.metatrader5.com
Стилизатор позволяет быстро привести оформление исходного кода к рекомендуемому стандарту. Это делает код легко читаемым, выглядящем профессионально. Грамотно оформленный код гораздо проще читать и анализировать в последующем как его автору, так и другим пользователям. Чтобы запустить стилизатор, нажмите " Стилизатор" в меню "Сервис" или...