Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1340

 
So, it turns out that the script
void OnStart()
  {
   int Target=6;       //Количество тайм-фреймов
   int Counter_UP=0;   //Счетчик нахождения цены над МА
   int Counter_DOWN=0;
   int MA = 200;       //Период МА
   double bufer_MA[];  //Буфер для хендла
   ENUM_TIMEFRAMES frame1[10];  //Битная маска тайм-фреймов
//___________________int битная маска ENUM  Массив таймфреймов__________________________________________
   frame1[1]=1;
   frame1[2]=5;
   frame1[3]=15;
   frame1[4]=30;
   frame1[5]=16385;
   frame1[6]=16388;
   frame1[7]=16408;
   frame1[8]=32769;
   frame1[9]=49153;
//____________________________________________________________________________________________________________

   int KollSymbols = SymbolsTotal(true);  //Колл. символов в маркет вотч
   Alert("Колл.Инстр = ",KollSymbols);
//---
   int MA200;  //Переменная для хендла
   for(int i=0; i<KollSymbols; i++) //Перебераем все символы из маркет вотч
     {
      string symbol = SymbolName(i,true);  //Выбираем имя символа из маркет вотч
     // Alert("symbol = ",symbol,"i= ",i);
      for(int I=1; I<=Target; I++)  //Перебераем таймфреймы
        {
         MA200 = iMA(symbol,frame1[I],MA,0,MODE_EMA,PRICE_MEDIAN);  //хендл на выбранном тайме
         CopyBuffer(MA200,0,TimeCurrent(),5,bufer_MA); // заполнение масива bufer_MA хендлом MA200 выбранного тайма

         ArraySetAsSeries(bufer_MA,true);  //Разворачиваем массив как в тайм-серии

         //Alert("Символ - ",symbol,"i= ",i);
         // Alert("Simbol = ",symbol," bufer_MA[1] = ",bufer_MA[1]);
         if(iClose(symbol,frame1[I],1) > bufer_MA[1])  //Если цена 1 баре, на выбранном символе и тайме, БОЛЬШЕ цены скользяхи на 1 баре
           {
            //Alert("iClose= ",iClose(symbol,frame1[I],1), " bufer_MA[1]= ",bufer_MA[1]);
            Counter_UP++;
            if(Counter_UP==Target)
               Alert("Инструмент для наблюдения в покупки - ",symbol);

            ArrayFree(bufer_MA);      //Очистка буфера индикатора
         
           }
         else
           {
            ArrayFree(bufer_MA);      //Очистка буфера индикатора
           }
         IndicatorRelease(MA200); //Удаление хендла
        }
      Counter_UP=0;
      Counter_DOWN=0;
     }
  }
//+------------------------------------------------------------------+

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

It works fine. And the list of 22 instruments. It takes about 5 minutes. It's weird, though. It spends most of its time writing handles to the array. Profiling results


Question: Why is it so time-consuming to copy 5 values from a handle to an array, although it is copied 132 times for 22 instruments from the list, i.e. for 273 instruments I would need to copy 1632 times, and with loading history for all the instruments on the hard disk.

 
Fast235 #:

about creating and deleting handles,

it works, I'm interested in the right way, I hope the developers will tell me.

That's just what I'm doing, look at the code above, there are questions too))

 
Kira27 #:
So, it turned out that the script

works fine. And the list of 22 tools takes about 5 minutes to process. This is weird, though. It spends most of its time writing the handle to the array. Profiling result


Question: Why is it so time-consuming to copy 5 values from a handle to an array while copying is performed 132 times for 22 tools from the list, i.e. for 273 tools I would need to copy 1632 times with history loading for all the tools to my hard disk.

If I'm not mistaken.

It seems to work normally, if the quotes have been downloaded, it does not slow down. The first start is very long, apparently it downloads the quotes.

//+------------------------------------------------------------------+
void OnStart()
  {
   int Target = 6;     //Количество тайм-фреймов
   int Counter_UP = 0; //Счетчик нахождения цены над МА
   int Counter_DOWN = 0;
   int MA = 200;       //Период МА
   double bufer_MA[];  //Буфер для хендла
   int MA200[][9];  //Переменная для хендла
   string symbol[];

   ENUM_TIMEFRAMES frame1[9];  //Битная маска тайм-фреймов
//___________________int битная маска ENUM  Массив таймфреймов__________________________________________
   frame1[0] = 1;
   frame1[1] = 5;
   frame1[2] = 15;
   frame1[3] = 30;
   frame1[4] = 16385;
   frame1[5] = 16388;
   frame1[6] = 16408;
   frame1[7] = 32769;
   frame1[8] = 49153;
//____________________________________________________________________________________________________________

   int KollSymbols = SymbolsTotal(true);  //Колл. символов в маркет вотч
   Print("Колл.Инстр = ", KollSymbols);
   int res = 0;
   for(int i = 0; i < KollSymbols; i++)
     {
      for(int I = 0; I < 9; I++) //Перебераем таймфреймы
        {
         ArrayResize(MA200, i + 1);
         ArrayResize(symbol, i + 1);
         symbol[i] = SymbolName(i, true); //Выбираем имя символа из маркет вотч
         MA200[i][I] = iMA(symbol[i], frame1[I], MA, 0, MODE_EMA, PRICE_MEDIAN); //хендл на выбранном тайме
         if(MA200[i][I] == INVALID_HANDLE)
            PrintFormat("Инвалид хэндл, символ %s, тайм %d", symbol[i], frame1[I]);
         res++;
        }
     }
   Print("Создано хэндлов = " + (string)res);

//---
   for(int i = 0; i < KollSymbols; i++)
     {
      for(int I = 0; I < 9; I++) //Перебераем таймфреймы
        {
         int size = CopyBuffer(MA200[i][I], 0, 1, 1, bufer_MA); // заполнение масива bufer_MA хендлом MA200 выбранного тайма
         PrintFormat("Скопировано %d, символ %s, тайм %d", size, symbol[i], frame1[I]);
         if(size > 0)
            if(iClose(symbol[i], frame1[I], 1) > bufer_MA[0]) //Если цена 1 баре, на выбранном символе и тайме, БОЛЬШЕ цены скользяхи на 1 баре
              {
               Counter_UP++;
              }
        }
     }
   Print("Counter_UP = " + (string)Counter_UP);
  }
//+------------------------------------------------------------------+
 
Kira27 #:

The point of the script is to go through each instrument from Market Watch on timeframes from 1min to 4H

If I were to do such a thing, I would create an array and store past data in it, updating current data. This would avoid heavy cycles and CopyBuffer. Everything would fly.

 
Aleksandr Slavskii #:

If I'm not mistaken.

It seems to work fine, if the quotes are downloaded, it does not slow down. The first start takes a very long time, I guess it downloads the quotes.

Thank you for your feedback and your version of the program, I will try it)! I only wonder why I don't delete handles before finishing the program or they will be deleted automatically after the program is finished, but the memory is not freed according to the task manager.

 
Aleksei Stepanenko #:

If I were to do such a thing, I would create an array and store past data in it, updating current data. This would avoid heavy loops and CopyBuffer. Everything would fly.

Thanks! I'll think about it too)

 
Kira27 #:

Thank you for your feedback and your version, I will experiment with it)! I don't understand only why you don't delete handles before terminating the program? Or they are automatically deleted at the end of the program, although the RAM is not freed, judging by the task manager.

I read somewhere that indicators handles are automatically deleted after some time interval after the script terminates. But it's not exact.

 
Greetings! Could you please advise how aftertesting an EA in MQL5 to output any of my statistics in a popup window when hovering the mouse over the arrows?
 

Hello

the terminal has a linear regression tool

There are scripts that draw the same channel with graphical objects

But only the central line is drawn correctly, deviation lines are drawn at an incorrect distance from the central one

advise if you know the correct formula for calculating the deviation, it should be like in the terminal

or maybe there is a ready-made solution

THANK YOU

 

Hello!

Can you please tell me why OrderSend function on cryptocurrency does not work when testing with AMarkets broker. I couldn't find any prohibition on trading advisors on crypto by the regulations. Or maybe I have errors in my code? GetLastError gives error 4756

#property copyright "qwerty"
#property link      "qwerty@list.ru"
#property version   "1.00"
//-----------------
//-----------------
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
//-----------------
//-----------------
CPositionInfo  aPosition;
CTrade         aTrade;
CSymbolInfo    aSymbol;
CAccountInfo   aAccount;
//-----------------
//-----------------

int      Slippage      = 3000;
//---
//---------------------------------
//------пробные переменные
double LotsCrypto = 0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!aSymbol.Name(Symbol()))
      return(INIT_FAILED);
   RefreshRates();
//---устанавливаем допустимое проскальзывание
   aTrade.SetDeviationInPoints(Slippage);
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
  RefreshRates();
   LotsCrypto = 0.1;
   if(OpenSellPosition(aSymbol.Name(), LotsCrypto, NULL, Slippage, ORDER_FILLING_RETURN))
      Print("Ура");  
   Comment("Symbol.Name = " + string(aSymbol.Name()) + "\n" +
           "Ask = " +  string(aSymbol.Ask()) + "\n"+
           "GetLastError = " +  string(GetLastError()) + "\n"+
           "LotsCrypto = " +  string(LotsCrypto));

}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//+ Обновление котировок                                             +
//+------------------------------------------------------------------+
bool RefreshRates()
  {
   if(!aSymbol.RefreshRates())
     {
      Print("Не удалось обновить котировки валютной пары!");
      return(false);
     }
   if(aSymbol.Ask() == 0 || aSymbol.Bid() == 0)
      return(false);
   return(true);
  }

//+------------------------------------------------------------------+
bool OpenSellPosition(string symbol, double volume, string comment="", ulong deviation=1000, ENUM_ORDER_TYPE_FILLING filling=ORDER_FILLING_FOK)
  {
   MqlTradeRequest Request;
   MqlTradeResult Results;
   ZeroMemory(Request);
   ZeroMemory(Results);
   Request.price=SymbolInfoDouble(_Symbol,SYMBOL_BID);
   Request.action=TRADE_ACTION_DEAL;
   Request.type=ORDER_TYPE_SELL;
   Request.symbol=symbol;
   Request.volume=volume;
   Request.deviation=deviation;
   Request.comment=comment;
   Request.type_filling=filling;
   bool res=false;
   res=OrderSend(Request,Results);
   if(res)
     {
      if(Results.deal>0)
         return(true);
      else
         return(false);
     }
   return(false);
  }
//+------------------------------------------------------------------+
Reason: