Preserving a string variable value when changing time frame, is there a way?

To add comments, please log in or register
pieroim
91
pieroim  

Hi,

Hi need to preserve a string variable from reset when I change TF. GlobalVariableSet is not a solution for me because I need to apply more times the same indicator on the chart with different properties, so to work correctly the GlobalVariable should have a different name for each indicator session, and this isn't possible because after the reset I should loss the temporary variable name..

Keith Watford
Moderator
20585
Keith Watford  
pieroim:

Hi,

Hi need to preserve a string variable from reset when I change TF. GlobalVariableSet is not a solution for me because I need to apply more times the same indicator on the chart with different properties, so to work correctly the GlobalVariable should have a different name for each indicator session, and this isn't possible because after the reset I should loss the temporary variable name..

There is nothing to stop you from using a magic number or even a magic string in an indicator same as in an EA. You can then write the values to a file using the magic string in the name of the file.

pieroim
91
pieroim  

Ok, if there is another solution than writing a file.. is ok.

Thank's

Piero

Fernando Carreiro
4986
Fernando Carreiro  

pieroim:

Hi need to preserve a string variable from reset when I change TF. GlobalVariableSet is not a solution for me because I need to apply more times the same indicator on the chart with different properties, so to work correctly the GlobalVariable should have a different name for each indicator session, and this isn't possible because after the reset I should loss the temporary variable name..

Ok, if there is another solution than writing a file.. is ok.

You can have your Terminal Global Variable names prefixed in such a way as to include the Symbol for example. In this way, you don't have to set a "Magic String" in order to differentiate between charts. You can also use a "MagicNumber" as part of the the variable names in order to differentiate between instances.


Keith Watford
Moderator
20585
Keith Watford  
Fernando Carreiro:

You can have your Terminal Global Variable names prefixed in such a way as to include the Symbol for example. In this way, you don't have to set a "Magic String" in order to differentiate between charts. You can also use a "MagicNumber" as part of the the variable names in order to differentiate between instances.

This wouldn't be an option in this case as he wants to put multiple instances of the same indicator on the same chart.

Also he said that he wants to preserve the value of string variables, although that can be done with GVs, not quite so simple

Fernando Carreiro
4986
Fernando Carreiro  
Keith Watford:

This wouldn't be an option in this case as he wants to put multiple instances of the same indicator on the same chart.

Also he said that he wants to preserve the value of string variables, although that can be done with GVs, not quite so simple

OP explained that he was using a string to prefix his GV names, and that is why he wanted to preserve it.

I provided a solution for two scenarios where there would be no need to preserve the string prefix (Magic string):

  1. When the Time-frame is changed on a chart but the Symbol is only used once.
  2. For other instances where a Magic Number uniquely identifies each instance irrespective of reuse of Symbol or Time-frame.
Keith Watford
Moderator
20585
Keith Watford  
Fernando Carreiro:

OP explained that he was using a variable name to prefix his GV, and that is why he wanted to preserve it.

I provided a solution for two scenarios where there would be no need to preserve the string prefix (Magic string):

  1. When the Time-frame is changed on a chart but the Symbol is only used once.
  2. For other instances where a Magic Number uniquely identifies each instance irrespective of reuse of Symbol or Time-frame.

Ok, maybe I misunderstood.

pieroim
91
pieroim  

Many thank's for your suggestion, 

initially I had the need to save a string as a value, and this was a problem solved only by saving on file.

Now I've solved using numbers to encode the string, so I can save a double variable in a global with a magic number.. it's not an immediate solution, but I believe it will work.. unless I do not make the mistake by inserting the same magic number on multiple instances and / or graphics .. better than nothing.

pieroim
91
pieroim  

Ok, it works!

Many Thank's.

Piero

alphatrading
103
alphatrading  

You can completely avoid the cumbersome handling of terminal global variables.

  • You can store a value in a MQL library where it will survive indicator init cycles until the indicator is unloaded.
  • You can store values in the chart as a hidden chart object where it will survive indicator init cycles until the chart is closed. There are some libraries in the code base.
  • You can store values directly in the chart's window object where it will survive until the chart is closed. @see http://winapi.freetechsecrets.com/win32/WIN32SetProp.htm

All those methods have the advantage of automatic clean-up once the variable's life-cycle ends.

fxsaber
15903
fxsaber  

Форум по трейдингу, автоматическим торговым системам и тестированию торговых стратегий

Нужны ли глобальные переменные терминала типа string?

fxsaber, 2017.04.10 18:25

Как вариант, таким образом можно записывать и считывать из глобальных переменных строки, простые структуры и даже массивы (например, обмениваться результатами CopyTicks)

// MQL4&5-code

#property strict

#include <TypeToBytes.mqh>

#define POSTFIX "___"

string GetName( const string Name, const int Num, const string PostFix = POSTFIX )
{
  return(Name + PostFix + (string)Num);
}

bool _GlobalVariableDel( const string Name )
{
  return(GlobalVariableDel(Name) && (GlobalVariablesDeleteAll(Name + POSTFIX) >= 0));
}

#define GLOBAL_VARIABLE_SET(A)                                                        \
template <typename T>                                                                 \
  datetime _GlobalVariableSet( const string Name, const T A )                         \
  {                                                                                   \
    _GlobalVariableDel(Name);                                                         \
                                                                                      \
    double Array[];                                                                   \
                                                                                      \
    const datetime Res = GlobalVariableSet(Name, _ArrayCopy(Array, _R(Value).Bytes)); \
    const int Size = ArraySize(Array);                                                \
                                                                                      \
    for (int i = 0; i < Size; i++)                                                    \
      GlobalVariableSet(GetName(Name, i), Array[i]);                                  \
                                                                                      \
    return(Res);                                                                      \
  }

GLOBAL_VARIABLE_SET(Value)
GLOBAL_VARIABLE_SET(&Value)
GLOBAL_VARIABLE_SET(&Value[])

#define GLOBAL_VARIABLE_GET(A)                                              \
  {                                                                         \
    double Array[];                                                         \
                                                                            \
    const int Amount = (int)Tmp;                                            \
    const int Size = ArrayResize(Array, Amount / sizeof(double) +           \
                                 ((Amount % sizeof(double) == 0) ? 0 : 1)); \
                                                                            \
    for (int i = 0; i < Size; i++)                                          \
      Array[i] = GlobalVariableGet(GetName(Name, i));                       \
                                                                            \
    uchar Bytes[];                                                          \
                                                                            \
    _ArrayCopy(Bytes, Array, 0, 0, Amount);                                 \
                                                                            \
    _W(A) = Bytes;                                                          \
  }

template <typename T>
const T _GlobalVariableGet( const string Name )
{
  T Res; // https://www.mql5.com/ru/forum/1111/page1869#comment_4854112

  double Tmp;

  if (GlobalVariableGet(Name, Tmp))
    GLOBAL_VARIABLE_GET(Res)

  return(Res);
}

template <typename T>
bool _GlobalVariableGet( const string Name, T &Value )
{
  double Tmp;
  const bool Res = GlobalVariableGet(Name, Tmp);

  if (Res)
    GLOBAL_VARIABLE_GET(Value)

  return(Res);
}

void OnStart()
{
  string Name = "Name";

// Записываем/считываем строки
  _GlobalVariableSet(Name, "Hello World!");
  Print(_GlobalVariableGet<string>(Name));

// Записываем/считываем простые структуры
  MqlTick Tick;
  SymbolInfoTick(_Symbol, Tick);

  _GlobalVariableSet(Name, Tick);
  Print(_GlobalVariableGet<MqlTick>(Name).time);

// Записываем/считываем массивы
  MqlTick Ticks[2];

  Ticks[0] = Tick;
  Ticks[1] = Tick;

  _GlobalVariableSet(Name, Ticks);

  MqlTick NewTicks[];

//  if (_GlobalVariableGet(Name, NewTicks)) // https://www.mql5.com/ru/forum/1111/page1868#comment_4853867
//    Print(NewTicks[1].time);

  _GlobalVariableDel(Name);
}
12
To add comments, please log in or register