Mt4 End of support. - page 30

 
Реter Konow:

The burden is placed on the computer by the developer's negligent attitude towards the coherence of their mechanism. A desire to save energy on improving the system. Unreasonable consumption of computer resources in the name of making their work easier.

As long as the computer successfully copes with inefficiently written code, the developer will continue to "parasitize" on the processing power. This is a dead-end road.

Sooner or later, the ineffective mechanism will stop developing and be replaced by a better counterpart.

Man's time and effort will be wasted and his brainchild will end up in the dustbin.

In the competitive world, this risk exists all the time.

Designing mechanisms, we should think about their performance in the first place, and about the comfort and convenience of spending our working hours in the second.)

You still haven't written a function to define a new bar in procedural style.

Forum on trading, automated trading systems and testing trading strategies

Mt4 End of support.

Artyom Trishkin, 2017.09.10 23:21

I had a goal for the end result of his procedural style code to work in such a loop:

   ENUM_TIMEFRAMES array_timeframes[]=
      {
      PERIOD_M1,PERIOD_M2,PERIOD_M3,PERIOD_M4,PERIOD_M5,PERIOD_M6,PERIOD_M10,PERIOD_M12,PERIOD_M15,PERIOD_M30,
      PERIOD_H1,PERIOD_H2,PERIOD_H3,PERIOD_H4,PERIOD_H6,PERIOD_H8,PERIOD_H12,PERIOD_D1,PERIOD_W1,PERIOD_MN1
      };
   int total=SymbolsTotal(true), total_tf=ArraySize(array_timeframes);
   for(int i=0; i<total; i++){
      string symbol_name=SymbolName(i,true);
      for(int j=0; j<total_tf; j++){
         if(IsNewBar(symbol_name,array_timeframes[j])){
            Print("Новый бар на ",symbol_name," ",EnumToString(array_timeframes[j]));
            }
         }
      }

 
Реter Konow:

Yes, we discussed this yesterday.

I used to deal with another platform and there the bars were formed by time, regardless of quotes coming in (look in TWS).

I was told that this is not the case on MT.

I will add a quote arrival check to confirm a new bar occurrence event.

Been looking at it for a while now. Interesting platform, but as I understand it's not free, and if you're not sure you'll make money, it's a shame to pay to use the toy...

 

Apparently my experiment with trying to explain the self-taught point of view failed...

 
Vladimir:

Is there, in principle, an example of this? Even if not yours? I have deep doubts. In early 2000's I stopped counting the number of debugged and working lines of code I wrote because it exceeded a million, it became uninteresting .

An elementary example would be to add another n-series of inputs to the EA, with different input parameters.
And, of course, maintaining these n-positions, with separate parameters, until closing.

...And most likely ( using oop) lines of code, you would have fewer. Although, there are adept at bloating the oop code)

 
Aleksey Altukhov:

I don't know if anyone has suggested it, but why not move everything in MT4 to MT5, then everyone would move.


And who would transfer this mountain of accumulated EAs, indicators and scripts?

 

I think I've found a primitive example of the usability of OOP. Here's a function for filling an array with a specified value. There are eight varieties, depending on the type of array.

Imagine you need to write a function that needs to pass one set of parameters, then another, then a third... Using algorithmic approach you'll get N different function's names. It would seem that there is nothing wrong, you can write 8 such functions as ArrayInitializeInt()ArrayInitializeDouble() and so on. But it's nice not to think about the type of array, just use one function in any case, and how safe it is to mix up which array you put there...

Документация по MQL5: Операции с массивами / ArrayInitialize
Документация по MQL5: Операции с массивами / ArrayInitialize
  • www.mql5.com
Операции с массивами / ArrayInitialize - справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 

Developed a new solution for the new bar function. It is simpler and more concise. It has the possibility to receive notification about the new bar event on any of the symbols that are available in the market overview and on any of the preset timeframes.

If you see any errors, please comment.

//+------------------------------------------------------------------+
//|                                                  Новый бар 2.mq4 |
//|                                                      Peter Konow |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Peter Konow"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
datetime Время_последнего_бара;

int      Частота_таймера        = 25;
int      Всех_символов;
int      Таймфреймы[7]          = {PERIOD_M1,PERIOD_M5,PERIOD_M15,PERIOD_M30,PERIOD_H1,PERIOD_H4,PERIOD_D1};
int      Всех_таймфреймов       = 7;
int      Количество_баров[][7];
bool     События_нового_бара[][7];

string   Символы[];
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create timer
   EventSetMillisecondTimer(25);
   //-------------------------------------------------------------
   //Записываем время последнего бара на момент загрузки эксперта.  
   //Для корректного начала работы, робота нужно запустить на М1. 
   //-------------------------------------------------------------
   Время_последнего_бара = Time[0];
   //-------------------------------------------------------------   
   //Узнаем сколько символов есть в обзоре рынка.
   //---------------------------------------------------------
   Всех_символов = SymbolsTotal(true);
   //---------------------------------------------------------   
   //Устанавливаем размер массива Символы. Внутри него будут записаны
   //имена всех символов, которые есть в окне обзоре рынка.
   //---------------------------------------------------------
   ArrayResize(Символы,Всех_символов);
   //---------------------------------------------------------
   //Устанавливаем размеры массивов "Количество_баров[]" и "События_нового_бара[]".
   //В массиве "Количество_баров[]" будет записыватся текущее количество баров каждого символа
   //и каждого таймфрейма. А в массиве "События_нового_бара[]" устанавливаться флаги
   //события нового бара для каждого символа и каждого таймфрейма. 
   //---------------------------------------------------------
   ArrayResize(Количество_баров,Всех_символов);
   ArrayResize(События_нового_бара,Всех_символов);
   //---------------------------------------------------------
   //Записываем наименования символов обзора рынка в массив "Символы[]".
   //---------------------------------------------------------
   for(int a1 = 0; a1 < Всех_символов; a1++)
     {
      Символы[a1] = SymbolName(a1 + 1,true); 
      //Возможно, нумерация символов в обзора рынка идет с нуля.
      //Тогда: Символы[a1] = SymbolName(a1,true);
     }
   //---------------------------------------------------------
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();
      
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
{
 static bool Начало_отсчета;
 static int  Минута;
 //---------------------------
 //Нам нужен корректный старт отсчета. Это должно быть время начала бара.
 //---------------------------
 if(!Начало_отсчета && Time[0] != Время_последнего_бара)Начало_отсчета = true; 
 //--------------------------- 
 if(Начало_отсчета)Минута++;
 //--------------------------- 
 //В следующем цикле, мы будем обращатся к функции iBars (раз в минуту) для получения количества баров на 
 //каждом из символов и таймфреймов, которые будем проходить в цикле.
 //Далее, будем сравнивать записанное количество баров с текущим и при 
 //наличии разницы установим флаг события нового бара в массив "События_нового_бара[]".
 //---------------------------
 if(Минута*Частота_таймера >= 60000)
   {
    for(int a1 = 0; a1 < Всех_символов; a1++)
      {
       string Этот_символ = Символы[a1];
       //---------------------------------
       for(int a2 = 0; a2 < Всех_таймфреймов; a2++)
         {
          int Этот_таймфрейм = Таймфреймы[a2];
          //------------------------------------------
          int Текущее_количество_баров = iBars(Этот_символ,Этот_таймфрейм);
          //------------------------------------------
          if(Текущее_количество_баров > Количество_баров[a1][a2])
            {
             //------------------------------------------------------------
             //Если это не самая первая запись в массив Количества баров,
             //то фиксируем событие нового бара.
             //------------------------------------------------------------
             if(Количество_баров[a1][a2])События_нового_бара[a1][a2]  = true;
             //------------------------------------------------------------
             //Устанавливаем новое значение текущего количества баров.
             //------------------------------------------------------------
             Количество_баров   [a1][a2]  = Текущее_количество_баров;
            }
          //------------------------------------------
         }
      }
    //---------
    Минута = 0;
   }
 //-----------------------------------------------
    
}
//+------------------------------------------------------------------+






//---------------------------------------------------------------------
//Функция Новый_бар() принимает наименование символа и таймфрейм.
//Она делает цикл по массиву символов, находит совпадение наименований и 
//с запрашиваемым символом, и далее ищет нужный таймфрейм для получения
//индекса ячейки массива в которой он находится. 
//Найдя индекс ячейки имени нужного символа и индекс ячейки нужного
//таймфрейма, функция обращается к массиву "События_нового_бара" и 
//возвращает факт события нового бара или его отсутствие.
//После возврата флага события, функция снимает этот флаг.
//Следовательно, флаг события можно получить только один раз за бар.
//---------------------------------------------------------------------
bool Новый_бар(string Символ, int Таймфрейм)
{
 bool Новый_бар;
 //-----------------------
 for(int a1 = 0; a1 < Всех_символов; a1++)
   {
    if(Символы[a1] == Символ)
      {
       for(int a2 = 0; a2 < Всех_таймфреймов; a2++)
         {
          if(Таймфреймы[a2] == Таймфрейм)
            {
             Новый_бар  = События_нового_бара[a1][a2];
             if(Новый_бар)События_нового_бара[a1][a2] = 0;
             return(Новый_бар);
            }
         }
      }
   }
 //-----------------------
 return(false);
}
//+------------------------------------------------------------------+
 
Реter Konow:

Developed a new solution for the new bar function. It is simpler and more concise. It has the possibility to receive notification about the new bar event on any of the symbols that are available in the market overview and on any of the preset timeframes.

If you see any errors, please comment.


4 cycles isn't it cool ? at 600 symbols in market overview every minute the terminal will die ....

 
Реter Konow:

Developed a new solution for the new bar function. It is simpler and more concise. It has the possibility to receive notification about the new bar event on any of the symbols that are available in the market overview and on any of the preset timeframes.

If you see any errors, please comment.

I don't expect this function to jump into OnTimer() and I have already commented on my idea

Forum on trading, automated trading systems and strategy testing

Mt4 End Support.

Alexey Viktorov, 2017.09.11 10:09

Apparently my experiment with trying to explain a self-taught point of view failed...


 
Реter Konow:

Developed a new solution for the new bar function. It is simpler and more concise. It has the possibility to receive notification about the new bar event on any of the symbols that are available in the market overview and on any of the preset timeframes.

If you see any errors, please comment.

As for comments on the code: What if you need to define the opening of the current period and only one symbol in the program? The whole structure will loop all the loops? It's not rational.

ps; And why should I start a millisecond timer? Isn't a second timer enough?