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

 
Taras Slobodyanik:

I don't see zero, you've messed up somewhere.


Do both printers give the same values?

Because there are no Print functions in my code and these lines follow one after another, so the values don't change in any way.

But Var gives 0 and Code gives the needed value

 
LuckySith:

But I output the value I'm assigning right away. So the code is essentially as follows:

a=b;

Print (a);

Print (b);

But a equals zero while b is printed correctly

It is possible if int a and double b>0 and b<1 when assigning a real value to an integer variable, the fractional part is discarded

 
STARIJ:

This is possible if int a and double b>0 and b<1 when assigning a real value to an integer variable, the fractional part is discarded


b is greater than one much greater than one

a is an array of type double

 

The problem has been solved.

I created the array in the following way:


double line[];

With this option, when assigning line[0]=x; the null element still appeared to be empty.


When I wrote


double line[20];


Everything is working as it should. I don't understand why, in the first case I simply created an unbounded array; what is the difference?

 
LuckySith:

The problem has been solved.

I created the array in the following way:


double line[];

With this option, when assigning line[0]=x; the null element still appeared to be empty.


When I wrote


double line[20];


Everything is working as it should. I don't understand why, in the first case I simply created an unbounded array; what is the difference?

You have created a dynamic array, while its size should be set and controlled by yourself.

 
Artyom Trishkin:

You have created a dynamic array, but you need to set and control the size yourself.

The #property strict directive speeds up the finding of this error. The program ends with a message like: array out of range in 'C.mq4' (31,32)
 

Is no one there to help? The dead end for me is set out here:writing the current iVolume informationto the file?

The software code is described here:https://www.mql5.com/ru/forum/160683/page378#comment_6053255

Любые вопросы новичков по MQL4, помощь и обсуждение по алгоритмам и кодам
Любые вопросы новичков по MQL4, помощь и обсуждение по алгоритмам и кодам
  • 2017.11.14
  • www.mql5.com
В этой ветке я хочу начать свою помощь тем, кто действительно хочет разобраться и научиться программированию на новом MQL4 и желает легко перейти н...
 
LRA:

Indicator by data from file - entered this line in the search and found


To retrieve data from a file, you must first fill it in.

 

Ow... Good people! Help, please! I'm learning how to program. Without your help it's a deadlock.

I am trying to write the indicator data into a file, so I can use it later to build an indicator. The indicator is drawn as a line based on the difference between the volume of positive ticks and volume of negative ticks for the current bar.

I used MQL4 Reference to receive information about how to upload a data array to a file. I have ended up with a code full of errors. I cannot understand the essence of errors, and in general I have not used correctly the hint from the reference book or not. Can anyone help?

input string             InpFileName="111.csv";      // Имя файла 
input string             InpDirectoryName="Data";     // Имя каталога 

datetime Время=0;   // Время прошлого бара
double Bid1;
double   Buf_1[];
// double ExtBuffer;
long V1; // объем для текущего тика вверх
long V2; // накопленный объем для всех тиков вверх текущего бара
long V3; // объем текущего тика вниз
long V4; // накопленный объем для всех тиков вниз для текущего бара
long V5;  // отрицательные и положительные iVolume нарастающим итогом


void OnInit()
{
   IndicatorDigits(0);
   SetIndexBuffer(0,Buf_1);
   //SetIndexBuffer(1,Buf_2);
   Bid1=Bid;
   V5 = 0;
    
}
 
 
//+------------------------------------------------------------------+
//| 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[])
{
   datetime Вр=Time[0];   // Время текущего бара
   if(Вр>Время)           // Если новый бар
   {
      Время=Вр;           // Запомнить
//      Buf_1[0]=0;         // и обнулить последний элемент буфера
   }
   
   datetime date_Buf_1; // массив дат индикатора 
   datetime time_Buf_1; // массив времени 
// --- считаю объем для положительных и отрицательных тиков      
   if(Bid >= Bid1) 
{
   if(Bid > Bid1) // если тик положительный..
{   
   V1 = iVolume(NULL, 0, 0); // если повышающий цену тик, то находим его объем
   V2 = V1 + V2;
}
  else
{
   V1 = 0;                // если Bid1 = Bid2, т.е. изменение цены = 0, то iVolume этого тика присваиваем 0;
   V2 = V1 + V2;      
}               
}              
   else 
{
   V3 = iVolume(NULL, 0, 0); // если понижающий цену тик 
   V4 = V3 + V4;             // то находим его объем  
}
  
   V5 = V2-V4;               // определяем разницу (дельту) между объемами положительных и отрицательных тиков
   Bid1=Bid;
   Buf_1 [0] = V5; // в буфер сгружаем  дельту

//   ExtBuffer = Buf_1 [0];
//   double macurrent=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,0); 

// запись в файл данных буфера

//--- установим для массивов признак таймсерии 
   ArraySetAsSeries(Buf_1,true); 
   ArraySetAsSeries(date_Buf_1,true);
   
//--- скопируем таймсерию 
   int copied=CopyTime(NULL,0,0,0,date_Buf_1);    

//--- подготовим массив Buf_1 
   ArrayResize(Buf_1,copied); 
//--- скопируем значения линии индикатора  
   for(int i=0;i<copied;i++) 
     { 
      Buf_1[i]= V5; 
     } 
//--- откроем файл для записи значений индикатора 
   ResetLastError(); 
   int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FILE_CSV); 
   if(file_handle!=INVALID_HANDLE) 
     { 
      PrintFormat("Файл %s открыт для записи",InpFileName); 
      PrintFormat("Путь к файлу: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH)); 
      //--- сначала запишем значения индикатора 
      FileWrite(file_handle,Buf_1); 
      //--- запишем время и значения в файл 
      for(int i=0;i<Buf_1;i++) 
         FileWrite(file_handle,time_Buf_1[i],Buf_1[i]); 
      //--- закрываем файл 
      FileClose(file_handle); 
      PrintFormat("Данные записаны, файл %s закрыт",InpFileName); 
     } 
   else 
      PrintFormat("Не удалось открыть файл %s, Код ошибки = %d",InpFileName,GetLastError()); 
  }
   
  return(rates_total);
}
 
YarTrade: I am trying to write the indicator data into a file so that I can use it later to build the indicator. The indicator is built as a line, based on data on the difference between the volume of positive ticks and the volume of negative ticks for the current bar.

If you think that someone looking at your code can quickly find an error, you are mistaken. The compiler looks for errors. The program text should be formatted - MetaEditor has a styling tool for that. If you like a different style - use, for example, the AStyle.exe program. After styling, you will quickly see that the program 1) has an extra closing parenthesis. 2) Declared variable: datetime date_Buf_1; // indicator date array - for this to be an array, it must be [size] or [] for a dynamic array and then the size must be set to ArrayResize it seems. And you have to do it before you use an array - see above posts about it. 3) FileOpen(InpDirectoryName+"//"+InpFileName - seems like the sticks should be tilted in the other direction. And you'd better do without InpDirectoryName+"//" - you will find the file in the Files folder anyway.

on line: int copied=CopyTime(NULL,0,0,0,date_Buf_1); the compiler gets angry, start=end=0 number=0

Стилизатор - Работа с исходным кодом - Разработка программ - Справка по MetaEditor
Стилизатор - Работа с исходным кодом - Разработка программ - Справка по MetaEditor
  • www.metatrader5.com
Данная функция предназначена для оформления исходного кода в соответствии с рекомендуемым стандартом. Это позволяет сделать код более читаемым, выглядящем профессионально. Грамотно оформленный код гораздо проще анализировать в последующем как его автору, так и другим пользователям. Для того чтобы запустить стилизатор, необходимо выполнить...
Reason: