Preguntas de los principiantes MQL5 MT5 MetaTrader 5 - página 1219

 
Vladimir Karputov:

Parece que el terminal sigue bombeando el historial, por lo que el indicador sigue recalculando. U otra variante: tienes un número MUY grande de barras configuradas en el terminal para su visualización en el gráfico, y tu ordenador tiene un número MUY grande de barras en el gráfico.

Gracias por la ayuda.

Si selecciona una fecha diferente, el cálculo se realiza inmediatamente. En la primera prueba hubo un desfase en el precio, posiblemente faltaron algunos precios - este es muy probablemente el problema.

 

Hola, hay un indicador MT5 "Grid Builder" que dibujalíneas horizontales en incrementos de precio. Puede seleccionar, por ejemplo, 100p, 200p, etc. Y construye una cuadrícula horizontal hacia arriba y hacia abajo con un paso determinado. Pero tiene un problema, por ejemplo, cuando dibujo niveles horizontales en el timeframe H4 (pongo líneas horizontales desde las herramientas de dibujo en el terminal) y cambio a cualquier otro timeframe, todas mis líneas se eliminan. Sólo quedan los niveles de los indicadores horizontales. ¿Cómo puedo corregir este error en el código? Para garantizar que mis niveles horizontales no se borren nunca. Aquí está el código del indicador (escribí esta pregunta en otro hilo, pero aún no hay respuesta)

//+------------------------------------------------------------------+
//|                                                  GridBuilder.mq5 |
//|                                              Copyright 2015, AM2 |
//|                                     https://www.forexsystems.biz |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, AM2"
#property link      "https://www.forexsystems.biz"
#property version   "1.00"
#property indicator_chart_window

//---- для расчёта и отрисовки индикатора использовано ноль буферов
#property indicator_buffers 0
//---- использовано всего ноль графических построений
#property indicator_plots   0
//--- входные параметры 
input int count = 50;      //количество линий вверх вниз от цены
input int step  = 333;     //шаг линий 
input double pr = 1.4622;  //цена от которой пляшем
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   ObjectsDeleteAll(0,0,OBJ_HLINE);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   Comment("");
   ObjectsDeleteAll(0,0,OBJ_HLINE);
  }
//+------------------------------------------------------------------+ 
//| Создает горизонтальную линию                                     | 
//+------------------------------------------------------------------+ 
bool HLine(const string name="HLine",double price=0)
  {
//--- создадим горизонтальную линию 
   if(!ObjectCreate(0,name,OBJ_HLINE,0,0,price))
     {
      Print(__FUNCTION__,
            ": не удалось создать горизонтальную линию! Код ошибки = ",GetLastError());
      return(false);
     }
//--- установим цвет линии 
   ObjectSetInteger(0,name,OBJPROP_COLOR,clrGreen);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,1);
   return(true);
  }
//+------------------------------------------------------------------+
//| 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[])
  {
   double price=pr;
//--- создадим горизонтальную линию 
   for(int i=0;i<=count;i++)
     {
      HLine("HLine"+(string)i,price+step*i*_Point);
      HLine("HLine"+(string)(i+count+1),price-step*i*_Point);
     }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
Документация по MQL5: Константы, перечисления и структуры / Константы объектов / Типы объектов
Документация по MQL5: Константы, перечисления и структуры / Константы объектов / Типы объектов
  • www.mql5.com
При создании графического объекта функцией ObjectCreate() необходимо указать тип создаваемого объекта, который может принимать одно из значений перечисления ENUM_OBJECT. Дальнейшие уточнения свойств созданного объекта возможно с помощью функций по работе с графическими объектами.
 
Александр:

Hola, hay un indicador MT5 "Grid Builder" que dibujalíneas horizontales en incrementos de precio. Puede seleccionar, por ejemplo, 100p, 200p, etc. Y construye una cuadrícula horizontal hacia arriba y hacia abajo con un paso determinado. Pero tiene un problema, por ejemplo, cuando dibujo niveles horizontales en el timeframe H4 (pongo líneas horizontales desde las herramientas de dibujo en el terminal) y cambio a cualquier otro timeframe, todas mis líneas se eliminan. Sólo quedan los niveles de los indicadores horizontales. ¿Cómo puedo corregir este error en el código? Para garantizar que mis niveles horizontales no se borren nunca. Aquí está el código del indicador (escribí esta pregunta en otro tema, pero no hay respuesta)

Preste atención a este código:

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   Comment("");
   ObjectsDeleteAll(0,0,OBJ_HLINE);
  }
//+------------------------------------------------------------------+ 

En particular, lea sobre ObjectsDeleteAll() - allí la causa y la respuesta para arreglarlo.

Документация по MQL5: Графические объекты / ObjectsDeleteAll
Документация по MQL5: Графические объекты / ObjectsDeleteAll
  • www.mql5.com
[in]  Префикс, по которому будут удалены все объекты, чьи имена начинаются с данного набора символов. Префикс можно указывать как 'name' или 'name*' – оба варианта работают одинаково. Если в качестве префикса указана пустая строка, то будут удалены объекты с любым именем. Функция использует синхронный вызов – это...
 
Artyom Trishkin:

Presta atención a este código:

En particular, lea sobre ObjectsDeleteAll() - ahí está la razón y la respuesta sobre cómo ajustarlo.

¡¡¡Gracias!!! Lo he solucionado, ahora funciona sin necesidad de borrar.

 
¿Están disponibles las operaciones de la base de datos SQLite en el probador? Me refiero a añadir y modificar datos.
 
Dmitri Custurov:
¿Las operaciones de la base de datos SQLite están disponibles en el probador? Me refiero a añadir y modificar datos.

Disponible. Sólo hay que vigilar la ubicación de la base. Se crean de la misma manera que los archivos.

 
Alexey Viktorov:

Disponible. Sólo hay que vigilar la ubicación de la base. Se crean igual que los archivos.

#define  DB_NAME "OHLC_DB"

int db_handle;
string TableName;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(){
   db_handle = DatabaseOpen(DB_NAME, DATABASE_OPEN_READWRITE|DATABASE_OPEN_CREATE); 

   if (db_handle != INVALID_HANDLE){
      Print(StringFormat("Database %s was opened", DB_NAME));
      
      TableName = Symbol() + "_" + enumTimeFrameToString(Period());
      if (DatabaseTableExists(db_handle, TableName)){
         Print(StringFormat("Table %s is exist", TableName));
      }else{
         if (DatabaseExecute(db_handle, "CREATE TABLE " + TableName + "("
                             "TIME TEXT PRIMARY KEY  NOT NULL,"
                             "OPEN              REAL NOT NULL,"
                             "HIGH              REAL NOT NULL,"
                             "LOW               REAL NOT NULL,"
                             "CLOSE             REAL NOT NULL );")){
            Print(StringFormat("Table %s was created", TableName));
            string time = "'" + TimeToString(iTime(Symbol(), PERIOD_CURRENT, 0)) + "'";
            double open = iOpen(Symbol(), PERIOD_CURRENT, 0);
            double high = iHigh(Symbol(), PERIOD_CURRENT, 0);
            double low = iLow(Symbol(), PERIOD_CURRENT, 0);
            double close = iClose(Symbol(), PERIOD_CURRENT, 0);

            if (!DatabaseExecute(db_handle,"INSERT INTO " + TableName + " (TIME,OPEN,HIGH,LOW,CLOSE) "
                                           "VALUES (" + StringFormat("%s,%.5f,%.5f,%.5f,%.5f", time, open, high, low, close) + ");")){
               Print("Table: ", TableName, " insert failed with code ", GetLastError());
               DatabaseClose(db_handle);
               return(INIT_FAILED);
            }else
               Print("New table started:");   
         }else{
            Print(StringFormat("Could not create %s table. Error is: %d", TableName, GetLastError()));
            DatabaseClose(db_handle);
            return(INIT_FAILED); 
         }
      }
      
      return(INIT_SUCCEEDED);
   }else{
      Print("Could not open db. Error is: ", GetLastError());
      return(INIT_FAILED); 
   }     
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason){
   DatabaseClose(db_handle);
}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(){
   string time = "'" + TimeToString(iTime(Symbol(), PERIOD_CURRENT, 0)) + "'";
   double open = iOpen(Symbol(), PERIOD_CURRENT, 0);
   double high = iHigh(Symbol(), PERIOD_CURRENT, 0);
   double low = iLow(Symbol(), PERIOD_CURRENT, 0);
   double close = iClose(Symbol(), PERIOD_CURRENT, 0);
   if (!DatabaseExecute(db_handle,"INSERT INTO " + TableName + " (TIME,OPEN,HIGH,LOW,CLOSE) "
                                  "VALUES (" + StringFormat("%s,%.5f,%.5f,%.5f,%.5f", time, open, high, low, close) + ");")){
      Print("Table: ", TableName, " insert failed with code ", GetLastError());
      DatabaseClose(db_handle);
   }   
}
//+------------------------------------------------------------------+
string enumTimeFrameToString(ENUM_TIMEFRAMES frame){
   switch(frame){
      case PERIOD_M1:  return "M1";
      case PERIOD_M2:  return "M2";
      case PERIOD_M3:  return "M3";
      case PERIOD_M4:  return "M4";
      case PERIOD_M5:  return "M5";
      case PERIOD_M6:  return "M6";
      case PERIOD_M10: return "M10";
      case PERIOD_M12: return "M12";
      case PERIOD_M15: return "M15";
      case PERIOD_M20: return "M20";
      case PERIOD_M30: return "M30";
      case PERIOD_H1:  return "H1";
      case PERIOD_H2:  return "H2";
      case PERIOD_H3:  return "H3";
      case PERIOD_H4:  return "H4";
      case PERIOD_H6:  return "H6";
      case PERIOD_H8:  return "H8";
      case PERIOD_D1:  return "D1";
      case PERIOD_W1:  return "W1";
      default:         return "MN1";
   }
}

Aquí está mi código. En la inicialización se crea un registro en la tabla. En el cuerpo de OnTick debería devolver inmediatamente un error, porque intento añadir un registro con la misma PRIMARY KEY, y después de eso la base se cierra inmediatamente. Pero al mismo tiempo debería ver al menos ese primer registro cuando lo abro, pero cuando lo ejecuto en el probador no está. Y ni siquiera se crea la tabla. Si lo abro en el terminal, todo es normal. El primer disco está ahí.

 
Dmitri Custurov:

Aquí está mi código. En la inicialización se crea un registro en la tabla. En el cuerpo de OnTick debería devolver inmediatamente un error, porque intento añadir un registro con la misma PRIMARY KEY, y después de eso la base se cierra inmediatamente. Pero al mismo tiempo debería ver al menos ese primer registro cuando lo abro, pero cuando lo ejecuto en el probador no está. Y ni siquiera se crea la tabla. Si lo abro en el terminal, todo es normal. El primer disco está ahí.

Una vez más estoy convencido de que el probador y el propio terminal son hipóstasis diferentes...

 
HistorySelect(xxx,TimeCurrent()) miss the latest history order / deal sometimes. Now you have to use HistorySelect(xxx,TimeCurrent()+1) To get a more accurate result.

 
tickfenix:

Hace tiempo que se recomienda añadir un día aTimeCurrent(). Es que ahora, en respuesta a tu código no del todo correcto, la terminal te está dando consejos.

Razón de la queja: