Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1532

 

I can't deal with buffers, I collect statistics, statistics collection works correctly and the indicator even draws everything on the chart (as text under each candlestick), but as soon as I create a buffer for filling it with statistics it gives error 'CntM5Buffer' - parameter conversion not allowed Trent_flat.mq5 30 21, I can't deal with these 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);
  }
//+------------------------------------------------------------------+



 

Can you please explain what the trick is?

this code loads the 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);
     }

this code flies.

   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:

Can you please explain what the trick is?

this code loads the terminal

This code flies.

The first code is not correct.

First you need to collect/fill the "RSI_01Buffer" array and then pass it to the function to calculate "iMAOnArray"

In the second code everything is correct.

 
Vitaly Muzichenko:

The first code is not correct.

First you need to collect/fill the "RSI_01Buffer" array and then pass it to the function to calculate "iMAOnArray".

In the second code everything is correct.

Thank you very much. This is the first time I've come across this and I've been puzzled.
 
Taras Slobodyanik:

Indicators work in one thread, if one waits, all others wait, until the terminal hangs.
When MT starts, initialization of indicator(s) may happen before initialization of terminal variables, i.e. it's a piece of cake to catch a hang.

Thank you. But so far I don't know other options.

 
Andrey Sokolov:

Thank you. But I don't know any other options at the moment.

And the right option is very simple...

 
Artyom Trishkin:

And the right option is very simple...

I'm sorry - what if it's like this? Is it correct or not very correct? - (I'm also trying to learn how to understand and implement it correctly.)

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

I'm sorry - what if it's like this? Would that be right or wrong? - (I'm also trying to learn how to understand and implement it correctly).

I almost learned - even opens a position

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

Can you tell me how to understand the documentation in general? It really bothers me that in the examples of even a simple graphical object like text, they throw in your face an example with a bunch of code and nowhere do they write which parameters are required and which are not and in order to just write some text or set a trend or even understand the buffers for an indicator you don't understand what minimum parameters need to be entered and have to stupidly copy and ***their code

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

Can you tell me how to understand the documentation in general? It really bothers me that even in examples of simple graphical objects like text they throw in your face a sample with a bunch of code and nowhere do they write which parameters are mandatory and which are not and in order to just write some text or set a trend or even understand the buffers for an indicator you don't understand which minimum parameters you have to enter and you just copy and ***their code


At least there is a lot of documentation now. Articles, examples.....
Reason: