Cualquier pregunta de los recién llegados sobre MQL4 y MQL5, ayuda y discusión sobre algoritmos y códigos - página 1532

 

No puedo lidiar con los buffers, recolecto estadísticas, la recolección de estadísticas funciona correctamente y el indicador incluso dibuja todo en el gráfico (como texto debajo de cada vela), pero tan pronto como creo un buffer para llenarlo con estadísticas da error 'CntM5Buffer' - conversión de parámetros no permitida Trent_flat.mq5 30 21, no puedo lidiar con estos buffers :(


//+------------------------------------------------------------------+
//|                                                   Trent_flat.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 1

#include  <statistic_func.mqh>
#include <obj_text.mqh>


int CntM5Buffer[];


ENUM_TIMEFRAMES TF = PERIOD_M5;
int bars_on_history = 50;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,CntM5Buffer,INDICATOR_CALCULATIONS);
//--- установим индексацию для буфера как в таймсерии
   ArraySetAsSeries(CntM5Buffer,true);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| 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[])
  {

   int start = 1;
   Comment("RATES_TOTAL = ", rates_total, "\n PREV_CALCULATED = ", prev_calculated, "\nR - P = ", rates_total-prev_calculated);
   if(rates_total - prev_calculated >0)
     {

      int total_bars;
      if(rates_total-prev_calculated > bars_on_history)
        {
         total_bars = bars_on_history;
        }
      else
        {
         total_bars = rates_total - prev_calculated;
        }

      Get_TF_statistic(TF,total_bars,CntM5Buffer);

     }

   return(rates_total);
  }
//+------------------------------------------------------------------+



 

¿Puede explicar en qué consiste el truco?

este código carga el terminal

   for(int i=limit;i>=0;i--)
     {
      RSI_01Buffer[i]=iRSI(NULL,0,RSI_Period,RSI_Price,i);
      RSI_02Buffer[i]=iMAOnArray(RSI_01Buffer,0,RSI_Period,0,MODE_SMA,i);
     }

este código vuela.

   for(int i=limit;i>=0;i--)
      RSI_01Buffer[i]=iRSI(NULL,0,RSI_Period,RSI_Price,i);
   for(int i=limit;i>=0;i--)
     {
      RSI_02Buffer[i]=iMAOnArray(RSI_01Buffer,0,RSI_Period,0,MODE_SMA,i);
     }
 
MakarFX:

¿Puede explicar en qué consiste el truco?

este código carga el terminal

Este código vuela.

El primer código no es correcto.

Primero hay que recoger/llenar el array "RSI_01Buffer" y luego pasarlo a la función para calcular "iMAOnArray"

En el segundo código todo es correcto.

 
Vitaly Muzichenko:

El primer código no es correcto.

Primero hay que recoger/llenar el array "RSI_01Buffer" y luego pasarlo a la función para calcular "iMAOnArray".

En el segundo código todo es correcto.

Muchas gracias. Es la primera vez que me encuentro con esto y me he quedado perplejo.
 
Taras Slobodyanik:

Los indicadores trabajan en un hilo, si uno espera, todos los demás esperan, hasta que el terminal se cuelga.
Cuando se inicia la MT, la inicialización del indicador(es) puede ocurrir antes de la inicialización de las variables terminales, es decir, es pan comido pillar un cuelgue.

Gracias. Pero hasta ahora no conozco otras opciones.

 
Andrey Sokolov:

Gracias. Pero no conozco ninguna otra opción por el momento.

Y la opción correcta es muy sencilla...

 
Artyom Trishkin:

Y la opción correcta es muy sencilla...

Lo siento, ¿y si es así? ¿Es correcto o no es muy correcto? - (También estoy intentando aprender a entenderlo y aplicarlo correctamente).

//+------------------------------------------------------------------+
//|                                                  Demo_iBands.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

//--- входные параметры
input int                  bands_period=20;           // период скользящей средней
input int                  bands_shift=0;             // сдвиг
input double               deviation=2.0;             // кол-во стандартных отклонений
input ENUM_APPLIED_PRICE   applied_price=PRICE_CLOSE; // тип цены
//--- переменная для хранения хэндла индикатора iBands
int    handle;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- создадим хэндл индикатора
   handle=iBands(_Symbol,_Period,bands_period,bands_shift,deviation,applied_price);
//--- если не удалось создать хэндл
   if(handle==INVALID_HANDLE)
     {
      //--- сообщим о неудаче и выведем номер ошибки
      PrintFormat("Не удалось создать хэндл индикатора iBands для пары %s/%s, код ошибки %d",
                  _Symbol,
                  EnumToString(_Period),
                  GetLastError());
      //--- работа индикатора завершается досрочно
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   if(handle!=INVALID_HANDLE)
      IndicatorRelease(handle);
//--- почистим график при удалении индикатора
   Comment("");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- индикаторные буферы
//--- get current Bands
   double         UpperBuffer[];
   double         LowerBuffer[];
   double         MiddleBuffer[];
   if(CopyBuffer(handle,BASE_LINE,-bands_shift,1,MiddleBuffer)!=1||
      CopyBuffer(handle,UPPER_BAND,-bands_shift,1,UpperBuffer)!=1||
      CopyBuffer(handle,LOWER_BAND,-bands_shift,1,LowerBuffer)!=1)
     {
      Print("CopyBuffer from Bands failed, no data");
      return;
     }
//--- сформируем сообщение
   Print("MiddleBuffer =",MiddleBuffer[0], "UpperBuffer =",UpperBuffer[0], "LowerBuffer =",LowerBuffer[0]);
  }
//+------------------------------------------------------------------+
 
SanAlex:

Lo siento, ¿y si es así? ¿Estaría bien o mal? - (También estoy intentando aprender a entenderlo y aplicarlo correctamente).

Casi he aprendido - incluso abre una posición

02 Demo_iBands

//+------------------------------------------------------------------+
//|                                                  Demo_iBands.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

#define    BAND_MAGIC 1234501

#include <Trade\Trade.mqh>
CTrade ExtTrade;
input group              "---- Lots Parameters ----"
input double             InpLots         = 0.1;         // Lots
input group              "---- Bands Parameters ----"
input int                bands_period    = 20;          // период скользящей средней
input int                bands_shift     = 0;           // сдвиг
input double             bands_deviation = 2.0;         // кол-во стандартных отклонений
input ENUM_APPLIED_PRICE applied_price   = PRICE_CLOSE; // тип цены
//--- переменная для хранения хэндла индикатора iBands
bool   ExtHedging=false;
int    handle=0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- prepare trade class to control positions if hedging mode is active
   ExtHedging=((ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE)==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING);
   ExtTrade.SetExpertMagicNumber(BAND_MAGIC);
   ExtTrade.SetMarginMode();
   ExtTrade.SetTypeFillingBySymbol(Symbol());
//--- создадим хэндл индикатора
   handle=iBands(_Symbol,_Period,bands_period,bands_shift,bands_deviation,applied_price);
//--- если не удалось создать хэндл
   if(handle==INVALID_HANDLE)
     {
      //--- сообщим о неудаче и выведем номер ошибки
      PrintFormat("Не удалось создать хэндл индикатора iBands для пары %s/%s, код ошибки %d",
                  _Symbol,
                  EnumToString(_Period),
                  GetLastError());
      //--- работа индикатора завершается досрочно
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   if(handle!=INVALID_HANDLE)
      IndicatorRelease(handle);
//--- почистим график при удалении индикатора
   Comment("");
  }
//+------------------------------------------------------------------+
//| Check for open position conditions                               |
//+------------------------------------------------------------------+
void CheckForOpen(void)
  {
   MqlRates rt[2];
//--- go trading only for first ticks of new bar
   if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
     {
      Print("CopyRates of ",_Symbol," failed, no history");
      return;
     }
   if(rt[1].tick_volume>1)
      return;
//--- get current Bands
   double MiddleBuffer[],UpperBuffer[],LowerBuffer[];
   if(CopyBuffer(handle,BASE_LINE,-bands_shift,1,MiddleBuffer)!=1||
      CopyBuffer(handle,UPPER_BAND,-bands_shift,1,UpperBuffer)!=1||
      CopyBuffer(handle,LOWER_BAND,-bands_shift,1,LowerBuffer)!=1)
     {
      Print("CopyBuffer from Bands failed, no data");
      return;
     }
//--- check signals
   ENUM_ORDER_TYPE signal=WRONG_VALUE;
   if(((rt[0].open>MiddleBuffer[0] && rt[0].close<MiddleBuffer[0])||
       (rt[0].open>UpperBuffer[0] && rt[0].close<UpperBuffer[0])||
       (rt[0].open>LowerBuffer[0] && rt[0].close<LowerBuffer[0])))
      signal=ORDER_TYPE_SELL;    // sell conditions
   else
     {
      if(((rt[0].open<MiddleBuffer[0] && rt[0].close>MiddleBuffer[0])||
          (rt[0].open<UpperBuffer[0] && rt[0].close>UpperBuffer[0])||
          (rt[0].open<LowerBuffer[0] && rt[0].close>LowerBuffer[0])))
         signal=ORDER_TYPE_BUY;  // buy conditions
     }
//--- additional checking
   if(signal!=WRONG_VALUE)
     {
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
         ExtTrade.PositionOpen(_Symbol,signal,InpLots,
                               SymbolInfoDouble(_Symbol,signal==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK),
                               0,0);
     }
  }
//+------------------------------------------------------------------+
//| Check for close position conditions                              |
//+------------------------------------------------------------------+
void CheckForClose(void)
  {
   MqlRates rt[2];
//--- go trading only for first ticks of new bar
   if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
     {
      Print("CopyRates of ",_Symbol," failed, no history");
      return;
     }
   if(rt[1].tick_volume>1)
      return;
//--- get current Bands
   double MiddleBuffer[],UpperBuffer[],LowerBuffer[];
   if(CopyBuffer(handle,BASE_LINE,-bands_shift,1,MiddleBuffer)!=1||
      CopyBuffer(handle,UPPER_BAND,-bands_shift,1,UpperBuffer)!=1||
      CopyBuffer(handle,LOWER_BAND,-bands_shift,1,LowerBuffer)!=1)
     {
      Print("CopyBuffer from Bands failed, no data");
      return;
     }
//--- positions already selected before
   bool signal=false;
   long type=PositionGetInteger(POSITION_TYPE);
   if(((type==(long)POSITION_TYPE_BUY && rt[0].open>MiddleBuffer[0] && rt[0].close<MiddleBuffer[0])||
       (type==(long)POSITION_TYPE_BUY && rt[0].open>UpperBuffer[0] && rt[0].close<UpperBuffer[0])||
       (type==(long)POSITION_TYPE_BUY && rt[0].open>LowerBuffer[0] && rt[0].close<LowerBuffer[0])))
      signal=true;
   if(((type==(long)POSITION_TYPE_SELL && rt[0].open<MiddleBuffer[0] && rt[0].close>MiddleBuffer[0])||
       (type==(long)POSITION_TYPE_SELL && rt[0].open<UpperBuffer[0] && rt[0].close>UpperBuffer[0])||
       (type==(long)POSITION_TYPE_SELL && rt[0].open<LowerBuffer[0] && rt[0].close>LowerBuffer[0])))
      signal=true;
//--- additional checking
   if(signal)
     {
      if(TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
         ExtTrade.PositionClose(_Symbol,3);
     }
//---
  }
//+------------------------------------------------------------------+
//| Position select depending on netting or hedging                  |
//+------------------------------------------------------------------+
bool SelectPosition()
  {
   bool res=false;
//--- check position in Hedging mode
   if(ExtHedging)
     {
      uint total=PositionsTotal();
      for(uint i=0; i<total; i++)
        {
         string position_symbol=PositionGetSymbol(i);
         if(_Symbol==position_symbol && BAND_MAGIC==PositionGetInteger(POSITION_MAGIC))
           {
            res=true;
            break;
           }
        }
     }
//--- check position in Netting mode
   else
     {
      if(!PositionSelect(_Symbol))
         return(false);
      else
         return(PositionGetInteger(POSITION_MAGIC)==BAND_MAGIC); //---check Magic number
     }
//--- result for Hedging mode
   return(res);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(void)
  {
//---
   if(SelectPosition())
      CheckForClose();
   else
      CheckForOpen();
//---
  }
//+------------------------------------------------------------------+
 

¿Puede decirme cómo entender la documentación en general? Realmente me molesta que en los ejemplos de incluso un simple objeto gráfico como el texto, te tiran a la cara un ejemplo con un montón de código y en ninguna parte escriben qué parámetros son necesarios y cuáles no y para sólo escribir un texto o establecer una tendencia o incluso entender los buffers para un indicador no entiendes qué parámetros mínimos hay que introducir y tienes que copiar estúpidamente y ***su código

 
Алексей КоКоКо:

¿Puede decirme cómo entender la documentación en general? Me molesta mucho que incluso en los ejemplos de objetos gráficos sencillos como el texto te tiran a la cara un ejemplo con un montón de código y en ningún sitio escriben qué parámetros son obligatorios y cuáles no y para escribir simplemente un texto o establecer una tendencia o incluso entender los buffers de un indicador no entiendes qué parámetros mínimos tienes que introducir y te limitas a copiar y ***su código


Al menos ahora hay mucha documentación. Artículos, ejemplos.....
Razón de la queja: