Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 695

 
psyman:

For some reason I can't catch a bar in the loop, which starts at 15 o'clock.

If I write if(i<24) as a condition, the log displays the time of each bar for the day, but the required condition is not met:


And what timeframe do you run the indicator on?

 
psyman:

Sentinel in both cases.

It works:

//+------------------------------------------------------------------+
//|                                                     TestHour.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 indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property strict
//--- plot Hour
#property indicator_label1  "Hour"
#property indicator_type1   DRAW_HISTOGRAM
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  #ifdef __MQL4__ 2 #else 6 #endif 
//--- input parameters
input uchar    InpHour  =  15;   // The required hour
//--- indicator buffers
double         BufferHour[];
//--- global variables
int            hour_req;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- set global variables
   hour_req=int(InpHour>23 ? 23 : InpHour);
//--- indicator buffers mapping
   SetIndexBuffer(0,BufferHour,INDICATOR_DATA);
//--- setting indicator parameters
   IndicatorSetString(INDICATOR_SHORTNAME,"Hour("+(string)hour_req+")");
#ifdef __MQL4__
   SetIndexLabel(0,"Hour("+(string)hour_req+")");
#else 
   PlotIndexSetString(0,PLOT_LABEL,"Hour("+(string)hour_req+")");
   ArraySetAsSeries(BufferHour,true);
#endif 
   IndicatorSetInteger(INDICATOR_DIGITS,0);
//---
   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[])
  {
//--- Установка массивов буферов как таймсерий
#ifdef __MQL5__
   ArraySetAsSeries(time,true);
#endif 
//--- Проверка количества доступных баров
   if(rates_total<1) return 0;
//--- Проверка и расчёт количества просчитываемых баров
   int limit=rates_total-prev_calculated;
   if(limit>1)
     {
      limit=rates_total-1;
      ArrayInitialize(BufferHour,0);
     }
//--- Подготовка данных

//--- Расчёт индикатора
   for(int i=limit; i>=0 && !IsStopped(); i--)
     {
      int hour=GetTimeHour(time[i]);
      BufferHour[i]=(hour==hour_req ? (hour>0 ? hour : 0.1) : 0);
     }

//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| Возвращает час указанного времени                                |
//+------------------------------------------------------------------+
int GetTimeHour(const datetime time)
  {
   #ifdef __MQL4__
   return TimeHour(time);
   #endif 
   MqlDateTime tm;
   if(!TimeToStruct(time,tm)) return WRONG_VALUE;
   return tm.hour;
  }
//+------------------------------------------------------------------+
 

Thank you, but it's so complicated for someone who is not burdened with experience and knowledge, it's a mess :-)


BufferHour[i]=(hour==hour_req ? (hour>0 ? hour : 0.1) : 0);

Why make a checkhour>0 when transferring data to the buffer? And if it doesn't, why assign 0.1?



I wanted to do highlighting on main chart, but not by a line, but by ordinal day of week Mon, Wed, Wed... via SetIndexArrow(0, 140); (maybe there is a simpler way, but so far nothing else came up), but for some reason I cannot make your code work in main window in four, and in five no such property already.

 
psyman:

Thank you, but it's so complicated for someone who is not burdened with experience and knowledge, it's a mess :-)


Why make a checkhour>0when transferring data to the buffer? And if it doesn't, why assign 0.1?



I wanted to do highlighting on main chart, but not by a line, but by ordinal day of week Mon, Wed, Wed... via SetIndexArrow(0, 140); (maybe there is a simpler way, but so far nothing else came up), but for some reason I cannot make your code work in main window in four, and in five no such property.

The buffer is filled with the hour value. And if the hour is zero, the histogram will not be drawn. So, we must check whether the hour is zero (we have set it to search for zero hour in the settings), and if it is zero, we must enter 0.1 in the buffer, not the hour value (zero), to display the histogram column. This will show a value of 0 instead of 0.1 in the data window, as the indicator Digits is set to zero.

 
psyman:

Thank you, but it's so complicated for someone who is not burdened with experience and knowledge, it's a mess :-)


Why make a checkhour>0 when transferring data to the buffer? And if it doesn't, why assign 0.1?



I wanted to do highlighting on main chart, but not by a line, but by ordinal day of week Mon, Wed, Wed... via SetIndexArrow(0, 140); (maybe there is a simpler way, but so far nothing else came up), but for some reason I cannot make your code work in main window in four, and in five no such property already.

PlotIndexSetInteger(0,PLOT_ARROW,140);

But you need to create a number of buffers equal to the number of weeks. And each buffer is given an arrow code from 140 to 149 - 1,2,3,4,5,6,7,8,9,10 - ten weeks is enough for a year? That's only 70 days. Or how did you want it?

 
Good day to you all!
Please help!
This BB MACD - indicator for MetaTrader 4 was downloaded by me from herehttps://www.mql5.com/en/code/9325
This indicator is calculated in two cycles.
Using data of the previous MACD buffer Bollinger Bands are calculated.

An attempt to change the counting direction of the main cycle and calculate everything at once in one cycle and at the same time to get rid of the
At the same time to get rid of the additional cycle when calculating Bollinger Bands ended in a fiasco.
The indicator produces the same results as its untouched counterpart, but brakes the terminal wildly when calculating history.
If you leave it on a monthly timeframe you won't notice it, but if you leave it on 15 minutes

I have to restart it.

I can't be sure what to do with it.

I can ask who can suggest how to calculate the slowest locations in the programs?

Thanks in advance for the tips!


This is the original. And below is the same with my changes.

//+------------------------------------------------------------------+
//|                                               Custom BB_MACD.mq4 |
//|                                     Copyright © 2005, adoleh2000 |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

#property  copyright "Copyright © 2005, adoleh2000"
#property  link      "http://www.metaquotes.net/"
//---- indicator settings
#property  indicator_separate_window
#property  indicator_buffers 4
#property  indicator_color1  Lime    //bbMacd up
#property  indicator_color2  Magenta //bbMacd up
#property  indicator_color3  Blue    //Upperband
#property  indicator_color4  Red     //Lowerband
//---- indicator parameters
extern int FastLen = 12;
extern int SlowLen = 26;
extern int Length = 10;
extern double StDv = 2.5;
//----
int loopbegin;
int shift;
double zeroline;
//---- indicator buffers
double ExtMapBuffer1[];  // bbMacd
double ExtMapBuffer2[];  // bbMacd
double ExtMapBuffer3[];  // Upperband Line
double ExtMapBuffer4[];  // Lowerband Line
//---- buffers
double bbMacd[];
double Upperband[];
double Lowerband[];
double avg[];
double bbMacdline;
double sDev;
double mean;
double sumSqr;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- 6 additional buffers are used for counting.
   IndicatorBuffers(8);   
//---- drawing settings     
   SetIndexBuffer(0, ExtMapBuffer1); // bbMacd line
   SetIndexStyle(0, DRAW_ARROW);
   SetIndexArrow(0, 108);
   IndicatorDigits(Digits + 1);
//----
   SetIndexBuffer(1, ExtMapBuffer2); // bbMacd line
   SetIndexStyle(1, DRAW_ARROW);
   SetIndexArrow(1, 108);
   IndicatorDigits(Digits + 1);
//----   
   SetIndexBuffer(2, ExtMapBuffer3); // Upperband line
   SetIndexStyle(2, DRAW_LINE, STYLE_SOLID, 1);
   IndicatorDigits(Digits + 1);
//----   
   SetIndexBuffer(3, ExtMapBuffer4); // Lowerband line
   SetIndexStyle(3, DRAW_LINE, STYLE_SOLID, 1);
   IndicatorDigits(Digits + 1);
//----
   SetIndexBuffer(4, bbMacd);
   SetIndexBuffer(5, Upperband);        
   SetIndexBuffer(6, Lowerband);
   SetIndexBuffer(7, avg);    
//---- name for DataWindow and indicator subwindow label
   IndicatorShortName("BB MACD(" + FastLen + "," + SlowLen + "," + Length+")");
   SetIndexLabel(0, "bbMacd");
   SetIndexLabel(1, "Upperband");
   SetIndexLabel(2, "Lowerband");  
//---- initialization done
   return(0);
  }
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom BB_MACD                                                   |
//+------------------------------------------------------------------+
int start()
  {
   int limit;
   int counted_bars = IndicatorCounted();
//---- check for possible errors
   if(counted_bars < 0) 
       return(-1);
//---- last counted bar will be recounted
   if(counted_bars > 0) 
       counted_bars--;
   limit = Bars - counted_bars;
//----
   for(int i = 0; i < limit; i++)
       bbMacd[i] = iMA(NULL, 0, FastLen, 0, MODE_EMA, PRICE_CLOSE, i) - 
                   iMA(NULL, 0, SlowLen, 0, MODE_EMA, PRICE_CLOSE, i);
//----
   for(i = 0; i < limit; i++)
     {
       avg[i] = iMAOnArray(bbMacd, 0, Length, 0, MODE_EMA, i);
       sDev = iStdDevOnArray(bbMacd, 0, Length, MODE_EMA, 0, i);  
       Upperband[i] = avg[i] + (StDv * sDev);
       Lowerband[i] = avg[i] - (StDv * sDev);
       ExtMapBuffer1[i]=bbMacd[i];     // Uptrend bbMacd
       ExtMapBuffer2[i]=bbMacd[i];     // downtrend bbMacd
       ExtMapBuffer3[i]=Upperband[i];  // Upperband
       ExtMapBuffer4[i]=Lowerband[i];  // Lowerband
       //----
       if(bbMacd[i] > bbMacd[i+1])
           ExtMapBuffer2[i] = EMPTY_VALUE;
       //----
       if(bbMacd[i] < bbMacd[i+1])
           ExtMapBuffer1[i] = EMPTY_VALUE;
     }
//---- done
   return(0);
  }
//+------------------------------------------------------------------+


//================


//+------------------------------------------------------------------+
//|                                               Custom BB_MACD.mq4 |
//|                                     Copyright © 2005, adoleh2000 |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

/*
Осторожно!!!
В том коде мной изменено направление расчёта главного цикла. Осторожно!!! Этот индикатор очень медленно выполняется!!! Его можно бросить только на недельный или месячный таймфрейм где в истории мало баров, если ниже 4х часов то терминал вешается!!! */
#property  copyright "Copyright © 2005, adoleh2000" #property  link      "http://www.metaquotes.net/" //---- indicator settings #property  indicator_separate_window #property  indicator_buffers 4 #property  indicator_color1  Lime    //bbMacd up #property  indicator_color2  Magenta //bbMacd up #property  indicator_color3  Blue    //Upperband #property  indicator_color4  Red     //Lowerband //---- indicator parameters extern int FastLen = 12; extern int SlowLen = 26; extern int Length = 10; extern double StDv = 2.5; //---- int loopbegin; int shift; double zeroline; //---- indicator buffers double ExtMapBuffer1[];  // bbMacd double ExtMapBuffer2[];  // bbMacd double ExtMapBuffer3[];  // Upperband Line double ExtMapBuffer4[];  // Lowerband Line //---- buffers double bbMacd[]; double Upperband[]; double Lowerband[]; double avg[]; double bbMacdline; double sDev; double mean; double sumSqr; //+------------------------------------------------------------------+ //| Custom indicator initialization function                         | //+------------------------------------------------------------------+ int init()   { //---- 6 additional buffers are used for counting.    IndicatorBuffers(8);   //---- drawing settings        SetIndexBuffer(0, ExtMapBuffer1); // bbMacd line    SetIndexStyle(0, DRAW_ARROW);    SetIndexArrow(0, 108);    IndicatorDigits(Digits + 1); //----    SetIndexBuffer(1, ExtMapBuffer2); // bbMacd line    SetIndexStyle(1, DRAW_ARROW);    SetIndexArrow(1, 108);    IndicatorDigits(Digits + 1); //----      SetIndexBuffer(2, ExtMapBuffer3); // Upperband line    SetIndexStyle(2, DRAW_LINE, STYLE_SOLID, 1);    IndicatorDigits(Digits + 1); //----      SetIndexBuffer(3, ExtMapBuffer4); // Lowerband line    SetIndexStyle(3, DRAW_LINE, STYLE_SOLID, 1);    IndicatorDigits(Digits + 1); //----    SetIndexBuffer(4, bbMacd);    SetIndexBuffer(5, Upperband);            SetIndexBuffer(6, Lowerband);    SetIndexBuffer(7, avg);     //---- name for DataWindow and indicator subwindow label    IndicatorShortName("BB MACD-2(" + FastLen + "," + SlowLen + "," + Length+")");    SetIndexLabel(0, "bbMacd");    SetIndexLabel(1, "Upperband");    SetIndexLabel(2, "Lowerband");            //---- initialization done    return(0);   } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function                       | //+------------------------------------------------------------------+ int deinit()   { //----    return(0);   } //+------------------------------------------------------------------+ //| Custom BB_MACD                                                   | //+------------------------------------------------------------------+ int start()   {    int limit, i,MaxPeriod;    int counted_bars = IndicatorCounted(); //---- check for possible errors    if(counted_bars < 0)        return(-1); //---- last counted bar will be recounted    if(counted_bars > 0)        counted_bars--;    limit = Bars - counted_bars;             if(counted_bars==0){              for(i=Bars-1; i>=1; i--) bbMacd[i]=0.0;//обнулим первый рассчитываемый массив              MaxPeriod= MathMax(MathMax(FastLen,SlowLen), Length);//это самые старые бары в истории которые не будем рассчитывать       limit=limit-MaxPeriod;    }    //      //---- основной цикл   for(i=limit; i>=1; i--){//ЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦ //В этом месте изменено направление пересчёта в основном цикле. //И все расчёты зависимых друг от друга буферов производятся последовательно  в одном цикле. //Дополнительный цикл расчета удалён.        bbMacd[i] = iMA(NULL, 0, FastLen, 0, MODE_EMA, PRICE_CLOSE, i) -                    iMA(NULL, 0, SlowLen, 0, MODE_EMA, PRICE_CLOSE, i);                           avg[i] = iMAOnArray(bbMacd, 0, Length, 0, MODE_EMA, i);        sDev = iStdDevOnArray(bbMacd, 0, Length, MODE_EMA, 0, i);          Upperband[i] = avg[i] + (StDv * sDev);        Lowerband[i] = avg[i] - (StDv * sDev);        ExtMapBuffer1[i]=bbMacd[i];     // Uptrend bbMacd        ExtMapBuffer2[i]=bbMacd[i];     // downtrend bbMacd        ExtMapBuffer3[i]=Upperband[i];  // Upperband        ExtMapBuffer4[i]=Lowerband[i];  // Lowerband        //----        if(bbMacd[i] > bbMacd[i+1])            ExtMapBuffer2[i] = EMPTY_VALUE;        //----        if(bbMacd[i] < bbMacd[i+1])            ExtMapBuffer1[i] = EMPTY_VALUE;      }//ЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦЦ //---- done    return(0);   } //+------------------------------------------------------------------+
BB MACD
BB MACD
  • www.mql5.com
BB_MACD Indicator.
 
Northwest:
Good day to you all!
Please help!
This BB MACD - indicator for MetaTrader 4 was downloaded by me from herehttps://www.mql5.com/en/code/9325
This indicator is calculated in two cycles.
Using data of the previous MACD buffer Bollinger Bands are calculated.

An attempt to change the counting direction of the main cycle and calculate everything at once in one cycle and at the same time to get rid of
At the same time to get rid of the additional cycle when calculating Bollinger Bands ended in a fiasco.
The indicator produces the same results as its untouched counterpart, but brakes the terminal wildly when calculating history.
If you leave it on a monthly timeframe you won't notice it, but if you leave it on 15 minutes

I have to restart it.

I can't be sure what to do with it.

I can ask who can suggest how to calculate the slowest locations in the programs?

Thanks in advance for the tips!


This is the original. And below is the same with my changes.


//================


Give it all back, don't torture the computer

iBandsOnArray, iStdDevOnArray calculated for data stored in an array

The array, on the other hand, is filled in 1 loop

 
Alekseu Fedotov:

Put everything back, don't torture the computer

iBandsOnArray, iStdDevOnArray calculated for data stored in an array

An array, on the other hand, is filled in 1 cycle

1. Put everything back, do not torture your computer .

Sorry, but you won't get it back. You have to make the indicator count from left to right.

I'm not bothering him, I'm using him for his intended purpose.

2.iBandsOnArray, iStdDevOnArray calculated using data stored in the array

Yes, they are calculated using data from bbMacd[] array, so what next?

3.The array is filled in one loop.

In one or in the first one?

Are you saying that in order to fill one array, you need a personal loop, in which this array is filled

array is filled and no other operations may be performed?


It is important for me to find out why the indicator slows down and how to calculate those places where it happens.

I have more questions but no answers.

Unfortunately, you haven't offered any clues.

 

How do I disable re-initialisation when EA timeframe changes?


There is some information here:

EARunning OnDeinit and OnInit, global class object does not change.

https://www.mql5.com/ru/forum/170952/page61#comment_6132824


Is it also correct for mql4?

Reason: