Errors, bugs, questions - page 2270

 

What is the difference

SetIndexBuffer(1,ValuesPainting,INDICATOR_COLOR_INDEX);

и

PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrBlue);

?

I'm twisting the code and can't figure out how to color the mouwing.

If one colour is growing and another is falling.

Can someone show me an example?

 
Vladimir Pastushak:

I'm spinning the code and I can't figure out how to colour the mouwing.

If one colour rises, if another falls.

Can anybody show me an example?

I am just learning MQL5, but it should look like this:

//+------------------------------------------------------------------+
//|                                                         myMA.mq5 |
//|                                                            IgorM |
//|                              https://www.mql5.com/ru/users/igorm |
//+------------------------------------------------------------------+
#property copyright "IgorM"
#property link      "https://www.mql5.com/ru/users/igorm"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   2
//--- plot Red
#property indicator_label1  "Red"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2
//--- plot Blue
#property indicator_label2  "Blue"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrBlue
#property indicator_style2  STYLE_SOLID
#property indicator_width2  2
//--- input parameters
input int      PeriodMA=10;
//--- indicator buffers
double         RedBuffer[];
double         BlueBuffer[];
int handleMA;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   ArraySetAsSeries(RedBuffer,true);
   ArraySetAsSeries(BlueBuffer,true);
   SetIndexBuffer(0,RedBuffer,INDICATOR_DATA);
   SetIndexBuffer(1,BlueBuffer,INDICATOR_DATA);
   handleMA=iMA(NULL,0,PeriodMA,0,MODE_SMA,PRICE_CLOSE);

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const int begin,
                const double &price[])
  {
//---
   int i,limit;
   double ma[];
   if(prev_calculated==0) limit=rates_total-2; else limit=rates_total-prev_calculated;
   for(i=limit;i>=0;i--)
     {
      CopyBuffer(handleMA,0,i,2,ma);
      if(ma[0]<ma[1])
        {
         RedBuffer[i]=ma[0]; BlueBuffer[i]=EMPTY_VALUE;
        }
      else
        {
         BlueBuffer[i]=ma[0];RedBuffer[i]=EMPTY_VALUE;
        }
     }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
 
A compilation error:
template<typename T>
void f( T& ) {}
void g1() { class A {} a; f( a ); } //(1)//нормально 
void g2() { class A {} a; f( a ); } //(2)//Error: '&' - parameter conversion not allowed

What is the fundamental difference between (1) and (2) ? Why is there an error in one case and a normal error in the other?

 
A100:

And what is the fundamental difference between (1) and (2) ? Why is there an error in one case and normal in the other?

So classes within functions can have the same name but different contents. The signature f is not clear in the second variant.

After the first one it is defined. And after the second one it is not redefined with the same name.

 
Vladimir Pastushak:

What is the difference

SetIndexBuffer(1,ValuesPainting,INDICATOR_COLOR_INDEX);

и

PlotIndexSetInteger(0,PLOT_LINE_COLOR,1,clrBlue);

?

I'm twisting the code and can't figure out how to color the mouwing.

If one colour is growing and another is falling.

Can someone show me an example?

//+------------------------------------------------------------------+
//|                                                      ColorMA.mq5 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                             https://mql5.com/ru/users/artmedia70 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://mql5.com/ru/users/artmedia70"
#property version   "1.00"
#property description "Colored Moving Average"
#property indicator_chart_window
#property indicator_buffers 2    // Всего буферов 2 - рисуемый буфер и буфер цвета
#property indicator_plots   1    // Один рисуемый буфер
//--- plot ClrMA
#property indicator_label1  "Colored MA"
#property indicator_type1   DRAW_COLOR_LINE
#property indicator_color1  clrBlue,clrRed,clrDarkGray
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2
//--- input parameters
input uint                 InpPeriod         =  14;            // Период расчёта
input ENUM_MA_METHOD       InpMethod         =  MODE_SMA;      // Метод расчёта
input ENUM_APPLIED_PRICE   InpAppliedPrice   =  PRICE_CLOSE;   // Цена расчёта
//--- indicator buffers
double         BufferMA[];       // Рисуемый буфер
double         BufferColors[];   // Буфер цвета
//--- global variables
int            period;
int            handle_ma;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- set global variables
   period=int(InpPeriod<1 ? 1 : InpPeriod);
//--- indicator buffers mapping
   SetIndexBuffer(0,BufferMA,INDICATOR_DATA);            // Рисуемый буфер
   SetIndexBuffer(1,BufferColors,INDICATOR_COLOR_INDEX); // Буфер цвета
//--- setting indicator parameters
   IndicatorSetString(INDICATOR_SHORTNAME,"Colored MA");
   IndicatorSetInteger(INDICATOR_DIGITS,Digits());
//--- setting buffer arrays as timeseries
   ArraySetAsSeries(BufferMA,true);
   ArraySetAsSeries(BufferColors,true);
//--- create MA's handles
   ResetLastError();
   handle_ma=iMA(NULL,PERIOD_CURRENT,period,0,InpMethod,InpAppliedPrice);
   if(handle_ma==INVALID_HANDLE)
     {
      Print("Не удалось создать хэндл iMA(",(string)period,") ",EnumToString(InpAppliedPrice),". Ошибка: ",GetLastError());
      return INIT_FAILED;
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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 &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//--- Проверка и расчёт количества просчитываемых баров
   if(rates_total<fmax(period,4)) return 0;  // три бара и меньше в расчёт не берём
//--- Проверка и расчёт количества просчитываемых баров
   int limit=rates_total-prev_calculated;
   if(limit>1)
     {
      /*
      Почему больше 1. Например, загрузилась история, и разница будет больше одного.
      Если все нормально, то разница rates_total-prev_calculated равна или 0, или 1
      0 - пришел новый тик, новый бар формироваться не начал.
      1 - пришел новый тик и начал формироваться новый бар
      */
      limit=rates_total-2; // rates_total - это Bars для текущего символа и периода
                           // Если не требуется проверять в цикле расчёта i+число, то limit=rates_total-1 (чтобы не вылететь за пределы массива), 
                           // иначе, если требуется проверять, например, i+period, то limit=rates_total-period-1
      ArrayInitialize(BufferMA,EMPTY_VALUE);
      ArrayInitialize(BufferColors,2);
     }
//--- Подготовка данных - в данном случае это и есть расчёт МА - копирование в буфер её значений из хэндла
   int count=(limit>1 ? rates_total : 1);       // если новый бар, то копируем всю доступную историю, иначе - только один текущий
   int copied=CopyBuffer(handle_ma,0,0,count,BufferMA);
   if(copied!=count) return 0;   // Если скопировать не удалось - выходим до следующего тика

//--- Установка цвета линии
   for(int i=limit; i>=0 && !IsStopped(); i--)
     {
      // Тут всё просто: 
      // У нас задано три цвета: #property indicator_color1  clrBlue,clrRed,clrDarkGray
      // 1. если МА на текущем баре выше чем МА на прошлом, то цвет под номером 0
      // 2. если МА на текущем баре ниже чем МА на прошлом, то цвет под номером 1
      // 3. иначе - цвет под номером 2 (в блоке инициализации в строке 86 задаётся этот цвет начальным для отображения линии, что, впрочем делать там не обязательно)
      BufferColors[i]=(BufferMA[i]>BufferMA[i+1] ? 0 : BufferMA[i]<BufferMA[i+1] ? 1 : 2);
     }
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

I've emailed you a slightly awkward example (I haven't corrected the Copy-Paste errors)

 
fxsaber:

So classes within functions can have the same name but different contents. The signature f is not clear in the second variant.

Here, everything is the same... and it works

#define  CLASS \
class A { \
public: \
        void f( int i ) { Print( i ); } \
        int a; \
}
void g1() { CLASS a; a.f( 1 ); }
void g2() { CLASS a; a.f( 2 ); }
void OnStart()
{
        g1();
        g2();
}

The previous example in C++ works... so the signatures are sorted out there somehow.

 
A compilation error:
void OnStart()
{
        struct A1 { int i; }; //(1)
        struct B1 : A1 {};    //(2)
        class  A2 { int i; }; //(3)
        class  B2 : A2 {};    //(4)//Error: 'B2' - struct undefined
}

What is the fundamental difference between (1)(2) and (3)(4)?

 
There is an error in the cigar service. When you change the leverage, it shows the opposite. For example if you change it from 1:500 to 1:100 it shows that leverage was changed from 1:100 to 1:500. I have to do something about it... )
 
A100:

Here it's all the same... and it works.

So the situation here is completely different - there's no template.

The previous example works in C++... so the signatures are somehow taken care of there

What is C++ giving out here?

template<typename T>
void f( T& ) { Print(__FUNCSIG__); }
void g1() { class A { int i; } a; f( a ); }
void g2() { class A { double d; } a; f( a ); }

To make it work in MQL5, the output should contain two different strings, not the same one. But the signature generation mechanism will have to be quite different in this case. If C++ produces the same result in print, the __FUNCSIG__ value will drop dramatically.

 

What can the following behavior be related to

compile indicator works correctly, compile again indicator does not work correctly. Does it work correctly in the tester?

Reason: