Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1331

 

Help fix the indicator, it is not displayed in the MT5 terminal, it gives errors during compilation.

 //--- descriзгo
#property description "Script cria objeto grбfico de \"Texto\"."
//--- janela de exibiзгo dos parвmetros de entrada durante inicializaзгo do script
#property script_show_inputs


//--- entrada de parвmetros do script
input int                IHistoryBars= 25 ;           // Check Historical Data
input string             InpFont= "Tahoma" ;       // Font Type
input int                InpFontSize= 7 ;           // Size of fonts
input color              UpColor= clrGold ;         // Cor Up
input color              DwColor= clrRoyalBlue ;         // Cor Dw
input color              HLColor= clrAqua ;         // Cor Center
input bool               InpBack= false ;           // Objeto de fundo
input bool               InpSelection= false ;       // Destaque para mover
input bool               InpHidden= true ;           // Ocultar na lista de objetos
input bool               WithDigit= true ;           // Ocultar na lista de objetos
input long               InpZOrder= 0 ;             // Prioridade para clique do mouse


int digits= 0 ,extradig= 0 ;

double             InpAngle= 0.0 ;           // Вngulo de inclinaзгo em graus
ENUM_ANCHOR_POINT InpAnchor= ANCHOR_CENTER ; // Tipo de ancoragem
double    gBars= 0 ;
double    gTotalRates= 0 ;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnInit ()
  {
   digits= MathPow ( 10 , _Digits -extradig);
   if (WithDigit) extradig= 1 ;

  }
//+------------------------------------------------------------------+
//| Mover ponto de ancoragem                                         |
//+------------------------------------------------------------------+
bool TextMove( const long    chart_ID= 0 ,   // ID do grбfico
               const string name= "Text" , // nome do objeto
               datetime      time= 0 ,       // coordenada do ponto de ancoragem do tempo
               double        price= 0 )     // coordenada do ponto de ancoragem do preзo
  {
//--- se a posiзгo do ponto nгo estб definida, mover para a barra atual tendo o preзo Bid
   if (!time)
      time= TimeCurrent ();
   if (!price)
      price= SymbolInfoDouble ( Symbol (), SYMBOL_BID );
//--- redefine o valor de erro
   ResetLastError ();
//--- mover o ponto de ancoragem
   if (! ObjectMove (chart_ID,name, 0 ,time,price))
     {
       Print ( __FUNCTION__ ,
             ": falha ao mover o ponto de ancoragem! Cуdigo de erro = " , GetLastError ());
       return ( false );
     }
//--- sucesso na execuзгo
   return ( true );
  }
//+------------------------------------------------------------------+
//| Verificar valores de ponto de ancoragem e definir valores padrгo |
//| para aqueles vazios                                              |
//+------------------------------------------------------------------+
void ChangeTextEmptyPoint( datetime &time, double &price)
  {
//--- se o tempo do ponto nгo estб definido, serб na barra atual
   if (!time)
      time= TimeCurrent ();
//--- se o preзo do ponto nгo estб definido, ele terб valor Bid
   if (!price)
      price= SymbolInfoDouble ( Symbol (), SYMBOL_BID );
  }
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit ( const int reason)
  {
   ClearMyObjects();
   Print ( "Deinit Value Chart, reason = " + IntegerToString (reason));
  }
//+------------------------------------------------------------------+
//| Value Chart                                                      | 
//+------------------------------------------------------------------+
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 &TickVolume[],
                 const long &Volume[],
                 const int &Spread[])
  {

//--- definir a forma como muitas vezes os textos serгo exibidos
   int scale=( int ) ChartGetInteger ( 0 , CHART_SCALE );
   int bars=( int ) ChartGetInteger ( 0 , CHART_VISIBLE_BARS )+ 3 ;
   double value;
   digits= MathPow ( 10 , _Digits -extradig);

//--- definir o passo
   int step= 1 ;
   switch (scale)
     {
       case 0 :
         step= 12 ;
         break ;
       case 1 :
         step= 6 ;
         break ;
       case 2 :
         step= 4 ;
         break ;
       case 3 :
         step= 2 ;
         break ;
     }
   gTotalRates=rates_total;
   gBars=bars;
   for ( int i=rates_total- 1 ;i>rates_total-bars;i-=step) 
     {
       if (Close[i]>Open[i])
        {
         // bullish candle
         value=(Close[i]-Open[i])*digits;
         //Print(Close[i]-Open[i], "->", Close[i]-Open[i]*digits);

         TextCreate( 0 , "Text_" +( string )i+( string ) PERIOD_CURRENT , 0 ,Time[i],(Close[i]+Open[i])/ 2 , DoubleToString (value,extradig),InpFont,InpFontSize,
                    UpColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder);

         value=(Open[i]-Low[i]) *digits;
         if (!TextCreate( 0 , "TextL_" +( string )i+( string ) PERIOD_CURRENT , 0 ,Time[i],Low[i], DoubleToString (value,extradig),InpFont,InpFontSize,
            HLColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder)) {       return 0 ;     }

         value=(High[i]-Close[i]) *digits;
         if (!TextCreate( ChartID (), "TextH_" +( string )i+( string ) PERIOD_CURRENT , 0 ,Time[i],High[i], DoubleToString (value,extradig),InpFont,InpFontSize,
            HLColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder)) {       return 0 ;     }

           } else {

         value=(Open[i]-Close[i]) *digits;
         if (!TextCreate( ChartID (), "Text_" +( string )i+( string ) PERIOD_CURRENT , 0 ,Time[i],(Close[i]+Open[i])/ 2 , DoubleToString (value,extradig),InpFont,InpFontSize,
            DwColor,-InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder)) {       return 0 ;      }

         value=(Close[i]-Low[i]) *digits;
         if (!TextCreate( ChartID (), "TextL_" +( string )i+( string ) PERIOD_CURRENT , 0 ,Time[i],Low[i], DoubleToString (value,extradig),InpFont,InpFontSize,
            HLColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder)) {       return 0 ;     }

         value=(High[i]-Open[i]) *digits;
         if (!TextCreate( ChartID (), "TextH_" +( string )i+( string ) PERIOD_CURRENT , 0 ,Time[i],High[i], DoubleToString (value,extradig),InpFont,InpFontSize,
            HLColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder)) {       return 0 ;     }
        }

     }
   ChartRedraw ();
   return 0 ;
  }
//+------------------------------------------------------------------+
//|  Trace Arrow Function                                            |
//+------------------------------------------------------------------+
void Trace( string name, int sens, double price, datetime time, color couleur)
  {
   ObjectCreate ( 0 ,name, OBJ_ARROW , 0 ,time,price);
   if (sens== 1 )
       ObjectSetInteger ( 0 ,name, OBJPROP_ARROWCODE , 233 );
   if (sens==- 1 )
       ObjectSetInteger ( 0 ,name, OBJPROP_ARROWCODE , 234 );
   ObjectSetInteger ( 0 ,name, OBJPROP_COLOR ,couleur);
   ObjectSetInteger ( 0 ,name, OBJPROP_WIDTH , 5 );
  }
//+------------------------------------------------------------------+
//|   Delete Arrow Function                                          |
//+------------------------------------------------------------------+  
void ClearMyObjects() 
  {
   string name;
   int scale=( int ) ChartGetInteger ( 0 , CHART_SCALE );
   int bars=( int ) ChartGetInteger ( 0 , CHART_VISIBLE_BARS )+ 3 ;
   double value;
   digits= MathPow ( 10 , _Digits -extradig);
   int step= 1 ;
   switch (scale)
     {
       case 0 :
         step= 12 ;
         break ;
       case 1 :
         step= 6 ;
         break ;
       case 2 :
         step= 4 ;
         break ;
       case 3 :
         step= 2 ;
         break ;
     }
   for ( int i=gTotalRates- 1 ;i>gTotalRates-bars;i-=step) 
     {
       if (!TextDelete( ChartID (), "Text_" +( string )i+( string ) PERIOD_CURRENT )){}
       if (!TextDelete( ChartID (), "TextH_" +( string )i+( string ) PERIOD_CURRENT )){}
       if (!TextDelete( ChartID (), "TextL_" +( string )i+( string ) PERIOD_CURRENT )){}
       //--- redesenhar o grбfico
     }
   ChartRedraw ();

  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Alterar o texto do objeto                                        |
//+------------------------------------------------------------------+
bool TextChange( const long    chart_ID= 0 ,   // ID do Grбfico
                 const string name= "Text" , // nome do objeto
                 const string text= "Text" ) // texto
  {
//--- redefine o valor de erro
   ResetLastError ();
//--- alterar texto do objeto
   if (! ObjectSetString (chart_ID,name, OBJPROP_TEXT ,text))
     {
       Print ( __FUNCTION__ ,
             ": falha ao alterar texto! Cуdigo de erro = " , GetLastError ());
       return ( false );
     }
//--- sucesso na execuзгo
   return ( true );
  }
//+------------------------------------------------------------------+
//| Excluir objeto Texto                                             |
//+------------------------------------------------------------------+
bool TextDelete( const long    chart_ID= 0 ,   // Id do Grбfico
                 const string name= "Text" ) // nome do objeto
  {
//--- redefine o valor de erro
   ResetLastError ();
//--- excluir o objeto
   if (! ObjectDelete (chart_ID,name))
     {
       Print ( __FUNCTION__ ,
             ": falha ao excluir o objeto \"Texto\"! Cуdigo de erro = " , GetLastError ());
       return ( false );
     }
//--- sucesso na execuзгo
   return ( true );
  }
//+------------------------------------------------------------------+
//| Criando objeto Texto                                             |
//+------------------------------------------------------------------+
bool TextCreate( const long               chart_ID= 0 ,               // ID do grбfico
                 const string             name= "Text" ,               // nome do objeto
                 const int                sub_window= 0 ,             // нndice da sub-janela
                 datetime                 time= 0 ,                   // ponto de ancoragem do tempo
                 double                   price= 0 ,                   // ponto de ancoragem do preзo
                 const string             text= "Text" ,               // o prуprio texto
                 const string             font= "Arial" ,             // fonte
                 const int                font_size= 10 ,             // tamanho da fonte
                 const color              clr= clrRed ,               // cor
                 const double             angle= 0.0 ,                 // inclinaзгo do texto
                 const ENUM_ANCHOR_POINT anchor= ANCHOR_CENTER , // tipo de ancoragem
                 const bool               back= false ,               // no fundo
                 const bool               selection= false ,           // destaque para mover
                 const bool               hidden= true ,               // ocultar na lista de objetos
                 const long               z_order= 0 )                 // prioridade para clicar no mouse
  {

   if ( ObjectFind (chart_ID,name)==- 1 ) 
     {

       //--- definir as coordenadas de pontos de ancoragem, se eles nгo estгo definidos
       //--- redefine o valor de erro
       ResetLastError ();
       //--- criar objeto Texto
       if (! ObjectCreate (chart_ID,name, OBJ_TEXT ,sub_window,time,price)) 
        {
         Print ( __FUNCTION__ ,
               ": falha ao criar objeto \"Texto\"! Cуdigo de erro = " , GetLastError ());
         return ( false );
        }
       //--- definir o texto
       ObjectSetString (chart_ID,name, OBJPROP_TEXT ,text);
       //--- definir o texto fonte
       ObjectSetString (chart_ID,name, OBJPROP_FONT ,font);
       //--- definir tamanho da fonte
       ObjectSetInteger (chart_ID,name, OBJPROP_FONTSIZE ,font_size);
       //--- definir o вngulo de inclinaзгo do texto
       ObjectSetDouble (chart_ID,name, OBJPROP_ANGLE ,angle);
       //--- tipo de definiзгo de ancoragem
       ObjectSetInteger (chart_ID,name, OBJPROP_ANCHOR ,anchor);
       ObjectSetInteger (chart_ID,name, OBJPROP_ALIGN , ALIGN_CENTER );

       //--- definir cor
       ObjectSetInteger (chart_ID,name, OBJPROP_COLOR ,clr);
       //--- exibir em primeiro plano (false) ou fundo (true)
       ObjectSetInteger (chart_ID,name, OBJPROP_BACK ,back);
       //--- habilitar (true) ou desabilitar (false) o modo de mover o objeto com o mouse
       ObjectSetInteger (chart_ID,name, OBJPROP_SELECTABLE ,selection);
       ObjectSetInteger (chart_ID,name, OBJPROP_SELECTED ,selection);
       //--- ocultar (true) ou exibir (false) o nome do objeto grбfico na lista de objeto 
       ObjectSetInteger (chart_ID,name, OBJPROP_HIDDEN ,hidden);
       //--- definir a prioridade para receber o evento com um clique do mouse no grбfico
       ObjectSetInteger (chart_ID,name, OBJPROP_ZORDER ,z_order);
       ObjectSetDouble (chart_ID,name, OBJPROP_PRICE ,price);
       ObjectSetInteger (chart_ID,name, OBJPROP_TIME ,time);

       //--- sucesso na execuзгo
       return ( true );
        } else {
      ChangeTextEmptyPoint(time,price);

       ObjectSetString (chart_ID,name, OBJPROP_TEXT ,text);
       ObjectSetInteger (chart_ID,name, OBJPROP_COLOR ,clr);
       ObjectSetInteger (chart_ID,name, OBJPROP_ANCHOR ,anchor);
       ObjectSetInteger (chart_ID,name, OBJPROP_ALIGN , ALIGN_CENTER );
       ObjectSetDouble (chart_ID,name, OBJPROP_ANGLE ,angle);
       ObjectSetDouble (chart_ID,name, OBJPROP_PRICE ,price);
       ObjectSetInteger (chart_ID,name, OBJPROP_TIME ,time);
       ObjectSetString (chart_ID,name, OBJPROP_FONT ,font);
       //--- definir tamanho da fonte
       ObjectSetInteger (chart_ID,name, OBJPROP_FONTSIZE ,font_size);
       ObjectSetInteger (chart_ID,name, OBJPROP_YDISTANCE , 100 );

/*ObjectSetString(chart_ID,name,OBJPROP_FONT,Font);
      ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,Size);*/
       return ( true );
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnChartEvent ( const int id,         // Event ID
                   const long & lparam,   // Parameter of type long event
                   const double & dparam, // Parameter of type double event
                   const string & sparam   // Parameter of type string events
                  )
  {
   if (id== CHARTEVENT_CHART_CHANGE )
     {
      ClearMyObjects();
     }

  }
//+------------------------------------------------------------------+
Files:
 
Green handsome:

Help fix the indicator, it is not displayed in the MT5 terminal, it gives errors when compiling.

The easiest way is to set ArraySetAsSeries(Open,true) ; ArraySetAsSeries(Close,true) ; and so on in OnCalculate at the very beginning of all arrays.

this is the traditional surprise on the face of it: in 5 the default indexing directions are different than in 4.

indicator does not use buffers, it just builds graph objects - after start press Ctrl+B and see where it put them there

 

Digging through documentation and forum ...
How to make variables of pointer type global [in the example var], if they are created in OnInit() by string:

CObj* var=new CObj(p1,p2,p3);

and the number of objects and constructor parameters are not known in advance and are calculated in OnInit() ?

 
Mikhail Tkachev:

Digging through documentation and forum ...
How to make variables of pointer type global, if they are created in OnInit():

and the number of objects and constructor parameters are not known in advance and are calculated in OnInit() ?

I don't understand anything, but pass an array of pointers CArrayObj to the objects created in OnInit()

Документация по MQL5: Стандартная библиотека / Коллекции данных / CArrayObj
Документация по MQL5: Стандартная библиотека / Коллекции данных / CArrayObj
  • www.mql5.com
CArrayObj - Коллекции данных - Стандартная библиотека - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Artyom Trishkin:

Nothing understood, but pass an array of CArrayObj pointers to objects created in OnInit()

Artem, thank you for your reply.
I apologize for unclear question)
There are three global variables of pointer type to an object in Expert Advisor: var1, var2, var3.

Before executing OnInit(), it is unknown whether all these variables will be needed (this is related to timeframes), also unknown are the parameters for constructors, which will initialize objects.
How to create such variables in OnInit() so that they are global?

 
Mikhail Tkachev:

Artem, thank you for your reply.
I apologize for unclear question)
Three global variables of pointer type can be used in EA: var1, var2, var3.

Before executing OnInit(), it is unknown whether all these variables will be needed (this is related to timeframes), also unknown are the parameters for constructors that will initialize objects.
How to create such variables in OnInit(), so that they are global?

I don't know what magic constructor you have there, which contains only unknowns :)

You don't have to declare objects as instances beforehand.

You need to declare one array CArrayObj. Your objects themselves must be descendants of CObject.

Create your object by new and add a pointer to it to the list.

Create the next object and add it to the list, and so on.

This list - a pointer to it (and the list is declared globally) - is passed to your constructors.

But here's how you were going to do constructors with arguments unknown in advance - I don't understand it a bit. Try to clarify it

 
Artyom Trishkin:


But here's how you're going to make constructors with arguments unknown in advance - I'm a bit confused here. Try to explain it

Creation of CIsNewBar typeobjects for each used timeframe for each symbol.
Characters are specified by one line with separators in input parameter, so you can't create all objects beforehand before OnInit().
I.e. the first unknown constructor parameter is a symbol.
The second unknown constructor parameter is a timeframe, as each symbol will have its own set of timeframes, similarly passed by a string with delimiters in the input-parameter.

HH.There was a problem with theCArrayObj class: when accessing elements of typeCArrayObj* ArrayObj. At(0), the class members of the object which is At(0) are unavailable, although these class members are exactly public, i.e. a construct of type ArrayObj.At(0).method(parameter) doesn't work.
And
I'm also afraid to use these libraries, maybe something will change in them when updating the terminal, and my Expert Advisor will suddenly stop working...
 
Mikhail Tkachev:

Create CIsNewBar typeobjects for each timeframe used for each symbol.
Characters are specified by one line with separators in input parameter, so it is impossible to create all objects before OnInit() in advance.
I.e. the first unknown constructor parameter is a symbol.
The second unknown constructor parameter is a timeframe, as each symbol will have its own set of timeframes, similarly passed by a string with delimiters in the input-parameter.

P.S.There was a problem with theCArrayObj class: when accessing elements of typeCArrayObj* ArrayObj. At(0), the class members of the object that At(0) is not available, although these class members are exactly public, i.e. a construct like ArrayObj.At(0).method(parameter) doesn't work.
And
I'm also afraid to use these libraries, maybe something will change in them when updating the terminal, and my Expert Advisor will suddenly stop working...

It's all wrong somehow...

Write in simple words what you want to do. Without any reference to your attempts to code it all.

 
Artyom Trishkin:

It just doesn't feel right...

Write in simple words what you want to do. Without any mention of your attempts to code it all.

Multicurrency Expert Advisor.
The list of symbols is specified via input parameter, the string with the delimiter "AUDUSD,EURUSD,GBPUSD...", the number of symbols is not predefined.
For each symbol, there are two timeframes, on which its "own" trading system works.
Correspondingly, there are two input parameters, strings delimited by : short timeframe for a respective symbol "M1,M30,M5..."
a long timeframe for the respective symbol "H1,D1,H4.."
I.e. for AUDUSD the timeframes are M1 and H1, for EURUSD M30 and D1, etc.
In OnTick(), for each symbol, it is necessary to track the appearance of a new bar on both (short and long) timeframes to make trading decisions.
I tried to write it as simply as possible)

 
Mikhail Tkachev:

Multicurrency Expert Advisor.
The list of symbols is set via input parameter, a string with separator "AUDUSD,EURUSD,GBPUSD...", the number of symbols is not predefined.
For each symbol, there are two timeframes, on which its "own" trading system works.
Correspondingly, there are two input parameters, strings delimited by : short timeframe for a respective symbol "M1,M30,M5..."
a long timeframe for the respective symbol "H1,D1,H4.."
I.e. for AUDUSD the timeframes are M1 and H1, for EURUSD M30 and D1, etc.
In OnTick(), for each symbol, it is necessary to track the appearance of a new bar on both (short and long) timeframes to make trading decisions.
I tried to write it in the easiest way possible.)

Do you already have a class for a new bar?

And what exactly do the input parameters look like?