Toute question des nouveaux arrivants sur MQL4 et MQL5, aide et discussion sur les algorithmes et les codes. - page 1532

 

Je n'arrive pas à gérer les tampons, je collecte des statistiques, la collecte des statistiques fonctionne correctement et l'indicateur dessine même tout sur le graphique (en tant que texte sous chaque chandelier), mais dès que je crée un tampon pour le remplir de statistiques, il donne l'erreur 'CntM5Buffer' - parameter conversion not allowed Trent_flat.mq5 30 21, je ne peux pas gérer ces tampons :(


//+------------------------------------------------------------------+
//|                                                   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);
  }
//+------------------------------------------------------------------+



 

Pouvez-vous m'expliquer en quoi consiste cette astuce ?

ce code charge le 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);
     }

ce code s'envole.

   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:

Pouvez-vous m'expliquer en quoi consiste cette astuce ?

ce code charge le terminal

Ce code vole.

Le premier code n'est pas correct.

Tout d'abord, vous devez collecter/remplir le tableau "RSI_01Buffer" et ensuite le passer à la fonction pour calculer "iMAOnArray".

Dans le second code, tout est correct.

 
Vitaly Muzichenko:

Le premier code n'est pas correct.

Tout d'abord, vous devez collecter/remplir le tableau "RSI_01Buffer" et ensuite le passer à la fonction pour calculer "iMAOnArray".

Dans le second code, tout est correct.

Merci beaucoup. C'est la première fois que je vois cela et je suis perplexe.
 
Taras Slobodyanik:

Les indicateurs fonctionnent en un seul fil, si l'un d'eux attend, tous les autres attendent, jusqu'à ce que le terminal se bloque.
Lorsque la MT démarre, l'initialisation du ou des indicateurs peut avoir lieu avant l'initialisation des variables terminales, c'est-à-dire qu'il est très facile d'attraper un hang.

Merci. Mais jusqu'à présent, je ne connais pas d'autres options.

 
Andrey Sokolov:

Merci. Mais je ne connais pas d'autres options pour le moment.

Et la bonne option est très simple...

 
Artyom Trishkin:

Et la bonne option est très simple...

Je suis désolé - et si c'est comme ça ? C'est correct ou pas très correct ? - (J'essaie également d'apprendre à le comprendre et à l'appliquer correctement).

//+------------------------------------------------------------------+
//|                                                  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:

Je suis désolé - et si c'était comme ça ? Ce serait bien ou mal ? - (J'essaie également d'apprendre à le comprendre et à le mettre en œuvre correctement).

J'ai presque appris - même ouvre une position

02 Demo_iBandes

//+------------------------------------------------------------------+
//|                                                  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();
//---
  }
//+------------------------------------------------------------------+
 

Pouvez-vous me dire comment comprendre la documentation en général ? Cela me dérange vraiment que dans les exemples, même pour un simple objet graphique comme le texte, ils vous jettent à la figure un exemple avec un tas de code et nulle part ils n'écrivent quels paramètres sont nécessaires et lesquels ne le sont pas et pour écrire simplement un texte ou définir une tendance ou même comprendre les tampons d'un indicateur, vous ne comprenez pas quels sont les paramètres minimums que vous devez entrer et devez copier *** votre code.

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

Pouvez-vous me dire comment comprendre la documentation en général ? Cela me dérange vraiment que même dans les exemples d'objets graphiques simples comme le texte, ils vous jettent à la figure un échantillon avec un tas de code et nulle part ils n'écrivent quels paramètres sont obligatoires et lesquels ne le sont pas et pour écrire simplement un texte ou définir une tendance ou même comprendre les tampons d'un indicateur, vous ne comprenez pas quels sont les paramètres minimums que vous devez entrer et vous vous contentez de copier et ***leur code.


Au moins, il y a maintenant beaucoup de documentation. Articles, exemples.....
Raison: