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

 

MQL5

No consigo que funcione. ¿Puede alguien sugerir algo?

Foro sobre trading, sistemas de trading automatizados y comprobación de estrategias

¿Puede alguien darme una pista, por favor?

Sergey Tabolin, 2019.03.07 08:14

Basado en un indicador del código base escribí un ejemplo de lo que quiero. Funciona. Pero da un error al iniciarse:

2019.03.06 21:24:26.091 my_MA_S (GBPUSD,M15)    array out of range in 'my_MA_S.mq5' (103,59)

¿Puede decirme dónde está el error?

//+------------------------------------------------------------------+
//|                                                       myMA_S.mq5 |
//|                                     Copyright 2019, Tabolin S.N. |
//|                           https://www.mql5.com/ru/users/vip.avos |
//+------------------------------------------------------------------+
#property   copyright   "Copyright 2019, Tabolin S.N."
#property   link        "https://www.mql5.com/ru/users/vip.avos"
#property   version     "1.07"
//#property   icon        "\\Images\\mi2.ico"
//----------------------------------------------------------------------------------------------
#define      GS          1.618
#define      PI          3.14159
//----------------------------------------------------------------------------------------------
#property strict
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1

#property indicator_label1  "myMA_S"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1 

//--- input parameters
input int      InpPeriodMA          = 45; // MA period
input int      InpShiftCorrection   = 9;  // Correction shift
//--- indicator buffers
double         Buffer1[];
int            handle_MA;                           // переменная для хранения хэндла индикатора HMA5
double         buffer_MA[];                         // массив для хранения значений индикатора HMA5
int            n=0;
int            ma_bars_calculated = 0; 
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
   ArraySetAsSeries(Buffer1,        true);
   ArraySetAsSeries(buffer_MA,      true);

   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,-1);

   SetIndexBuffer(0,Buffer1,INDICATOR_DATA);
//--- set shortname and change label
   string short_name="myMA_S("+
                              IntegerToString(InpPeriodMA)+","+
                              IntegerToString(InpShiftCorrection)+")";
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
   PlotIndexSetString(0,PLOT_LABEL,short_name);
//--- set accuracy
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//--- sets first bar from what index will be drawn
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,InpPeriodMA);

   handle_MA = iMA(Symbol(),0,InpPeriodMA,0,MODE_SMA,PRICE_CLOSE);
   if(handle_MA == INVALID_HANDLE)                                       // проверяем наличие хендла индикатора
   {
      Comment("Не удалось получить хендл индикатора handle_MA");         // если хендл не получен, то выводим сообщение в лог об ошибке
      Print("Не удалось получить хендл индикатора handle_MA");
      return(INIT_FAILED);                                                 // завершаем работу с ошибкой
   }

   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
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[])
  {
   
   int ma_values_to_copy; 
   int ma_calculated = BarsCalculated(handle_MA); 
   if(ma_calculated <= 0){ 
      PrintFormat("BarsCalculated() вернул %d, код ошибки %d",ma_calculated,GetLastError()); 
      return(0); 
     }  
   if(prev_calculated == 0 || ma_calculated != ma_bars_calculated || rates_total > prev_calculated + 1){ 
      if(ma_calculated > rates_total) ma_values_to_copy = rates_total; 
      else ma_values_to_copy = ma_calculated; 
     } else { 
      ma_values_to_copy = (rates_total - prev_calculated) + 1; 
     } 
     
   if(CopyBuffer(handle_MA,0,0,ma_values_to_copy,buffer_MA) < 0 ) // копируем данные из индикаторного массива в массив buffer_HMA5
   {                                                                                // если не скопировалось
      Print("Не удалось скопировать данные из индикаторного буфера в buffer_MA");   // то выводим сообщение об ошибке
      return(0);                                                                    // и выходим из функции
   }

   for(int i = 0; i < ma_values_to_copy; i++)
     {
      Buffer1[i]  = buffer_MA[i]+(buffer_MA[i+1]-buffer_MA[i+InpShiftCorrection])/(InpShiftCorrection/GS);//1.314;
     }
   
   return(rates_total);
  }
//+------------------------------------------------------------------+

¿Qué es lo que está mal?
Archivos adjuntos:
my_MA_S.mq5  10 kb
 
Сергей Таболин:

MQL5

No consigo que funcione. ¿Puede alguien darme una pista?

¿Qué ocurre?
Dos buffers, pero #property especifica uno
 
Artyom Trishkin:
Dos buffers y la #propiedad especifica uno

Gracias por el consejo...

Pero nada ha cambiado. Soy un total de menos en los indicadores (((

#property strict
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   1

#property indicator_label1  "myMA_S"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1 

//--- input parameters
input int      InpPeriodMA          = 45; // MA period
input int      InpShiftCorrection   = 9;  // Correction shift
//--- indicator buffers
double         Buffer1[];
int            handle_MA;                           // переменная для хранения хэндла индикатора HMA5
double         buffer_MA[];                         // массив для хранения значений индикатора HMA5
int            n=0;
int            ma_bars_calculated = 0; 
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
   ArraySetAsSeries(Buffer1,        true);
   ArraySetAsSeries(buffer_MA,      true);

   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,-1);
   PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,-1);

   SetIndexBuffer(0,Buffer1,INDICATOR_DATA);
   SetIndexBuffer(1,buffer_MA,INDICATOR_CALCULATIONS);
 
Сергей Таболин:

Gracias por el consejo...

Pero nada ha cambiado. Soy un total de menos en los indicadores (((

No puedo decirlo desde un teléfono móvil
 
Сергей Таболин:

Gracias por el consejo...

Pero nada ha cambiado. Soy un total de menos en los indicadores ((

No he mirado bien el código y no está claro en qué línea está el error, pero como si el error no estuviera aquí.

Intenta reducir el límite

for(int i = 0; i < ma_values_to_copy-5; i++)
 
Vitaly Muzichenko:

No he mirado bien el código y no está claro en qué línea está el error, pero no es que el error esté aquí.

Intenta reducir el límite

El error está exactamente en este bucle.

   for(int i = 0; i < ma_values_to_copy; i++)
     {
      Buffer1[i]  = buffer_MA[i]+(buffer_MA[i+1]-buffer_MA[i+InpShiftCorrection])/(InpShiftCorrection/GS);// ошибка тут
     }

Pero su sugerencia me ha llevado a hacer un pequeño cambio:

   for(int i = 0; i < ma_values_to_copy-InpShiftCorrection; i++)
     {
      Buffer1[i]  = buffer_MA[i]+(buffer_MA[i+1]-buffer_MA[i+InpShiftCorrection])/(InpShiftCorrection/GS);//1.314;
     }

El error ha desaparecido. Gracias )))

 
He descargado mt5 para mi cuenta de trading. Soy un principiante, ¿dónde ir y dónde pagar por el comercio real?
 
Раиль Алеев:
He descargado mt5. para mi cuenta de trading. ¿Me pueden decir dónde y cómo pagar por el comercio real? Soy un novato.

Enciende el ordenador. Arranca tu navegador. En la barra de búsqueda escriba las palabras "abrir una cuenta de MetaTrader 5".

 
¿Tiene CodeBase un EA con la función "una operación por barra" (excluyendo el EA "en la apertura de la barra")?
 

¿Ha funcionado esto alguna vez, o no?

¿Cómo puedo hacer que cuando se cambie un color en los parámetros de entrada, este color esté en"indicator_color1"? Ahora mismo, no importa cómo lo cambies, es el original

#property indicator_type1   DRAW_LINE
#property indicator_color1  clrAqua


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[])
  {
   Comment( indicator_color1 ); // постоянно clrAqua

   return(rates_total);
  }