Errores, fallos, preguntas - página 2133

 
Error en CCanvas::Attach. Falta la línea resaltada
//+------------------------------------------------------------------+
//| Attach new object without bitmap resource                        |
//+------------------------------------------------------------------+
bool CCanvas::Attach(const long chart_id,const string objname,const int width,const int height,ENUM_COLOR_FORMAT clrfmt=COLOR_FORMAT_XRGB_NOALPHA)
  {
   if(OBJ_BITMAP_LABEL==ObjectGetInteger(chart_id,objname,OBJPROP_TYPE))
     {
      string rcname=ObjectGetString(chart_id,objname,OBJPROP_BMPFILE);
      if(StringLen(rcname)==0 && width>0 && height>0 && ArrayResize(m_pixels,width*height)>0)
        {
         ZeroMemory(m_pixels);
         if(ResourceCreate("::"+objname,m_pixels,width,height,0,0,0,clrfmt) && 
            ObjectSetString(chart_id,objname,OBJPROP_BMPFILE,"::"+objname))
           {
            m_chart_id = chart_id;
            m_width=width;
            m_height=height;
            m_objname=objname;
            m_rcname="::"+objname;
            m_format=clrfmt;
            m_objtype=OBJ_BITMAP_LABEL;
            //--- success
            return(true);
           }
        }
     }
//--- failed
   return(false);
  }
 
Oh, debería pedirle a Nikolay Semko que escriba una versión alternativa de los kanvas, con un buen antialiasing, tal vez una visión diferente, y escribir un artículo, tal vez lo haga?
 
Aleksandr Teleguz:

Hola. Por favor, ayúdenme a encontrar la causa de este error. Estoy transfiriendo un indicador de mql4 a mql5. Estoy utilizando el siguiente "shell" para las funciones de iHigh:

Como resultado, obtengo el error 4301: "Símbolo desconocido", a pesar de que se pasa una cadena devuelta por la función Symbol() como parámetro de símbolo. Este es un fragmento de código de la función que llama a iHigh

¿Quién es "yo"? ¿Cuál es su valor antes del bucle?


¿Está haciendo la llamada ResetLastError antes deiHigh?

 
Vladimir Karputov:

¿Quién es la "i"? ¿Cuál es su valor antes del bucle?


¿Hace una llamada a ResetLastError antes deiHigh?

El valor de i se repite en la función OnCalculate

for(int i=rates_total-prev_calculated; i>0 && !IsStopped(); i--)
     {
      if(i>rates_total-10) continue;


No hice la llamada ResetLastError, ahora lo hice - el código de error es el mismo. Utilizo arrays low[i], high[i] etc. en la función OnCalculate, y iHigh, iLow etc. en funciones externas.

 
Aleksandr Teleguz:

El valor de i se repite en la función OnCalculate


No llamé a ResetLastError, ahora lo hice - el código de error es el mismo. Utilizo arrays low[i], high[i] etc. en la función OnCalculate y iHigh, iLow etc. en funciones externas.

Proporcione el código MQL5 que se puede ejecutar y describa las condiciones en las que se produce el error.

 
Vladimir Karputov:

Proporcione el código MQL5 que se puede ejecutar y describa las condiciones en las que se produce el error.

Parece que tengo algo mal en mi terminal. Corrí el mismo código en el netbook en otro mt5, la misma cuenta de demostración - no hay error.

Aquí está el código en sí:

/+------------------------------------------------------------------+
//|                                                      Strelka.mq4 |
//|                                                Alexander Teleguz |
//|                                            https://investmany.ru |
//+------------------------------------------------------------------+

#property indicator_chart_window
#property indicator_buffers 12
#property indicator_plots   6

#define OP_SELL 1

int OnInit()
{
  
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   
}
//+------------------------------------------------------------------+

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[])
{
   ArraySetAsSeries(time,true);
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
   
   for(int i = rates_total-prev_calculated; i>0 && !IsStopped(); i--)
   {
      if(i>rates_total-10) continue;
      bool filtr = Filtr1(OP_SELL, i);
   }
      
   return(rates_total);
}
//+------------------------------------------------------------------+
bool Filtr1(int type, int i)
{
   ENUM_TIMEFRAMES tf = Period();
   string symbol = Symbol();
   int i1, i2=0; //индекс внешнего бара, счетчик
   for(i1=i+1; i2<6; i1++)
   {
      if(iLow(symbol, tf, i1)<=iLow(symbol, tf, i1+1)&&
         iHigh(symbol, tf, i1)>=iHigh(symbol, tf, i1+1)) //если бар внешний
      {
         break; //выход из цикла
      }
      else
      {
         i2++;
      }
   }
   return(false);
}
//+------------------------------------------------------------------+
double iHigh(string symbol, ENUM_TIMEFRAMES tf,int index)
{
   if(index < 0) return(-1);
   double Arr[1];
   if(CopyHigh(symbol,tf, index, 1, Arr)>0) 
        return(Arr[0]);
   else
   {
      Print(__FUNCTION__, GetLastError());
      return(-1);
   } 
}
//+------------------------------------------------------------------+
double iLow(string symbol, ENUM_TIMEFRAMES tf,int index)
{
   if(index < 0) return(-1);
   double Arr[1];
   if(CopyLow(symbol,tf, index, 1, Arr)>0) 
        return(Arr[0]);
   else
   {
      Print(__FUNCTION__, GetLastError());
      return(-1);
   }
}
//+------------------------------------------------------------------+
 
Aleksandr Teleguz:

Parece que tengo algo mal en mi terminal. Corrí el mismo código en el netbook en otro mt5, la misma cuenta de demostración - no hay error.

Aquí está el código en sí:

Nota: Estás escribiendo en la sección principal del foro de MQL5, aquí es donde se habla de MQL5. Para MQL4 hay una sección especial:MQL4 y MetaTrader 4. Por favor, publique su código en la sección correspondiente. Es aún mejor cuando el editor respeta a los usuarios y publica inmediatamente el código en la cabecera donde se puede ver el tipo de lenguaje.

 
Esto es MQL5.
 

¡Hola!
No puedo cambiar el marco temporal de un objeto gráfico, no sé si el terminal se está equivocando o yo.
Este es el código de comprobación

int OnStart(void)
{
        double price;
        datetime time0, time1;
        string obj_name= "test_of_line_timeframe_setting";
        ENUM_TIMEFRAMES tf1, tf2;

        // берем последнюю цену и время 
        MqlRates rates[];
        int copied=CopyRates(NULL,0,0,3,rates);
        price= rates[0].open;
        time0= rates[0].time;
        
        // рисуем линию
        ObjectCreate(0, obj_name, OBJ_HLINE, 0, time0, price);
// --- отображение на переднем плане (false) или background (true)
    ObjectSetInteger (0, obj_name, OBJPROP_BACK , false);
// --- Включить (true) или отключить (false) режим для перемещения меток с помощью мыши
    ObjectSetInteger (0, obj_name, OBJPROP_SELECTABLE , true);
    ObjectSetInteger (0, obj_name, OBJPROP_SELECTED , false);
// --- Скрыть (true) или отобразить (false) графический объект в списке объектов
    ObjectSetInteger (0, obj_name, OBJPROP_HIDDEN , false);
// --- Установите порядок приоритета для получения события щелчка мыши по диаграмме
    ObjectSetInteger (0, obj_name, OBJPROP_ZORDER , 0);

        
        // устанавливаем видимость на дневном таймфрэйме
        ObjectSetInteger(0,obj_name,OBJPROP_PERIOD,PERIOD_D1); 
        // считываем видимость 
        tf1= ObjectGetInteger(0,obj_name,OBJPROP_PERIOD);

        // устанавливаем видимость на часовом таймфрэйме
        ObjectSetInteger(0,obj_name,OBJPROP_PERIOD,PERIOD_H1); 
        // считываем видимость 
        tf2= ObjectGetInteger(0,obj_name,OBJPROP_PERIOD);

        if (tf1==tf2) Alert("таймфрейм изменить не удается");
        else Alert("таймфрейм успешно изменен");

        ObjectDelete(0,obj_name); 

        return(0);
}
 
Error de OBJ_CHART. Indicador
#property indicator_chart_window

#property indicator_buffers 0
#property indicator_plots indicator_buffers

#define  PRINT(A) Print(#A + " = " + (string)(A))

// Создаем OBJ_CHART
const string Name = __FILE__;
const bool Init = ObjectCreate(0, Name, OBJ_CHART, 0, 0, 0) && EventSetTimer(1);
const long Chart = ObjectGetInteger(0, Name, OBJPROP_CHART_ID);

void OnInit()
{  
  // Задаем свойства объекта
  ObjectSetInteger(0, Name, OBJPROP_XSIZE, 400); // Ширина
  ObjectSetInteger(0, Name, OBJPROP_YSIZE, 250); // Высота
  ChartSetInteger(Chart, CHART_SHOW, false);

  ChartGetInteger(Chart, CHART_WIDTH_IN_PIXELS); // Если закомментировать строку, то все будет работать правильно
}

void OnDeinit( const int )
{
  ObjectDelete(0, Name);
}

void OnTimer()
{
  // Считываем свойства объекта
  PRINT(ChartGetInteger(Chart, CHART_WIDTH_IN_PIXELS));  // Правильное значение - 400
  PRINT(ChartGetInteger(Chart, CHART_HEIGHT_IN_PIXELS)); // Правильное значение - 250

  EventKillTimer();
}

int OnCalculate( const int, const int, const int, const double& [] )
{  
  return(0);
}


El resultado es incorrecto

ChartGetInteger(Chart,CHART_WIDTH_IN_PIXELS) = 330
ChartGetInteger(Chart,CHART_HEIGHT_IN_PIXELS) = 226


Pero en cuanto se comenta la línea seleccionada, el indicador empieza a funcionar correctamente

ChartGetInteger(Chart,CHART_WIDTH_IN_PIXELS) = 400
ChartGetInteger(Chart,CHART_HEIGHT_IN_PIXELS) = 250


Por alguna razón, ChartGetInteger en OnInit afecta a las propiedades del objeto gráfico.