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

 
Andrey Sokolov:

I see. Thank you. Anybody else have any tips?

I learned with you, too.

MiddleBuffer

//+------------------------------------------------------------------+
//|                                                  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()
  {
//--- индикаторные буферы
   double         UpperBuffer[];
   double         LowerBuffer[];
   double         MiddleBuffer[];
//--- количество копируемых значений из индикатора iBands
   int values_to_copy=2;
//--- если FillArraysFromBuffer вернула false, значит данные не готовы - завершаем работу
   if(!FillArraysFromBuffers(MiddleBuffer,UpperBuffer,LowerBuffer,bands_shift,handle,values_to_copy))
      return;
//--- сформируем сообщение
   Print("MiddleBuffer =",MiddleBuffer[0], "UpperBuffer =",UpperBuffer[0], "LowerBuffer =",LowerBuffer[0], "values_to_copy =",values_to_copy);
  }
//+------------------------------------------------------------------+
//| Заполняем индикаторные буферы из индикатора iBands               |
//+------------------------------------------------------------------+
bool FillArraysFromBuffers(double &base_values[],     // индикаторный буфер средней линии Bollinger Bands
                           double &upper_values[],    // индикаторный буфер верхней границы
                           double &lower_values[],    // индикаторный буфер нижней границы
                           int shift,                 // смещение
                           int ind_handle,            // хэндл индикатора iBands
                           int amount                 // количество копируемых значений
                          )
  {
//--- сбросим код ошибки
   ResetLastError();
//--- заполняем часть массива MiddleBuffer значениями из индикаторного буфера под индексом 0
   if(CopyBuffer(ind_handle,0,-shift,amount,base_values)<0)
     {
      //--- если копирование не удалось, сообщим код ошибки
      PrintFormat("Не удалось скопировать данные из индикатора iBands, код ошибки %d",GetLastError());
      //--- завершим с нулевым результатом - это означает, что индикатор будет считаться нерассчитанным
      return(false);
     }
//--- заполняем часть массива UpperBuffer значениями из индикаторного буфера под индексом 1
   if(CopyBuffer(ind_handle,1,-shift,amount,upper_values)<0)
     {
      //--- если копирование не удалось, сообщим код ошибки
      PrintFormat("Не удалось скопировать данные из индикатора iBands, код ошибки %d",GetLastError());
      //--- завершим с нулевым результатом - это означает, что индикатор будет считаться нерассчитанным
      return(false);
     }
//--- заполняем часть массива LowerBuffer значениями из индикаторного буфера под индексом 2
   if(CopyBuffer(ind_handle,2,-shift,amount,lower_values)<0)
     {
      //--- если копирование не удалось, сообщим код ошибки
      PrintFormat("Не удалось скопировать данные из индикатора iBands, код ошибки %d",GetLastError());
      //--- завершим с нулевым результатом - это означает, что индикатор будет считаться нерассчитанным
      return(false);
     }
//--- все получилось
   return(true);
  }
//+------------------------------------------------------------------+
 
Guys, who is not busy and can look. sketched out an EA on yesterday's indicator but something is not working right. It seems to open trades not based on signals. I've tried to add close orders on the opposite signal but deals are closed then not. I have a clue if there is an error in the condition.
input int Magic = 000;
input double Lots = 0.1;
input int TakeProfit = 100;
input int StopLoss = 50;
input int Slippage = 5;

double vverh,vnuz,SL,TP;
int tiket;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
  /* if (Digits == 3 || Digits == 5)
   {
      TakeProfit *=10;
      StopLoss *=10;
      Slippage *=10;
   }*/
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
           
     
      vverh = iCustom(NULL,0,"777",0,1); // стрелка вверх
      vnuz = iCustom(NULL,0,"777",1,1); // стрелка вниз
      
     //-----------------------------------------------------------
     if (CountSell() == 0 && vnuz >0)
      {
      tiket = OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"",Magic,0, Red);
      if (tiket>0)
         {
         SL=NormalizeDouble(Bid+StopLoss*Point,Digits);
         TP=NormalizeDouble(Bid-TakeProfit*Point,Digits);
         if (OrderSelect(tiket, SELECT_BY_TICKET))
            if (!OrderModify(tiket,OrderOpenPrice(),SL,TP,0))
               Print("Ошибка модификации ордера на продажу");
         } else Print("Ошибка открытия ордера на продажу");
      }
      
      ////////////////////////////////////////////////////////////////
    if (CountBuy() == 0 && vverh >0)
      {
      tiket = OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"",Magic,0,Blue);
      if (tiket>0)
         {
         TP=NormalizeDouble(Ask+TakeProfit*Point,Digits);
         SL=NormalizeDouble(Ask-StopLoss*Point,Digits);
         if (OrderSelect(tiket, SELECT_BY_TICKET))
           if (!OrderModify(tiket,OrderOpenPrice(),SL,TP,0))
           Print("Ошибка модификации ордера на покупку");
         } else Print("Ошибка открытия ордера на покупку");
      }  
     
      
  }
//+------------------------------------------------------------------+
int CountSell()
{
   int count =0;
   for (int trade = OrdersTotal()-1; trade>=0; trade--)
   {
   if (OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))
      {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType() == OP_SELL)
         count++;
      }
   }
   return(count);
}
//+------------------------------------------------------------------+
int CountBuy()
{
   int count =0;
   for (int trade = OrdersTotal()-1; trade>=0; trade--)
   {
   if (OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))
      {
      if (OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==OP_BUY)
         count++;
      }
   }
   return(count);
}
Files:
 
PapaYozh:

Just don't be surprised when it stops workingor worksintermittently.

For what reason? Why don't you write down what's wrong?

 
Andrey Sokolov:

For what reason? Why don't you tell me what's wrong?

What's with all the harassment?

 
PapaYozh:

What's with the hit-and-run?

I see.

Can anyone else tell me what's wrong with it, and the reason it stops working, if indeed something is wrong?

 
Andrey Sokolov:

I see.

Maybe someone else can tell me what's wrong there, and what's the reason it stops working if there's really something wrong?

Here's the answer

Forum on trading, automated trading systems and strategy testing

Any questions from newbies on MQL4 and MQL5, help and discussion of algorithms and codes

Igor Makanu, 2021.07.05 14:16.

because the indicator is not yet calculated.

https://www.mql5.com/ru/docs/series/barscalculated


the OnInit() section is not the best place to get the terminal environment, I think it works logically and correctly

 
Alexey Viktorov:
Here's the answer.

Thank you.

I need it to do the history calculations immediately on startup. I'm doing it in the inite because I need it that way.

I added a pause in the init, before calculations. If so, are there still some pitfalls?

 
Andrey Sokolov:

It is necessary to make calculations on the history at the startup. I do it in the inite because I need it that way.

I added a pause in the inite, before calculations. If so, there are still some pitfalls?

It is easier and more reliable to put the first start flag in OnTick()

 
jarikn:
Guys, who is not busy and can look. sketched out an EA on yesterday's indicator but something is not working right. It seems to open trades not based on signals. I've tried to add close orders on the opposite signal but deals are closed then not. I think I have a really good feedback.
Most likely, the indicator draws ... and look for errors in the log
 
Andrey Sokolov:

For what reason? Why don't you write what's wrong?

Because the developers have written that OnInit() is intended for initialization, not for something else

What will happen - you made a pause to get the indicator values in OnInit() - what will happen if the user switches the TF at the same time?

SZZY: And how would your code behave if you run an EA, then close the terminal and reopen the terminal with an already running EA?

Reason: