Array out of range in Need of help - page 10

 
Aleksei Stepanenko:

I don't understand what's wrong. It's a line of minima.

Just in case, copy the code again, I've changed it periodically there, maybe you have an old version

Yes yes, I have to change the version when editing the code.

AUDUSD seems to be OK.

I will go over EURUSD for the solder years. It will be long.

I would like to add week and month at once, if that's not too much trouble ? And shift the labels like on the example.

So as not to look at the graph ten times. (already know the story by heart).

I think I can manage 8 pairs in a month.

I won't get into your code myself ( I will study the process quietly with classes and so on using your example).

Almost forgot (to make an alert like warning if there is no history or the line has not changed its values)

 

New version. Here it draws three periods: day, week and month. There is a but, I will write below.

#property version   "2.00"
#property strict

//символ и таймфрейм текущего графика
string symbol;
ENUM_TIMEFRAMES frame;
datetime time=0, current;
int digits;

long ChartId;
int Window;
string Name="MiniMax";
MqlDateTime date; 

struct BarData
   {
   struct Elem
      {
      int      number;     //порядковый номер периода (дня, месяца или года)
      double   high;       //максимум периода
      double   low;        //минимум периода
      datetime time_high;  //время максимума
      datetime time_low;   //время минимума
      } Arr[];             //массив периода
   int index;              //текущий индекс массива
   double   max;           //последнее максимальное значение периода
   double   min;           //последнее минимальное значение периода
   datetime time_max;      //время максимума
   datetime time_min;      //время минимума

   //при создании структуры указываем, что массив пустой
   BarData(){index=-1;}    
   
   //функция записывает текущие экстремумы
   void WriteBar(int eNumber, string eSymbol, ENUM_TIMEFRAMES eFrame, datetime eTime)
      {
      if(eTime==0) return;
      int eShift=iBarShift(eSymbol,eFrame,eTime);
      double eHigh=iHigh(eSymbol,eFrame,eShift);
      double eLow=iLow(eSymbol,eFrame,eShift);
      bool eIsNew=false;
      //если элементов ещё нет или период сменился
      if(index<0 || eNumber!=Arr[index].number)
         {         
         ArrayResize(Arr,++index+1);
         Arr[index].number=eNumber;
         Arr[index].high=eHigh;
         Arr[index].low=eLow;
         Arr[index].time_high=eTime;
         Arr[index].time_low=eTime;
         if(index==0)
            {
            max=eHigh;
            time_max=eTime;
            min=eLow;
            time_min=eTime;
            }
         else
            {
            eIsNew=true;
            }
         }
      //если произошло обновление текущего максимума
      if(eHigh-Arr[index].high>0)
         {
         Arr[index].high=eHigh;
         Arr[index].time_high=eTime;
         }
      //если произошло обновление текущего минимума
      if(Arr[index].low-eLow>0)
         {
         Arr[index].low=eLow;
         Arr[index].time_low=eTime;
         }
      //если произошло обновление предыдущего максимума
      if(eIsNew)
         {
         max=Arr[index-1].high;
         time_max=Arr[index-1].time_high;
         for(int i=index-2; i>=0; i--)
            {
            if(Arr[i].high-Arr[index-1].high>0)
               {
               max=Arr[i].high;
               time_max=Arr[i].time_high;
               break;
               }
            }
         }
      //если произошло обновление предыдущего минимума
      if(eIsNew)
         {
         min=Arr[index-1].low;
         time_min=Arr[index-1].time_low;
         for(int i=index-2; i>=0; i--)
            {
            if(Arr[index-1].low-Arr[i].low>0)
               {
               min=Arr[i].low;
               time_min=Arr[i].time_low;
               break;
               }
            }
         }
      }
      
   double GetHigh() {return(index>0?Arr[index-1].high:Arr[index].high);}
   double GetLow() {return(index>0?Arr[index-1].low:Arr[index].low);}
   } day, week, month;

int OnInit()
   {
   symbol=Symbol();
   frame=(ENUM_TIMEFRAMES)Period();
   digits=(int)SymbolInfoInteger(symbol,SYMBOL_DIGITS);
   //идентификатор графика и номер окна индикатора
   ChartId=ChartID();
   Window=0;
   return(INIT_SUCCEEDED);
   }

void OnTick()
   {
   //текущее время закрытого бара
   current=iTime(symbol,frame,1);
   do
      {    
      TimeToStruct(time,date);
      //делаем записи каждого периода
      day.WriteBar(date.day,symbol,frame,time);
      week.WriteBar(GetWeekNumber(time),symbol,frame,time);
      month.WriteBar(date.mon,symbol,frame,time);
      
      if(time<current) {time=iTime(symbol,frame,(iBarShift(symbol,frame,time)-1));} else break;
      }
   while(time<=current);
   
   //рисуем дневные линии
   RedrawHLine(ChartId,Window,Name+"_Day_1_High",day.GetHigh(),clrBlue,1,DoubleToString(day.GetHigh(),digits),digits);
   RedrawHLine(ChartId,Window,Name+"_Day_1_Low",day.GetLow(),clrBlue,1,DoubleToString(day.GetLow(),digits),digits);
   RedrawText(ChartId,Window,Name+"_Day_1_High_Text",iTime(symbol,frame,20),day.GetHigh(),"Day 1:  "+DoubleToString(day.GetHigh(),digits),ANCHOR_RIGHT_LOWER,"Arial",8,clrBlue,"",digits);
   RedrawText(ChartId,Window,Name+"_Day_1_Low_Text",iTime(symbol,frame,20),day.GetLow(),"Day 1:  "+DoubleToString(day.GetLow(),digits),ANCHOR_RIGHT_UPPER,"Arial",8,clrBlue,"",digits);

   RedrawHLine(ChartId,Window,Name+"_Day_Max_High",day.max,clrRed,1,DoubleToString(day.max,digits),digits);
   RedrawHLine(ChartId,Window,Name+"_Day_Min_Low",day.min,clrRed,1,DoubleToString(day.min,digits),digits);
   RedrawText(ChartId,Window,Name+"_Day_Max_Text",iTime(symbol,frame,70),day.max,"Day Max:  "+DoubleToString(day.max,digits),ANCHOR_RIGHT_LOWER,"Arial",8,clrRed,"",digits);
   RedrawText(ChartId,Window,Name+"_Day_Min_Text",iTime(symbol,frame,70),day.min,"Day Min:  "+DoubleToString(day.min,digits),ANCHOR_RIGHT_UPPER,"Arial",8,clrRed,"",digits);
   
   //рисуем недельные линии
   RedrawHLine(ChartId,Window,Name+"_Week_1_High",week.GetHigh(),clrBlue,1,DoubleToString(week.GetHigh(),digits),digits);
   RedrawHLine(ChartId,Window,Name+"_Week_1_Low",week.GetLow(),clrBlue,1,DoubleToString(week.GetLow(),digits),digits);
   RedrawText(ChartId,Window,Name+"_Week_1_High_Text",iTime(symbol,frame,120),week.GetHigh(),"Week 1:  "+DoubleToString(week.GetHigh(),digits),ANCHOR_RIGHT_LOWER,"Arial",8,clrBlue,"",digits);
   RedrawText(ChartId,Window,Name+"_Week_1_Low_Text",iTime(symbol,frame,120),week.GetLow(),"Week 1:  "+DoubleToString(week.GetLow(),digits),ANCHOR_RIGHT_UPPER,"Arial",8,clrBlue,"",digits);

   RedrawHLine(ChartId,Window,Name+"_Week_Max_High",week.max,clrRed,1,DoubleToString(week.max,digits),digits);
   RedrawHLine(ChartId,Window,Name+"_Week_Min_Low",week.min,clrRed,1,DoubleToString(week.min,digits),digits);
   RedrawText(ChartId,Window,Name+"_Week_Max_Text",iTime(symbol,frame,170),week.max,"Week Max:  "+DoubleToString(week.max,digits),ANCHOR_RIGHT_LOWER,"Arial",8,clrRed,"",digits);
   RedrawText(ChartId,Window,Name+"_Week_Min_Text",iTime(symbol,frame,170),week.min,"Week Min:  "+DoubleToString(week.min,digits),ANCHOR_RIGHT_UPPER,"Arial",8,clrRed,"",digits);
   
   //рисуем месячные линии
   RedrawHLine(ChartId,Window,Name+"_Month_1_High",month.GetHigh(),clrBlue,1,DoubleToString(month.GetHigh(),digits),digits);
   RedrawHLine(ChartId,Window,Name+"_Month_1_Low",month.GetLow(),clrBlue,1,DoubleToString(month.GetLow(),digits),digits);
   RedrawText(ChartId,Window,Name+"_Month_1_High_Text",iTime(symbol,frame,220),month.GetHigh(),"Month 1:  "+DoubleToString(month.GetHigh(),digits),ANCHOR_RIGHT_LOWER,"Arial",8,clrBlue,"",digits);
   RedrawText(ChartId,Window,Name+"_Month_1_Low_Text",iTime(symbol,frame,220),month.GetLow(),"Month 1:  "+DoubleToString(month.GetLow(),digits),ANCHOR_RIGHT_UPPER,"Arial",8,clrBlue,"",digits);

   RedrawHLine(ChartId,Window,Name+"_Month_Max_High",month.max,clrRed,1,DoubleToString(month.max,digits),digits);
   RedrawHLine(ChartId,Window,Name+"_Month_Min_Low",month.min,clrRed,1,DoubleToString(month.min,digits),digits);
   RedrawText(ChartId,Window,Name+"_Month_Max_Text",iTime(symbol,frame,270),month.max,"Month Max:  "+DoubleToString(month.max,digits),ANCHOR_RIGHT_LOWER,"Arial",8,clrRed,"",digits);
   RedrawText(ChartId,Window,Name+"_Month_Min_Text",iTime(symbol,frame,270),month.min,"Month Min:  "+DoubleToString(month.min,digits),ANCHOR_RIGHT_UPPER,"Arial",8,clrRed,"",digits);
   }

//получаем номер недели в году
int GetWeekNumber(datetime eTime)
   {
   MqlDateTime eDate;
   //получаем дату начала года
   TimeToStruct(eTime,eDate);
   eDate.mon=1;
   eDate.day=1;
   eDate.hour=0;
   eDate.min=0;
   eDate.sec=0;
   datetime StartTime=StructToTime(eDate);
   //возвращаем дату назад в структуру, чтобы определить день недели начала года
   TimeToStruct(StartTime,eDate);
   return(int((eTime-StartTime+86400*eDate.day_of_week)/604800));
   }

//перерисовывает линию по новым координатам, если её нет, то создаёт
void RedrawHLine(long eChartId, int eWindow, string eName, double ePrice, color eColor, int eWidth, string eTooltip, int eDigits)
   {
   if(ObjectFind(eChartId,eName)==-1)
      {
      if(!ObjectCreate(eChartId,eName,OBJ_HLINE,eWindow,0,0)) return;
      ObjectSetInteger(eChartId,eName,OBJPROP_STYLE,STYLE_SOLID);
      ObjectSetInteger(eChartId,eName,OBJPROP_WIDTH,eWidth);
      ObjectSetInteger(eChartId,eName,OBJPROP_BACK,true);
      ObjectSetInteger(eChartId,eName,OBJPROP_SELECTABLE,false);
      ObjectSetInteger(eChartId,eName,OBJPROP_SELECTED,false);
      ObjectSetInteger(eChartId,eName,OBJPROP_HIDDEN,true);
      }
   if(ObjectFind(eChartId,eName)==-1) return;   
   if(NormalizeDouble(ObjectGetDouble(eChartId,eName,OBJPROP_PRICE)-ePrice,eDigits)!=0) ObjectSetDouble(eChartId,eName,OBJPROP_PRICE,ePrice);
   if(ObjectGetInteger(eChartId,eName,OBJPROP_COLOR)!=eColor) ObjectSetInteger(eChartId,eName,OBJPROP_COLOR,eColor);
   if(ObjectGetString(eChartId,eName,OBJPROP_TOOLTIP)!=eTooltip) ObjectSetString(eChartId,eName,OBJPROP_TOOLTIP,eTooltip);
   }

//перерисовываем текст по новым координатам, если его нет, то создаём
void RedrawText(long eChartId, int eWindow, string eName, datetime eTime, double ePrice, string eText, ENUM_ANCHOR_POINT eAnchor, string eFont, int eSize, color eColor, string eTooltip, int eDigits)
   {
   if(ObjectFind(eChartId,eName)==-1)
      {
      if(!ObjectCreate(eChartId,eName,OBJ_TEXT,eWindow,0,0)) return;
      ObjectSetString(eChartId,eName,OBJPROP_FONT,eFont);
      ObjectSetInteger(eChartId,eName,OBJPROP_FONTSIZE,eSize);
      ObjectSetDouble(eChartId,eName,OBJPROP_ANGLE,0.0);
      ObjectSetInteger(eChartId,eName,OBJPROP_ANCHOR,eAnchor);
      //на переднем  плане
      ObjectSetInteger(eChartId,eName,OBJPROP_BACK,false);
      ObjectSetInteger(eChartId,eName,OBJPROP_SELECTABLE,false);
      ObjectSetInteger(eChartId,eName,OBJPROP_SELECTED,false);
      ObjectSetInteger(eChartId,eName,OBJPROP_HIDDEN,true);
      ObjectSetString(eChartId,eName,OBJPROP_TOOLTIP,eTooltip);
      }
   if(ObjectFind(eChartId,eName)==-1) return;
   //координаты метки
   if(ObjectGetInteger(eChartId,eName,OBJPROP_TIME)!=eTime) ObjectSetInteger(eChartId,eName,OBJPROP_TIME,eTime);
   if(NormalizeDouble(ObjectGetDouble(eChartId,eName,OBJPROP_PRICE)-ePrice,eDigits)!=0) ObjectSetDouble(eChartId,eName,OBJPROP_PRICE,ePrice);
   if(ObjectGetInteger(eChartId,eName,OBJPROP_COLOR)!=eColor) ObjectSetInteger(eChartId,eName,OBJPROP_COLOR,eColor);
   if(ObjectGetString(eChartId,eName,OBJPROP_TEXT)!=eText) ObjectSetString(eChartId,eName,OBJPROP_TEXT,eText);
   }
 

The nuance is that in one case we are comparing the previous day to the history and in the other we are comparing the previous week. It turns out that yesterday may belong to the current week, but its maximum may be higher than the maximum of the previous week.

And because we are comparing days to days and weeks to weeks, it may turn out that the lines of the day highs are higher than the week highs. Like here:

But that's your logic, think whether you need it or not.

//--- Max_W_Level
 for(int i = 1; i<ArrayRange(Bar_data_D1,0) ;i++)
    {
     //Print(" i = ",i);
     if(Bar_data_D1 [i][3]>=0)
       {
        if(Bar_data_W1 [i][3] > High_W1_Level)    
          {
           Max_W_Level = Bar_data_W1 [i][3];break;
          }
       }  
    } 
 

By the way, there is an out-of-array error as well:

//--- Max_W_Level
 for(int i = 1; i<ArrayRange(Bar_data_D1,0) ;i++)
    {
     if(Bar_data_D1 [i][3]>=0)
       {
        if(Bar_data_W1 [i][3] > High_W1_Level)    
          {
           Max_W_Level = Bar_data_W1 [i][3];break;
          }
       }  
    } 

The loop goes through the array of daily bars, and we select elements from the array of weekly bars.

 

Thanks to Dmitry Fedoseev for the idea of getting the number of the week of the year.

I found it in this article:https://www.mql5.com/ru/articles/599

Well done, Dima!
Dmitry Fedoseev
Dmitry Fedoseev
  • www.mql5.com
Добавил тему А как часто это бывает у вас? Согласен с модераторами, вопрос совершенно не по теме форума. Так что если удалите не обижусь. Надеюсь на забаните. Собственно вопрос всем - как часто ваш мобильный оператор подписывает вас на какую-нибудь фигню? И естественно потом доказывает, что Добавил опрос Как у вас с электропитанием? Добавил...
 
Aleksei Stepanenko:

By the way, there is an out-of-array error as well:

The loop goes through the array of daily bars, while we select elements from the array of weekly bars.


There is an obvious error here, this line was added in the process of discussion and copy-paste played its role.

It was so from the beginning and going outside the array is still relevant.

We may seem to forget about the error array out of range in, because you did not feel lazy and provided much more advanced code (many thanks to you for that).

But I still want to understand what the problem is (since this array is accessed from other places in the EA, and what's going on there remains a mystery)

I have noticed ( Where is the returned value of the int type saved? You passed all data into the function, but didn't get anything from it) I added .

It was like this:

ArrayCopyRates(Bar_data_D1,_Symbol,PERIOD_D1); // Copies bar data of the specified chart into an array and returns the number of copied bars

ArrayCopyRates(Bar_data_W1,_Symbol,PERIOD_W1); // Copies data of bars for a specified chart into an array and returns number of copied bars

ArrayCopyRates(Bar_data_MN1,_Symbol,PERIOD_MN1); // Copies data of bars of a specified chart into an array and returns number of copied bars

Now it looks like this:

ACR_D1 = ArrayCopyRates(Bar_data_D1,_Symbol,PERIOD_D1); // Copies bar data of the specified chart into an array and returns the number of copied bars

ACR_W1 = ArrayCopyRates(Bar_data_W1,_Symbol,PERIOD_W1); // Copies data of bars for a specified chart into an array and returns number of copied bars

ACR_MN1 = ArrayCopyRates(Bar_data_MN1,_Symbol,PERIOD_MN1); // Copies data of bars in a specified chart into an array and returns the number of copied bars

Output the value in the som



2020.12.12 16:51:31.536 2020.02.10 00:05:00 _Test AUDUSD,H1: i = 1001 Bar_data_D1 [i][2] = 0.7633799999999999

2020.12.12 16:51:31.536 2020.02.10 00:05:00 _Test AUDUSD,H1: i = 1002 Bar_data_D1 [i][2] = 0.76147

2020.12.12 16:51:31.536 2020.02.10 00:05:00 _Test AUDUSD,H1: i = 1003 Bar_data_D1 [i][2] = 0.75097

2020.12.12 16:51:31.536 2020.02.10 00:05:00 _Test AUDUSD,H1: array out of range in '_Test.mq4' (150,59)

2020.12.12 16:51:31.537 2020.02.10 00:05:00 Testing pass stopped due to a critical error in the EA

2020.12.12 16:51:31.537 AUDUSD,H1: 65147 tick events (73 bars, 9291875 bar states) processed in 0:00:02.407 (total time 0:00:05.672)

#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.4"
#property strict

#include <stderror.mqh>
#include <stdlib.mqh>
//------------------------------------------------------------------+
int Order_MagicNumber; // для авто торговли 
int Magic = 0;         //для ручная торговля
//------------------------------------------------------------------+
extern color  Color               = clrBlue;  // Color линия Bid

//+------------------------------------------------------------------+
//|                  переменные Функция Level 
//+------------------------------------------------------------------+
double   Bar_data_D1  [][6]; // Копирует в массив данные баров указанного графика и возвращает количество скопированных баров D1
int      ACR_D1;             // Возвращает количество скопированных баров D1
double   Bar_data_W1  [][6]; // Копирует в массив данные баров указанного графика и возвращает количество скопированных баров W1
int      ACR_W1;             // Возвращает количество скопированных баров W1
double   Bar_data_MN1 [][6]; // Копирует в массив данные баров указанного графика и возвращает количество скопированных баров MN1
int      ACR_MN1;            // Возвращает количество скопированных баров MN1
double   High_D1_Level;      // Возвращает значение максимальной цены бара D1
double   Low_D1_Level;       // Возвращает значение минимальной цены бара  D1
double   High_W1_Level;      // Возвращает значение максимальной цены бара W1
double   Low_W1_Level ;      // Возвращает значение минимальной цены бара  W1
double   High_MN1_Level;     // Возвращает значение максимальной цены бара MN1
double   Low_MN1_Level;      // Возвращает значение минимальной цены бара  MN1
double   Max_D_Level;        // ближайшей максимальный D уровень
double   Min_D_Level ;       // ближайшей минимальный  D уровень
double   Max_W_Level ;       // ближайшей максимальный W уровень
double   Min_W_Level ;       // ближайшей минимальный  W уровень
double   Max_MN_Level ;      // ближайшей максимальный MN уровень
double   Min_MN_Level ;      // ближайшей минимальный  MN уровень

//-------------------------------------------------------------------+
int       Time_Seconds;        // сохроняем секунду 
int       Time_Minute;         // сохроняем минуту 
int       Time_Hour;           // сохроняем час
datetime  Time_Day;            // сохроняем день

//-------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
 Level();
 return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
 DestroyObject();
}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
 On_Timer();             // функция Timer
 Comment( "\n",
          "\n",
          "\n"," Возвращает количество скопированных баров D1  = ",ACR_D1,
          "\n"," Возвращает количество скопированных баров W1  = ",ACR_W1,
          "\n"," Возвращает количество скопированных баров MN1 = ",ACR_MN1,
          "\n",
          "\n");    
}    
//+------------------------------------------------------------------+
//|                        Функция Level 
//+------------------------------------------------------------------+
void Level()
{
 ACR_D1  = ArrayCopyRates(Bar_data_D1,_Symbol,PERIOD_D1); // Копирует в массив данные баров указанного графика и возвращает количество скопированных баров
 ACR_W1  = ArrayCopyRates(Bar_data_W1,_Symbol,PERIOD_W1); // Копирует в массив данные баров указанного графика и возвращает количество скопированных баров
 ACR_MN1 = ArrayCopyRates(Bar_data_MN1,_Symbol,PERIOD_MN1); // Копирует в массив данные баров указанного графика и возвращает количество скопированных баров
 
 High_D1_Level  = iHigh(_Symbol,PERIOD_D1,1);   // Возвращает значение максимальной цены бара D1
 Low_D1_Level   = iLow (_Symbol,PERIOD_D1,1);   // Возвращает значение минимальной цены бара  D1
 
//--- Max_D_Level
 //for(int i = 1; i<ArrayRange(Bar_data_D1,0) ;i++) // (если с этим то пролетаем со свистом (просто не перерисовываем линию этим днём)
  for(int i = 1;  ;i++)                             // (так выход за массив)
    {
     Print("i = ",i," Bar_data_D1 [i][3] = ",Bar_data_D1 [i][3]);
     if(Bar_data_D1 [i][3] > High_D1_Level)  
       {
        Max_D_Level = Bar_data_D1 [i][3];break;
       }
    } 
    
//--- Min_D_Leve  
 // for(int i = 1; i<ArrayRange(Bar_data_D1,0) ;i++)
  for(int i = 1; ;i++)
     {
      Print("i = ",i," Bar_data_D1 [i][2] = ",Bar_data_D1 [i][2]);
      if( Bar_data_D1 [i][2] < Low_D1_Level)
        {
         Min_D_Level = Bar_data_D1 [i][2];break;
        }
     }      
    
 //+-----------------------High_D1_Level-----------------------------+  
 if(ObjectFind("High_D1")!=High_D1_Level) 
   {
    ObjectDelete("High_D1");
    if(ObjectFind("High_D1")!=0)
      {
       ObjectCreate("High_D1",OBJ_HLINE, 0, Time[0],High_D1_Level);
       ObjectSet("High_D1", OBJPROP_COLOR, clrMaroon);
       ObjectSet("High_D1", OBJPROP_WIDTH, 1);
      }
   } 
 if(ObjectFind("High_D1_label")!=High_D1_Level)
   {
    ObjectDelete("High_D1_label"); 
    if(ObjectFind("High_D1_label") != 0)
      {
       ObjectCreate("High_D1_label", OBJ_TEXT, 0, Time[13], High_D1_Level);
       ObjectSetText("High_D1_label", "High_D1: " + DoubleToStr(High_D1_Level,_Digits), 8,"Verdana", Brown);
      }
   } 
 //+-------------------------Low_D1_Level----------------------------+ 
 if(ObjectFind("Low_D1")!=Low_D1_Level) 
   {
    ObjectDelete("Low_D1");
    if(ObjectFind("Low_D1")!=0)
      {
       ObjectCreate("Low_D1",OBJ_HLINE, 0, Time[0],Low_D1_Level);
       ObjectSet("Low_D1", OBJPROP_COLOR, clrMaroon);
       ObjectSet("Low_D1", OBJPROP_WIDTH, 1);
      }
   } 
   
 if(ObjectFind("Low_D1_label")!=Low_D1_Level)
   {
    ObjectDelete("Low_D1_label"); 
    if(ObjectFind("Low_D1_label") != 0)
      {
       ObjectCreate("Low_D1_label", OBJ_TEXT, 0, Time[13], Low_D1_Level);
       ObjectSetText("Low_D1_label", "Low_D1: " + DoubleToStr(Low_D1_Level,_Digits), 8,"Verdana", Brown);
      }
   } 
   
     //+-----------------------Max_D_Level-----------------------------+  
 if(ObjectFind("Max_D")!=Max_D_Level) 
   {
    ObjectDelete("Max_D");
    if(ObjectFind("Max_D")!=0)
      {
       ObjectCreate("Max_D",OBJ_HLINE, 0, Time[0],Max_D_Level);
       ObjectSet("Max_D", OBJPROP_COLOR, clrMaroon);
       ObjectSet("Max_D", OBJPROP_WIDTH, 1);
      }
   } 
 if(ObjectFind("Max_D_label")!=Max_D_Level)
   {
    ObjectDelete("Max_D_label"); 
    if(ObjectFind("Max_D_label") != 0)
      {
       ObjectCreate("Max_D_label", OBJ_TEXT, 0, Time[30], Max_D_Level);
       ObjectSetText("Max_D_label", "Max_D: " + DoubleToStr(Max_D_Level,_Digits), 8,"Verdana", Brown);
      }
   } 
 //+-------------------------Min_D_Level----------------------------+ 
 if(ObjectFind("Min_D")!= Min_D_Level) 
   {
    ObjectDelete("Min_D");
    if(ObjectFind("Min_D")!=0)
      {
       ObjectCreate("Min_D",OBJ_HLINE, 0, Time[0],Min_D_Level);
       ObjectSet("Min_D", OBJPROP_COLOR, clrMaroon);
       ObjectSet("Min_D", OBJPROP_WIDTH, 1);
      }
   } 
   
 if(ObjectFind("Min_D_label")!=Min_D_Level)
   {
    ObjectDelete("Min_D_label"); 
    if(ObjectFind("Min_D_label") != 0)
      {
       ObjectCreate("Min_D_label", OBJ_TEXT, 0, Time[30], Min_D_Level);
       ObjectSetText("Min_D_label", "Min_D: " + DoubleToStr(Min_D_Level,_Digits), 8,"Verdana", Brown);
      }
   }       
}
//+------------------------------------------------------------------+
//|        функция удаление всех объектов созданных советником
//+------------------------------------------------------------------+
void DestroyObject()
{
 int tot=ObjectsTotal();
 for( int i=tot; i>=0; i--)
    {
    
     if(ObjectName(i)=="High_D1"){ObjectDelete(0,"High_D1");Print("<< Объект High_D1 удалён >>");}
     if(ObjectName(i)=="High_D1_label"){ObjectDelete(0,"High_D1_label");Print("<< Объект High_D1_label удалён >>");}
     
     if(ObjectName(i)=="Low_D1"){ObjectDelete(0,"Low_D1");Print("<< Объект Low_D1 удалён >>");}
     if(ObjectName(i)=="Low_D1_label"){ObjectDelete(0,"Low_D1_label");Print("<< Объект Low_D1_label удалён >>");}
     
   }
}
//+-------------------------------------------------------------------------+   
//                         функция Timer                    
//+-------------------------------------------------------------------------+
void On_Timer()
{
 if(Seconds() != Time_Seconds)
   {
    Time_Seconds = Seconds();
   }
     
 if(Minute() != Time_Minute)
   {   
    Time_Minute = Minute();
   }
     
 if(Hour() != Time_Hour)
   {
    
    Time_Hour = Hour();
   }
     
 if(Day()!= Time_Day)
   {
    Level();
    Time_Day = Day();
   }
}
 

Why is so little history copied into the array?

And where and how do these values come from in the first place?

 
Aleksei Stepanenko:

By the way, there is an out-of-array error as well:

The loop goes through the array of daily bars, and we select elements from the array of weekly bars.

We should immediately understand the size of the array of the daily TF and time it and not go beyond the time.

I would probably solve the weekly bars differently. I would get the price levels with dates, if they are needed, and fill them into a separate array and compare with this array. Or rather, that is how I do it. For each TF my own array of extrema.

I am not making comparisons, I am speaking about arrays

Индикатор экстремумов по Вильямсу
Индикатор экстремумов по Вильямсу
  • www.mql5.com
Экстремумы первого порядка ищутся скользящим окном средний бара между соседними и разделяются на максимумы и минимумы первого порядка. Условие средний бар больше или меньше соседних. Максимумы и минимумы второго и третьего порядка ищутся раздельно среди максимумов и минимумов меньшего порядка. Максимумы второго ищутся между максимумами первого...
 
Valeriy Yastremskiy:

And immediately understand the size of the daily TF array and time it and stay on time.

I would probably solve the weekly ones differently. I would get price levels with dates at weekly ones, if they are needed, and fill them into a separate array and compare with this array. Or rather, that is how I do it. For each TF I have my own array of extrema.

I'm not making comparisons, I'm talking about arrays.

(I would get price levels with dates, if they are needed, and fill them into a separate array and compare them with that array)

We don't know which ones we need and which ones we don't, we need all possible history of all bars.

ArrayCopyRates

Copies data of the specified chart bars into an array and returns the number of copied bars.

intArrayCopyRates(
MqlRates&rates_array[],// array MqlRates passed by the reference
stringsymbol=NULL,// the tool
inttimeframe=0// timeframe
);


where is it not clear ?

I can't figure out the connection

It sees 323 months which is somewhere close to 27 years, 1403 weeks, 7015 days

AUDUSD history since 1993, 2020-1993= 27


 Comment( "\n",
          "\n",
          "\n"," Возвращает количество скопированных баров D1  = ",ACR_D1, всего получили 1003
          "\n"," Возвращает количество скопированных баров W1  = ",ACR_W1, здесь 1001
          "\n"," Возвращает количество скопированных баров MN1 = ",ACR_MN1,здесь 323
          "\n",
          "\n");
 
Dark Kchlyzov:

(Get price levels with dates, if needed, and put them in a separate array and compare with this array).

We don't know which ones we need and which ones we don't, we need all possible history of all bars.

ArrayCopyRates

Copies data of the specified chart bars into an array and returns the number of copied bars.

intArrayCopyRates(
MqlRates&rates_array[],// array MqlRates passed by the reference
stringsymbol=NULL,// the tool
inttimeframe=0// timeframe
);


where is it not clear ?

I can't figure out the connection

It sees 323 months which is somewhere close to 27 years, 1403 weeks, 7015 days

AUDUSD history since 1993, 2020-1993= 27



No idea in what can be measured or determined. First we measure the range and we know.

If we write down all the extrema in the daily data over 27 years and identify the equal ones, they will be too many. The task is similar to identifying copies on a disc, only simpler.

Reason: