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

 
Hi all.
This is my first time on the forum, if I'm doing something wrong on the forum, please forgive me in advance.
I am looking at charts with indicators for a long time. Recently I lost 2 deposits. Before opening a new account I want to check the strategy profitability on the history. I am using demo account in MT4.
I am not a programmer at all. I am only able to install indicator on MT4 and maybe change the thickness of the indicator line in MetaEditor (I most likely will not be able to change the colour in the indicator code, only in the terminal).
Do you have any clear information for someone with my knowledge, where to start testing step by step (in plain English "instructions for the niggers how to use the toilet")? The strategy has 3 indicators: MA (3 simple ones), Stochastic with standard levels, and CCI with 5 levels. Opening of short deals after crossing levels of indicators from top to bottom, long deals vice versa (I guess it is clear...). Setting of take and loss.
I would like to be able to visually track the strategy in auto-mode as well as without visualization to select parameters of indicators and orders.
 
ZebStamp:
Hi all.
This is my first time on the forum, if I'm doing something wrong on the forum, please forgive me in advance.
I am looking at charts with indicators for a long time. Recently I lost 2 deposits. I want to check the strategy profitability on the historical data before opening a new account. I am using demo account in MT4.
I am not a programmer at all. I am only able to install indicator on MT4 and maybe change the thickness of the indicator line in MetaEditor (I most likely will not be able to change the colour in the indicator code, only in the terminal).
Do you have any clear info for someone with my knowledge, where to start testing step by step (in plain English "instructions for the niggers how to use the toilet")? The strategy has 3 indicators: MA (3 simple ones), Stochastic with standard levels, and CCI with 5 levels. Opening of short deals after crossing levels of indicators from top to bottom, long deals vice versa (I guess it is clear...). Setting of take and loss.
I would like to be able to track the strategy in auto mode visually, as well as without visualization to select parameters of indicators and orders.

When creating a graphical object (GO), such as TrendLine, you select the colour. When you recreate the TrendLine, it is created with the same colour. For Hline - you choose a colour - and the next one is like this. Take yellow, blue, ...

If CS creates Expert Advisor, indicator, script - then as you write in the programme. Sometimes the choice of parameters

 
STARIJ:

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 it's better to do without InpDirectoryName+"//" - you will find the file in the Files folder anyway.

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


Thanks. I managed to fix something, but more intuitively than by understanding. But we still have 3 errors concerning the array:

'Buf_1' - array required 111.mq4 93 21

'date_Buf_1' - array required 111.mq4 94 21

'Buf_1' - array required 111.mq4 100 16


//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
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[0],true);
   ArraySetAsSeries(date_Buf_1[0],true);

//--- скопируем таймсерию 
   int copied=CopyTime(NULL,0,10000,0,date_Buf_1);

//--- подготовим массив Buf_1 
   ArrayResize(Buf_1[0],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[0],Buf_1[0]);
      //--- закрываем файл 
      FileClose(file_handle);
      PrintFormat("Данные записаны, файл %s закрыт",InpFileName);
     }
   else
      PrintFormat("Не удалось открыть файл %s, Код ошибки = %d",InpFileName,GetLastError());

   return(rates_total);
  }
//+------------------------------------------------------------------+


I don't understand how to implement your comments. But I found an extra staple :)
 
YarTrade:

Thank you. I managed to fix something, but more intuitively than by understanding. But I still have 3 errors concerning the array:

'Buf_1' - array required 111.mq4 93 21

'date_Buf_1' - array required 111.mq4 94 21

'Buf_1' - array required 111.mq4 100 16



I don't understand how to implement your comments. But I found an extra bracket :)
Leave only names of array variables. Remove "[]" in those lines of code to which the compiler points you.
 
Artyom Trishkin:
Leave only names of variable arrays. Remove "[]" in those lines of code to which the compiler points you.

Thank you. I'll see what happens in real life. I have great doubts that something will be written to the file :)

 

A number of questions have arisen, I hope very much for your help. I have found a very sad thing, that EA's performance during testing and in real time is very different, so I would like to analyze the most common and typical errors. I will first write about the ones I have encountered. I would appreciate if you could share your experiences with the programmer who knows what he should keep in mind and what he should keep in his code.

1. The error of division by zero was appearing in the real trading mode, despite the fact that division by zero was not present in the code and it had not occurred during backtests. The programmer solved the problem by writing each divisor as NormalizeDouble(x,Digits);

2. The deal did not open. Friday's day the deal was opened when the backtest was running, but no deal was opened during real trading. Moreover, the journal of the Expert Advisor hasn't shown any errors. I do not know what may be the problem here, but I have a couple of things. First, I got warnings like "return value of 'ordersend' should be checked" but if I understand correctly, this should not affect the code execution? Or is it all about slippage? My value is 1, which is not too small. And the bar at which I should perform an entry opened without a gap.

I took the line "if(Volume[0]>1) return;" from the standard example with slips and inserted it at the beginning of the code. That is, my code is executed only during the first tick when a new bar appears. Can it be that a bar opens with a volume and my code is not executed?

4. Please advise on things to pay attention to or typical errors when working with EA with history and real time, please


 
LuckySith:

A number of questions have arisen, I hope very much for your help. I have found a very sad thing, that EA's performance during testing and in real time is very different, so I would like to analyze the most common and typical errors. I will first write about the ones I have encountered. I would appreciate if you could share your experiences with the programmer who knows what he should keep in mind and what he should keep in his code.

1. The error of division by zero was appearing in the real trading mode, despite the fact that division by zero was not present in the code and it had not occurred during backtests. The programmer solved the problem by writing each divisor as NormalizeDouble(x,Digits);

2. The deal did not open. Friday's day the deal was opened when the backtest was running, but no deal was opened during real trading. Moreover, the journal of the Expert Advisor hasn't shown any errors. I do not know what may be the problem here, but I have a couple of things. First, I got warnings like "return value of 'ordersend' should be checked" but if I understand correctly, this should not affect the code execution? Or is it all about slippage? My value is 1, which is not too small. And the bar at which I should perform an entry opened without a gap.

I took the line "if(Volume[0]>1) return;" from the standard example with slips and inserted it at the beginning of the code. That is, my code is executed only during the first tick when a new bar appears. Can it be that a bar opens with a volume and my code is not executed?

4. Please advise on things to pay attention to, or typical mistakes when working with the EA with history and real time, please

Replace this wild construct "if(Volume[0]>1) return;" with a normal "New Bar" check, the forum is full of them.

Warnings of the "return value of 'ordersend' should be checked" kind are not errors so far, they are potential errors for the future. There shouldn't be any warnings in the code, much less when working online.

"I have 1, which is not too little" - this may be very little at opening a new bar, and especially at the opening of a half-hour or an hour, at this time the spread widens greatly.

What we need: to do a check on the new bar, and if it is new, then watch the conditions for entry, if they coincided - make a deal. After that we have to record that the bar worked out and wait for the new one.

What we have now: if(Volume[0]>1) return; = if there is a new bar, we look for conditions, the condition didn't fit == large spread = exit again in OnTick(), on the next tick if(Volume[0]>1) return; it will not go further, so the trade is already missed, even if the spread is 0.0001

 

Hello. Can you please tell me how to describe the following with the code: There is a flat, bounded by upper and lower horizontal lines. The Expert Advisor detects and sets them by itself.

We need the EA to detect when the price leaves the flat zone and then returns to this zone. And only after that it opens a position.

To filter the noise, I use a moving target with parameter 2 or 3

 
Vitaly Muzichenko:

Replace such wild constructions "if(Volume[0]>1) return;" with normal "New Bar" check, there are plenty of them here on the forum.

Warnings like "return value of 'ordersend' should be checked" - this is not an error yet, this is a potential error for the future. There shouldn't be any warnings in the code, much less when working online.

"I have 1, which is not too little" - this may be very little at opening a new bar, and especially at the opening of a half-hour or an hour, at this time the spread widens greatly.

What we need: to do a check on the new bar, and if it is new, then watch the conditions for entry, if they coincided - make a deal. After that we have to record that the bar worked out and wait for the new one.

What we have now: if(Volume[0]>1) return; = if there is a new bar, then look at the conditions, the condition does not fit == large spread = exit again in OnTick(), on the next tick if(Volume[0]>1) return; it will not miss further, so the trade will be missed even if the spread is 0.0001


About opening a new bar. Would it be good? :

datetime counted_bar = 0;

int OnInit()
{
   counted_bar = 0; // если нужно, чтоб при перезапуске последний бар был проанализирован
   ...

void OnTick()
{
   // Если появился новый бар
   if ( iTime( _Symbol, _Period, 0 ) > counted_bar )
   {
      counted_bar = iTime( _Symbol, _Period, 0 );

      // Анализируем индикаторы
      ...
   }
 
LuckySith:

About opening a new bar. Would that be a good option? :

Let it be like this initially.

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.

As far as I can see from your post, we have to do it this way:

void OnTick()
{
   // Если появился новый бар
   if ( iTime( _Symbol, _Period, 0 ) > counted_bar )
   {
      // Анализируем индикаторы
      if(SpreadMax > текущий спред) return;

      counted_bar = iTime( _Symbol, _Period, 0 );
      ...
   }

The essence is this: if spread is higher than normal, then we exit again toOnTick, and on a new tick check the 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:

void OnTick()
{
   // Если появился новый бар
   if ( iTime( _Symbol, _Period, 0 ) > counted_bar )
   {
      if(SpreadMax > текущий спред) return;
      // Анализируем индикаторы
      ...
      result = OrderSend(...);
      // если открылась позиция, то result будет тикет позиции
       if(result>0) counted_bar = iTime( _Symbol, _Period, 0 );
   }

In general, you need to define the logic, when it should record, and do not check again before the formation of a "New Bar".