Tutte le domande dei nuovi arrivati su MQL4 e MQL5, aiuto e discussione su algoritmi e codici - pagina 1532

 

Non riesco a gestire i buffer, raccolgo le statistiche, la raccolta delle statistiche funziona correttamente e l'indicatore disegna anche tutto sul grafico (come testo sotto ogni candela), ma appena creo un buffer per riempirlo di statistiche dà errore 'CntM5Buffer' - parameter conversion not allowed Trent_flat.mq5 30 21, non posso gestire questi buffer :(


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



 

Puoi spiegare per favore qual è il trucco?

questo codice carica il terminale

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

questo codice vola.

   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:

Puoi spiegare per favore qual è il trucco?

questo codice carica il terminale

Questo codice vola.

Il primo codice non è corretto.

Prima dovete raccogliere/riempire l'array "RSI_01Buffer" e poi passarlo alla funzione per calcolare "iMAOnArray".

Nel secondo codice tutto è corretto.

 
Vitaly Muzichenko:

Il primo codice non è corretto.

Prima dovete raccogliere/riempire l'array "RSI_01Buffer" e poi passarlo alla funzione per calcolare "iMAOnArray".

Nel secondo codice tutto è corretto.

Grazie mille. È la prima volta che mi sono imbattuto in questo e sono rimasto perplesso.
 
Taras Slobodyanik:

Gli indicatori lavorano in un thread, se uno aspetta, tutti gli altri aspettano, finché il terminale si blocca.
Quando MT parte, l'inizializzazione dell'indicatore (o degli indicatori) può avvenire prima dell'inizializzazione delle variabili terminali, cioè è un gioco da ragazzi catturare un blocco.

Grazie. Ma finora non conosco altre opzioni.

 
Andrey Sokolov:

Grazie. Ma non conosco altre opzioni al momento.

E l'opzione giusta è molto semplice...

 
Artyom Trishkin:

E l'opzione giusta è molto semplice...

È corretto o poco corretto? - (Sto anche cercando di imparare a capirlo e implementarlo correttamente).

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

Sarebbe giusto o sbagliato? - (Sto anche cercando di imparare a capirlo e implementarlo correttamente).

Ho quasi imparato - apre anche una posizione

02 Bande demo

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

Potete dirmi come capire la documentazione in generale? Mi dà molto fastidio che negli esempi anche di un semplice oggetto grafico come il testo, ti buttano in faccia un esempio con un mucchio di codice e da nessuna parte scrivono quali parametri sono richiesti e quali no e per scrivere semplicemente del testo o impostare un trend o anche capire i buffer per un indicatore non capisci quali parametri minimi devono essere inseriti e devi stupidamente copiare e ***il loro codice

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

Potete dirmi come capire la documentazione in generale? Mi dà veramente fastidio che anche negli esempi di semplici oggetti grafici come il testo ti buttano in faccia un esempio con un mucchio di codice e da nessuna parte scrivono quali parametri sono obbligatori e quali no e per scrivere semplicemente del testo o impostare un trend o anche capire i buffer per un indicatore non capisci quali parametri minimi devi inserire e semplicemente copi e ***il loro codice


Almeno c'è molta documentazione ora. Articoli, Articoli, .....