//+------------------------------------------------------------------+//| 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"//--- входные параметрыinputint bands_period=20; // период скользящей среднейinputint bands_shift=0; // сдвигinputdouble deviation=2.0; // кол-во стандартных отклоненийinputENUM_APPLIED_PRICE applied_price=PRICE_CLOSE; // тип цены//--- переменная для хранения хэндла индикатора iBandsint handle;
//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+intOnInit()
{
//--- создадим хэндл индикатора
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 |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
if(handle!=INVALID_HANDLE)
IndicatorRelease(handle);
//--- почистим график при удалении индикатораComment("");
}
//+------------------------------------------------------------------+//| Expert tick function |//+------------------------------------------------------------------+voidOnTick()
{
//--- индикаторные буферыdouble UpperBuffer[];
double LowerBuffer[];
double MiddleBuffer[];
//--- количество копируемых значений из индикатора iBandsint 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 Bandsdouble &upper_values[], // индикаторный буфер верхней границыdouble &lower_values[], // индикаторный буфер нижней границыint shift, // смещениеint ind_handle, // хэндл индикатора iBandsint amount // количество копируемых значений
)
{
//--- сбросим код ошибкиResetLastError();
//--- заполняем часть массива MiddleBuffer значениями из индикаторного буфера под индексом 0if(CopyBuffer(ind_handle,0,-shift,amount,base_values)<0)
{
//--- если копирование не удалось, сообщим код ошибкиPrintFormat("Не удалось скопировать данные из индикатора iBands, код ошибки %d",GetLastError());
//--- завершим с нулевым результатом - это означает, что индикатор будет считаться нерассчитаннымreturn(false);
}
//--- заполняем часть массива UpperBuffer значениями из индикаторного буфера под индексом 1if(CopyBuffer(ind_handle,1,-shift,amount,upper_values)<0)
{
//--- если копирование не удалось, сообщим код ошибкиPrintFormat("Не удалось скопировать данные из индикатора iBands, код ошибки %d",GetLastError());
//--- завершим с нулевым результатом - это означает, что индикатор будет считаться нерассчитаннымreturn(false);
}
//--- заполняем часть массива LowerBuffer значениями из индикаторного буфера под индексом 2if(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.
inputint Magic = 000;
inputdouble Lots = 0.1;
inputint TakeProfit = 100;
inputint StopLoss = 50;
inputint Slippage = 5;
double vverh,vnuz,SL,TP;
int tiket;
//+------------------------------------------------------------------+//| Expert initialization function |//+------------------------------------------------------------------+intOnInit()
{
//---/* if (Digits == 3 || Digits == 5)
{
TakeProfit *=10;
StopLoss *=10;
Slippage *=10;
}*///---return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Expert deinitialization function |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
//---
}
//+------------------------------------------------------------------+//| Expert tick function |//+------------------------------------------------------------------+voidOnTick()
{
//---
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("Ошибка модификации ордера на продажу");
} elsePrint("Ошибка открытия ордера на продажу");
}
////////////////////////////////////////////////////////////////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("Ошибка модификации ордера на покупку");
} elsePrint("Ошибка открытия ордера на покупку");
}
}
//+------------------------------------------------------------------+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);
}
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
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
I see. Thank you. Anybody else have any tips?
I learned with you, too.
Just don't be surprised when it stops workingor worksintermittently.
For what reason? Why don't you write down what's wrong?
For what reason? Why don't you tell me what's wrong?
What's with all the harassment?
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?
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?
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 correctlyHere'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?
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()
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.
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?