Features of the mql5 language, subtleties and tricks - page 81

 
Probably not many people do that, so here
// Заполнение массива строками из файла - классика
int FileToStrings( const string FileName, string &Str[] )
{
  ArrayResize(Str, 0);

  const int handle = FileOpen(FileName, FILE_READ | FILE_ANSI );
  
  if (handle != INVALID_HANDLE)
  {
    while (!FileIsEnding(handle))
      Str[ArrayResize(Str, ArraySize(Str) + 1) - 1] = FileReadString(handle);
    
    FileClose(handle);
  }
  
  return(ArraySize(Str));
}

// Заполнение массива строками из файла - альтернатива
int FileToStrings2( const string FileName, string &Str[] )
{
  uchar Bytes[];
  
  return(FileLoad(FileName, Bytes) ? StringSplit(CharArrayToString(Bytes), '\n', Str) : 0);
}

void OnStart()
{
  const string FileName = "Test.txt";
  
  string Str[];  
  FileToStrings(FileName, Str);

  string Str2[];  
  FileToStrings2(FileName, Str2);
  
  ArrayPrint(Str);
  ArrayPrint(Str2);
}
I myself use the second option when I need to rasp something. Probably works faster too, haven't checked it.
 
// "Сортировка" символов Обзора рынка

// Обмен значений
template <typename T>
void Swap( T &Value1, T &Value2 )
{
  const T Tmp = Value1;
  
  Value1 = Value2;
  Value2 = Tmp;  
}

// Сортировка строк
bool ArraySort( string &Str[], const bool Increase = true )
{
  const int Compare = Increase ? 1 : -1;
  const int Size = ArraySize(Str);
  
  for (int i = 0; i < Size - 1; i++)
    for (int j = i + 1; j < Size; j++)
      if (StringCompare(Str[i], Str[j]) == Compare)
        Swap(Str[i], Str[j]);
  
  return(true);
}

// Выключение (что возможно) символов в Обзоре рынка
void MarketWatchOff()
{
  for (int i = SymbolsTotal(true) - 1; i >= 0; i--)
    SymbolSelect(SymbolName(i, true), false);
}

// Получение символов из Обзора рынка
int GetMarketWatch( string &Str[] )
{
  const int Size = ArrayResize(Str, SymbolsTotal(true));
  
  for (int i = 0; i < Size; i++)
    Str[i] = SymbolName(i, true);
    
  return(Size);
}

// Задание символов Обзора рынка
void SetMarketWatch( const string &Str[] )
{
  MarketWatchOff();
  
  const int Size = ArraySize(Str);
  
  for (int i = 0; i < Size; i++)
    SymbolSelect(Str[i], true);        
}

// "Сортировка" символов Обзора рынка
void SortMarketWatch()
{
  string Str[];
  
  GetMarketWatch(Str);
  ArraySort(Str);
  
  SetMarketWatch(Str);
}

void OnStart()
{
  SortMarketWatch();
}
 

Forum on trading, automated trading systems and testing trading strategies

Discussion of article "Creating and testing custom symbols in MetaTrader 5"

fxsaber, 2018.04.12 07:59

#property script_show_inputs

#include <fxsaber\ThirdPartyTicks\CustomSymbol.mqh> // https://www.mql5.com/ru/code/20225

// Generate M1-history from ticks
void OnStart()
{  
  MqlTick Ticks[];
  CUSTOMSYMBOL Symb;

  if (Symb.IsCustom() && (CopyTicksRange(Symb.Name, Ticks, COPY_TICKS_ALL, 0, LONG_MAX) > 0))
  {
    Symb.AddTicks(Ticks);
  
    Symb.CreateHistoryRates();
    
    ChartOpen(Symb.Name, PERIOD_CURRENT);
  }
}
 
fxsaber:
Probably not many people do so, so I use the second variant when I need to parse something. Probably works faster too, I haven't checked it.

The second option is not only better, but also more correct. The first variant is unreliable. It contains a fatal error that leads to a fatal error.

 
Ihor Herasko:

The second option is not only better, but also more correct. The first variant is unreliable. It contains fatal error and fatal error.

I did not see any special problems in the first variant. As for the second, it seems that it is used by one or two people.

Поиск - MQL5.community
Поиск - MQL5.community
  • www.mql5.com
Поиск выполняется с учетом морфологии и без учета регистра. Все буквы, независимо от того, как они введены, будут рассматриваться как строчные. По умолчанию наш поиск показывает страницы...
 
fxsaber:

I did not see any particular problem with the first option. As for the second, it seems that one or two people use it.

How about this? What about this one:

Str[ArrayResize(Str, ArraySize(Str) + 1) - 1]

if not a fatal error?

 
Ihor Herasko:

How about this? What about this:

if not a fatal error?

You can use Reserve to speed it up. But the point of Reserve is questionable in this case, because the array of complex objects is a string.

As for fatal error, handling a negative ArrayResize value is up to your taste.

 
fxsaber:

You can use Reserve to speed it up. As for the fatal error, handling a negative ArrayResize value is optional.

No, it's not about acceleration. We should think about reliability first. And that's why processing of ArrayResize value return cannot be called "at will". After all, this thread is not for beginners where the basics are explained and simplified examples are given.

P. S. By the way, ArrayResize can return a positive value, but it will still cause an array overrun error.
 
Ihor Herasko:

The processing of the ArrayResize value return can by no means be called "at will". After all, this is not a branch for beginners, where the basics are explained and simplified examples are given.

In this case, I do not see it appropriate to kill the clarity for the sake of reliability. The task was to show the second method. Here it was a demonstration of a method, not a universal ready-made solution.

You must not copy-paste my codes. They are always for training purposes only. That is the person is supposed to understand the code and having grasped the main idea he will write his own variant based on it.

P. S. By the way, you can return ArrayResize with a positive value, but you will still get an error of array overrun.
There will be no out-of-array in this situation.
 
fxsaber:

There will be no overrun of the array in this situation.

Please:

void AddElements(int &arrnArray[], int nCount)
{
   int nTotal = ArraySize(arrnArray);
   if (ArrayResize(arrnArray, nTotal + nCount) < 0)
      return;

   for (int i = nTotal + nCount - 1; i >= nTotal; --i)
      arrnArray[i] = i;
}

In cases where the arrnArray array cannot be expanded, ArrayResize will return the current array size (at least 0). Therefore, executing the body of the loop will cause the array to go outside the array.

Reason: