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

 
Vitaly Muzichenko:

Let it initially be like this.

Next, we need to make a proper fixation that the bar is worked out, but here we need to calculate the whole approach to the TOR.

So far, what I see from your post, we need to do this:

The essence is that if spread is more than normal, then we go out again toOnTick, and on a new tick we check spread, if it is normal - we send an order and remember that there was a trade on this bar.

There is also a second way:

In general, you need to define the logic, when it should record, and do not check again until the "New bar" is formed.


I understand you, thank you!

 

Gentlemen, can you give me a hint? I have been trying to write the indicator data into a file for the second week in order to read it later and build an indicator based on the data. The indicator is a training one, I calculate volume on each tick of a certain bar. If the tick is positive its volume is added with "+", if it is negative - with "-". I add obtained accumulated volumes and obtain a delta and consider this delta cumulative. This produces a curve. However, this curve is built only in real time. It cannot be plotted in history. For this purpose, I have decided to write the data into a file. I got stuck at this stage. I've managed with a bitterness that the code won't generate compiler errors. However, the resulting product doesn't work. The indicator worked before that. After I've attached the code for writing the file to it the indicator doesn't work anymore. The program creates a file with one incomprehensible record and dies at this point. I've been sitting here all day and can't figure it out. Can anyone help me?

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2012, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property version   "1.00"
#property strict
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_label1  "Вверх"
#property indicator_type1   DRAW_LINE
#property indicator_color1  Salmon
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2

#property indicator_label2  "Вниз"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrDarkTurquoise
#property indicator_style2  STYLE_SOLID
#property indicator_width2  2

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[0]);
      //--- запишем время и значения в файл 
      for(int i=0;i<Buf_1[0];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:

Gentlemen, can you give me a hint? I have been trying to write the indicator data into a file for the second week in order to read it later and build an indicator based on the data. The indicator is a training one, I calculate volume on each tick of a certain bar. If the tick is positive its volume is added with "+", if it is negative - with "-". I add obtained accumulated volumes and obtain a delta and consider this delta cumulative. This produces a curve. However, this curve is built only in real time. It cannot be plotted in history. For this purpose, I have decided to write the data into a file. I got stuck at this stage. I've managed with a bitterness that the code won't generate compiler errors. However, the resulting product doesn't work. The indicator worked before that. After I've attached the code for writing the file to it the indicator doesn't work anymore. The program creates a file with one incomprehensible record and dies at this point. I've been sitting here all day and can't figure it out. Can anyone help me?


It would be a good idea to move the pointer to the end of the file before recording.

FileSeek - Файловые операции - Справочник MQL4
FileSeek - Файловые операции - Справочник MQL4
  • docs.mql4.com
Если выставить позицию за "правую границу" файла (больше, чем размер файла), то последующая запись в файл будет будет произведена не с конца файла, а с выставленной позиции. При этом между предыдущим концом файла и выставленной позицией будут записаны неопределенные значения...
 
Alexey Viktorov:

It would be good to move the pointer to the end of the file before writing.


What is this for? I've read the link, but I don't understand it.

 
YarTrade:

What is this for? I read the link, but I don't understand it.

What for? When you open a file, the pointer is positioned at the beginning of the file and information is written at the beginning of the file. To write to the right place, you have to move the pointer to the right place.

 
YarTrade:

Gentlemen, can you give me a hint? For the second week I've been trying to write indicator data to a file...

Have you read it?
 
Alexey Kozitsyn:
Have you read it?

I'm still learning MQL4. I haven't read.

Is there an online training service where you can learn MQL4 for free/paid by examples with an instructor? I have almost read an MQL4 tutorial, but I cannot program at all. I am not familiar with programming before. I am trying to learn something in this thread, but I haven't made any progress. May you give me some advice?

 
YarTrade:

I'm still learning MQL4. I haven't read.

Is there an online training service where you can learn MQL4 for free/paid by examples with a tutor? I have almost read an MQL4 tutorial, but I cannot program at all. I am not familiar with programming before. I am trying to learn something in this thread, but I haven't made any progress. Can you give me some suggestions?

1. Working with files in mql4 is the same as in mql5.

2. With all due respect to Sergei Kovalev, he also answered my questions in his time, but in my opinion, the lessons from Kirill are easier to understand. In Yandex you type in and immediately 2 links to his lesson


 

Hello! The tutorial from the website was enough for me, after a few years of beating about the baffles I learned to write my own indicators. But the questions remain. Now I do not understand why indicators get confused. On M1 after about 12 hours some of them start drawing incorrectly but signal correctly. Some draw and signal incorrectly. On M5 they keep drawing five times longer. Can you give me a hint please.

 
Alexey Viktorov:

1. The handling of files in mql4 is the same as in mql5.

2. With all due respect to Sergei Kovalev, he also answered my questions in his time, but in my opinion, Kirill's lesson is easier to understand. In Yandex, type on and immediately 2 links to his lesson



Is it feasible to learn with the help of "Kirill's" lessons if you have not engaged in programming before? How long does it take?

Reason: