Libraries: TypeToBytes - page 5

 
fxsaber:
Two lines with the same result
ArrayCompare(Array1, Array2) == 0
_R(Array1) == Array2
 
// Read/Write private fields of simple structures

#include <TypeToBytes.mqh>

template <typename T>
struct STRUCT
{
private:
  T Data; // private field
  
public:
  T GetData( void ) const
  {
    return(this.Data);
  }
};

void OnStart()
{    
  STRUCT<int> Struct = {0};  
  
  _W(Struct) = 2;          // Write access to private field
  Print(Struct.GetData()); // make sure that it is
  
  Print(_R(Struct)[0]);    // Read-access to private field
}
 
The library prescribes a container class that stores variables and arrays of any other simple types in an array of a given type.
// Example of working with a container
#include <TypeToBytes.mqh>

#define  PRINT(A) Print(#A + " = " + (string)(A));

void OnStart()
{
  // Arbitrary data for the example
  string Str[] = {"123", "Hello World!"};
  double Num = 5;
  MqlTick Tick = {0};
  Tick.bid = 1.23456;
  
  CONTAINER<long> Container;  // Create a container - everything will be stored in an array of a simple type (long is chosen in the example)
  
  // Fill the container with different data
  Container[0] = Str;
  Container[1] = Num;
  Container[2] = Tick;
  
  ArrayPrint(Container.Data); // Output the contents of the array in which the container stores all data
  
  // Print the types of data stored in the container
  for (int i = 0; i < Container.GetAmount(); i++)
    PRINT(Container[i].GetType())
    
  // Let's get the data itself 
  string Str2[];
  Container[0].Get(Str2);                // Got the array
  ArrayPrint(Str2);
  
  PRINT(Container[1].Get<double>())      // We got a number
  PRINT(Container[2].Get<MqlTick>().bid) // We got the structure
  
  Container[1] = "Replace";   // Replaced data by index
  
  // Verify that the replacement has taken place 
  PRINT(Container[1].GetType())
  PRINT(Container[1].Get<string>())
}
 
fxsaber:
The library contains a container class that stores variables and arrays of any other simple types in an array of a given type.

Example of practical application in Report-bible

Send a frame with different data

        string Str;
        REPORT::ToString(Str);

        double Balance[];
        REPORT::GetBalanceHistory(Balance);

      #ifdef __TYPETOBYTES__
        CONTAINER<uchar> Container;

        Container[0] = Str;     // put the report string in the container
        Container[1] = Balance; // added a double array of the balance change history to the container as well

        ::FrameAdd(NULL, 0, ::AccountInfoDouble(ACCOUNT_BALANCE), Container.Data); // Sent a frame with string report and balance array
      #else  // __TYPETOBYTES__

Receive a frame with different data

 CONTAINER<uchar> Container;

    while (::FrameNext(Pass, Name, ID, Value, Container.Data))
    {
        string Str;
        Container[0].Get(Str);     // Get the report string from the frame

        double Balance[];
        Container[1].Get(Balance); // Get the corresponding double array from the frame

// .....
Report
Report
  • 2017.07.19
  • fxsaber
  • www.mql5.com
Библиотека для MetaTrader 4/5, которая позволяет формировать отчеты по истории торгов.
 
Another example of Container application

Forum on trading, automated trading systems and testing trading strategies

Questions from MQL5 MT5 MetaTrader 5 beginners

fxsaber, 2017.08.23 14:10

You need to use Frame Mode to write the Agents data into one file.

// Example of recording Agent data (including Cloud Agents) into one file
input int Range = 0;

void OnTick()
{
// ....
}

// Open the file only in Single Run or Frame modes.
const int handle = ((MQLInfoInteger(MQL_TESTER) && !MQLInfoInteger(MQL_OPTIMIZATION)) || MQLInfoInteger(MQL_FRAME_MODE)) ?
                   FileOpen(__FILE__, FILE_WRITE | FILE_TXT) : INVALID_HANDLE;

// Data preparation
void GetData( string &Str, MqlTick &Ticks[], double &Balance )
{
  Str = "Hello World!";
  
  CopyTicks(_Symbol, Ticks, COPY_TICKS_ALL, 0, 2); // Last two ticks (example)
  
  Balance = AccountInfoDouble(ACCOUNT_BALANCE);
}

// Writing data
void SaveData( const string &Str, const MqlTick &Ticks[], const double Balance )
{
  FileWrite(handle, Str);
  
  for (int i = 0; i < ArraySize(Ticks); i++)
    FileWrite(handle, Ticks[i].bid);
    
  FileWrite(handle, Balance);
}

void OnTesterDeinit()
{
  if (handle != INVALID_HANDLE)  
    FileClose(handle);
    
  ChartClose();
}

#include <TypeToBytes.mqh> // https://www.mql5.com/en/code/16280

double OnTester()
{
  string Str;
  MqlTick Ticks[];
  double Balance;
  
  GetData(Str, Ticks, Balance); // Preparing data for recording

  if (MQLInfoInteger(MQL_OPTIMIZATION)) // Optimisation
  {
    CONTAINER<uchar> Container; // https://www.mql5.com/ru/forum/95447/page4#comment_5464205
    
    Container[0] = Str;
    Container[1] = Ticks;
    Container[2] = Balance;
  
    FrameAdd(NULL, 0, 0, Container.Data); // Sent data from the Agent to the Terminal
  }
  else // Single run
  {    
    if (handle != INVALID_HANDLE)
      SaveData(Str, Ticks, Balance); // The data will be written to the MQL5\Files folder of the Agent (not the Terminal)
    
    FileClose(handle);
  }
  
  return(0);
}

void OnTesterPass()
{    
  if (handle != INVALID_HANDLE)
  {
    ulong Pass;
    string Name;
    long ID;
    double Value;
  
    CONTAINER<uchar> Container; // https://www.mql5.com/ru/forum/95447/page4#comment_5464205
  
    while (FrameNext(Pass, Name, ID, Value, Container.Data))
    {
      string Str;
      MqlTick Ticks[];
      double Balance;
      
      // Received data from the Agent
      Container[0].Get(Str);
      Container[1].Get(Ticks);
      Container[2].Get(Balance);
      
// FileWrite(handle, Pass); // If you want to write the number of the passage
      SaveData(Str, Ticks, Balance); // The data will be written to the MQL5\Files folder of the Terminal (not the Agent)
    }
  }
}
 
Example of standard data coding (red - library usage)

Forum on trading, automated trading systems and testing trading strategies

New version of MetaTrader 5 build 1640: creating and testing your own financial instruments

fxsaber, 2017.10.10 07:51

// How much MqlRates data and packing/unpacking speed are squeezed
#include <TypeToBytes.mqh> // https://www.mql5.com/en/code/16280

#define  TOSTRING(A) #A + " = " + (string)(A) + "\n"

void OnStart()
{
  MqlRates Rates[];
  uchar Tmp[];  
  
  const int Amount = CopyRates(_Symbol, PERIOD_CURRENT, 0, Bars(_Symbol, PERIOD_CURRENT), Rates) * sizeof(MqlRates);  
  
  // Archiving
  const ulong StartTime1 = GetMicrosecondCount();
  const int AmountZIP = CryptEncode(CRYPT_ARCH_ZIP, _R(Rates).Bytes, Tmp, Tmp);
  
  Print(TOSTRING(Amount) + TOSTRING(AmountZIP) + TOSTRING((double)Amount / AmountZIP) + TOSTRING(GetMicrosecondCount() - StartTime1));
  
  uchar Tmp2[];
  
  // Unzip
  const ulong StartTime2 = GetMicrosecondCount();
  CryptDecode(CRYPT_ARCH_ZIP, Tmp, Tmp2, Tmp2);
  Print(TOSTRING(GetMicrosecondCount() - StartTime2));
  
  Print(TOSTRING(_R(Rates) == Tmp2)); // Does the data match?
}
 
Using the library to put/retrieve any data into/from a string
// Cross-platform example of passing arbitrary data via a custom event

#include <fxsaber\HistoryTicks\Data_String.mqh> // https://www.mql5.com/en/code/20298

// Print arbitrary data
template <typename T>
bool MyPrint( const T &Value )
{
  T Array[1];
  
  Array[0] = Value;
  
  ArrayPrint(Array, _Digits, NULL, 0, WHOLE_ARRAY, ARRAYPRINT_HEADER | ARRAYPRINT_ALIGN);
  
  return(true);
}

void OnChartEvent( const int id, const long &lparam, const double&, const string &sparam )
{
  // Print out the obtained data
  if ((id == CHARTEVENT_CUSTOM) &&
      (lparam ?  MyPrint(DATA_STRING::FromString<MqlDateTime>(sparam)) // Got MqlDateTime
              : !MyPrint(DATA_STRING::FromString<MqlTick>(sparam))))   // Got MqlTick
    ExpertRemove(); // Out of the example
}

void OnInit()
{
  MqlTick Tick;  
  MqlDateTime DateTime;
  
  // Filled in the values
  SymbolInfoTick(_Symbol, Tick);  
  TimeCurrent(DateTime);

  // Passed on
  EventChartCustom(0, 0, 0, 0, DATA_STRING::ToString(Tick));     // Passed MqlTick
  EventChartCustom(0, 0, 1, 0, DATA_STRING::ToString(DateTime)); // Passed MqlDateTime
}
 
A simple example of use

Forum on trading, automated trading systems and testing trading strategies

Beta version of MetaTrader 5 build 1995: Economic Calendar, MQL5 programs as services and API for R language

fxsaber, 2019.02.18 16:36

#include <TypeToBytes.mqh> // https://www.mql5.com/en/code/16280

int StringToShortArray2( const string Str, ushort &Array[], const int = 0, const int = 0 )
{
  const int Size = ArrayResize(Array, StringLen(Str));
  
  for (int i = 0; i < Size; i++)
    _W(Array[i]) = Str[i];
  
  return(Size);
}
 

Hi. So it's working.

struct Message
  {
   int               cnt;
   bool              res;
   int               ter;
  };

#include <Exchange_Data.mqh>

#define  AMOUNT 100

EXCHANGE_DATA<Message>ExchangeTicks(AMOUNT,true);
//+------------------------------------------------------------------+
//| Custom indicator initialisation function |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   static Message Ticks[1];
   Ticks[0].cnt=1;
   Ticks[0].res=true;
   Ticks[0].ter=1;
   ExchangeTicks.DataSave(Ticks);
//---
   return(INIT_SUCCEEDED);
  }

This is how it works.

struct Message
  {
   int               cnt;
   bool              res;
   int               ter;
   string            str;
  };

#include <Exchange_Data.mqh>

#define  AMOUNT 1000

EXCHANGE_DATA<Message>ExchangeTicks(AMOUNT,true);
//+------------------------------------------------------------------+
//| Custom indicator initialisation function |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   static Message Ticks[1];
   Ticks[0].cnt=1;
   Ticks[0].res=true;
   Ticks[0].ter=1;
   Ticks[0].str = "SDf";
   ExchangeTicks.DataSave(Ticks);
//---
   return(INIT_SUCCEEDED);
  }

I got it from here for MT4

https://www.mql5.com/ru/forum/5905/page11#comment_6134460
 
Aleksei Beliakov:

It's like that.

#define  DEFINE_STRING(A)                        \
  struct STRING##A                              \
  {                                             \
  private:                                      \
    short Array[A];                             \
                                                \
  public:                                       \
    void operator =( const string Str )         \
    {                                           \
      ::StringToShortArray(Str, this.Array);    \
                                                \
      return;                                   \
    }                                           \
                                                \
    string operator []( const int = 0 ) const   \
    {                                           \
      return(::ShortArrayToString(this.Array)); \
    }                                           \
  };                                            
  
DEFINE_STRING(128) // An analogue of a string that has a maximum of 128 characters.

#undef  DEFINE_STRING

struct Message
  {
   int               cnt;
   bool              res;
   int               ter;
   STRING128         str;
  };