If you change a global variable in a function, it will change. But this is a dangerous way of programming, because in the code, as it grows, there will be unobvious assignments in different functions of the program.
There's a main function in the program, that's where you do the global variable assignment. And in other functions, do it this way:
Or like this:
I agree that in voluminous code, it's easy to miss the point of an unwanted variable change (X). From this point of view, calling the main function each time you need to find out what's wrong with X is correct. But here is the question. If the main function calculates and outputs several different values (X, Y, Z) and is quite large, while X is used repeatedly in the course of the program, won't this approach excessively consume computing power? I.e. in order to get X, we repeatedly run a whole block where we also recalculate Y and Z in addition to X , which, say, was needed only once. Therefore, if the algorithm contains sequential change and overwrite of X from one function to another, it may be more complicated for a programmer (requires more attention and checks for errors), but then it is easier for the machine.
screwing something on isn't respecting yourself or others...
Take the trouble to redesign to modern interfaces
So show me how it must look like on modern interfaces. The man apparently has never coded (otherwise he would have figured out the Alert without us). He just found the code somewhere, brought it here and wants an alert.
But here is the question. If the main function calculates and outputs several different values (X, Y, Z) and is quite large, and X is used many times along the way
int X=0;
void OnTick()
{
if(УсловиеДляРедкогоРасчёта) X=ТяжёлыйРедкийРасчёт();
ЛекийПостоянныйРасчёт(X);
}
Show us how it should look like on modern interfaces. It seems that the man has never programmed (otherwise he would have figured out the alert without us). He just found the code somewhere, brought it here and wants an alert.
Where do you get such "indicators" and "advisors" from? but if you melt down, the source won't run out...
there's no such thing on the site for a long time.
If the maker of these indicators has not succeeded, the market has moved to the new MQL5(4). They will help and explain things there, and it will be useful to everyone.
Please advise mql5 on how to pass to the function open,close and TD from OnCalculate not through the function parameters, so that I don't have to write each time the opening and closing of candlesticks into parameters when calling the function
jarikn : Guys. help to fasten the alert to the indicator.
screwed - I do not remember the code from the code base and the author - to whom I need to say thanks! - if he recognizes his code - I say thank you to him!
and here is your indicator - I did it - only on MT5 with Alert.
//+------------------------------------------------------------------+//| jarikn.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_buffers2//---- использовано всего два графических построения#property indicator_plots2//+----------------------------------------------+//| Параметры отрисовки бычьго индикатора |//+----------------------------------------------+//---- отрисовка индикатора 1 в виде символа#property indicator_type1DRAW_ARROW//---- в качестве цвета бычей линии индикатора использован розовый цвет#property indicator_color1 Lime
//---- толщина линии индикатора 1 равна 4#property indicator_width12//---- отображение метки медвежьей линии индикатора#property indicator_label1"jarikn Buy"//+----------------------------------------------+//| Параметры отрисовки медвежьего индикатора |//+----------------------------------------------+//---- отрисовка индикатора 2 в виде символа#property indicator_type2DRAW_ARROW//---- в качестве цвета медвежьей линии индикатора использован зеленый цвет#property indicator_color2 Magenta
//---- толщина линии индикатора 2 равна 4#property indicator_width22//---- отображение метки бычьей линии индикатора#property indicator_label2"jarikn Sell"//+----------------------------------------------------+//| перечисление для вариантов транслируемых сигналов |//+----------------------------------------------------+enum ENUM_SIGNAL_MODE
{
MODE_SIGNAL, //Сигналы пробоя
MODE_TREND //Сигналы пробоя и тренда
};
//+----------------------------------------------+//| Входные параметры индикатора |//+----------------------------------------------+inputint ShiftArrow = 0 ;
input group "---- Входные переменные для алертов ----"input ENUM_SIGNAL_MODE SignMode=MODE_SIGNAL; //Вариант подачи сигналаinputuint NumberofBar= 0 ; //Номер бара для подачи сигналаinputbool SoundON= true ; //Разрешение алертаinputuint NumberofAlerts= 1 ; //Количество алертовinputbool EMailON= false ; //Разрешение почтовой отправки сигналаinputbool PushON= false ; //Разрешение отправки сигнала на мобильный//--- indicator buffers//---- объявление динамических массивов, которые будут в//---- дальнейшем использованы в качестве индикаторных буферовdouble UpArrow[];
double DownArrow[];
int StartBars;
//+------------------------------------------------------------------+//| Custom indicator initialization function |//+------------------------------------------------------------------+intOnInit ()
{
//--- indicator buffers mapping
StartBars= 5 ;
//---- превращение динамического массива в индикаторный буферSetIndexBuffer ( 0 ,UpArrow, INDICATOR_DATA );
//---- осуществление сдвига начала отсчета отрисовки индикатора 1PlotIndexSetInteger ( 0 , PLOT_DRAW_BEGIN ,StartBars);
//--- создание метки для отображения в DataWindowPlotIndexSetString ( 0 , PLOT_LABEL , "jarikn Buy" );
//---- символ для индикатораPlotIndexSetInteger ( 0 , PLOT_ARROW , 108 );
//---- индексация элементов в буфере как в таймсерииArraySetAsSeries (UpArrow, true );
//--- line shifts when drawingPlotIndexSetInteger ( 0 , PLOT_SHIFT ,ShiftArrow);
//---- превращение динамического массива в индикаторный буферSetIndexBuffer ( 1 ,DownArrow, INDICATOR_DATA );
//---- осуществление сдвига начала отсчета отрисовки индикатора 2PlotIndexSetInteger ( 1 , PLOT_DRAW_BEGIN ,StartBars);
//--- создание метки для отображения в DataWindowPlotIndexSetString ( 1 , PLOT_LABEL , "jarikn Sell" );
//---- символ для индикатораPlotIndexSetInteger ( 1 , PLOT_ARROW , 108 );
//---- индексация элементов в буфере как в таймсерииArraySetAsSeries (DownArrow, true );
//--- line shifts when drawingPlotIndexSetInteger ( 1 , PLOT_SHIFT ,ShiftArrow);
//---- установка формата точности отображения индикатораIndicatorSetInteger ( INDICATOR_DIGITS , _Digits );
//---- имя для окон данных и лэйба для субъоконstring short_name= "jarikn" ;
IndicatorSetString ( INDICATOR_SHORTNAME ,short_name);
//---return ( INIT_SUCCEEDED );
}
//+------------------------------------------------------------------+//| Custom indicator iteration function |//+------------------------------------------------------------------+intOnCalculate ( constint rates_total,
constint prev_calculated,
constdatetime &time[],
constdouble &Open[],
constdouble &High[],
constdouble &Low[],
constdouble &Close[],
constlong &tick_volume[],
constlong &volume[],
constint &spread[])
{
//---- проверка количества баров на достаточность для расчетаif (rates_total<StartBars)
return ( 0 );
int limit,i;
//---- расчет стартового номера first для цикла пересчета баровif (prev_calculated>rates_total || prev_calculated<= 0 ) // проверка на первый старт расчета индикатора
limit=rates_total-StartBars; // стартовый номер для расчета всех баровelse
limit=rates_total-prev_calculated; // стартовый номер для расчета новых баров//---- индексация элементов в массивах как в таймсерияхArraySetAsSeries (Open, true );
ArraySetAsSeries (High, true );
ArraySetAsSeries (Low, true );
ArraySetAsSeries (Close, true );
//----for (i = 0 ; i <= limit; i++)
{
DownArrow[i] = 0 ;
UpArrow[i] = 0 ;
if (High[i+ 2 ]>High[i+ 1 ] && Low[i+ 2 ]>Low[i+ 1 ] && High[i+ 2 ]>High[i+ 3 ] && Low[i+ 2 ]>Low[i+ 3 ])
if (Open[i+ 1 ]>Close[i+ 1 ] && Close[i+ 2 ] > Close[i+ 1 ])
{
if (Open[i+ 2 ]>Close[i+ 2 ])
DownArrow[i] = High[i+ 2 ] + 0.0003 ; //Low[i+2] + (High[i+2]-Low[i+2]);
}
if (High[i+ 2 ]<High[i+ 1 ] && Low[i+ 2 ]<Low[i+ 1 ] && High[i+ 2 ]<High[i+ 3 ] && Low[i+ 2 ]<Low[i+ 3 ])
if (Open[i+ 1 ]<Close[i+ 1 ] && Close[i+ 2 ] < Close[i+ 1 ])
{
if (Open[i+ 2 ]<Close[i+ 2 ])
UpArrow[i] = Low[i+ 2 ] - 0.0003 ; //High[i+2] - (High[i+2]-Low[i+2]);
}
}
//--- alert
BuySignal( "Alert BuySignal" ,UpArrow, 0 ,rates_total,prev_calculated,Close,spread);
SellSignal( "Alert SellSignal" ,DownArrow, 0 ,rates_total,prev_calculated,Close,spread);
//--- OnCalculate done. Return new prev_calculated.return (rates_total);
}
//+------------------------------------------------------------------+//| Buy signal function |//+------------------------------------------------------------------+void BuySignal( string SignalSirname, // текст имени индикатора для почтовых и пуш-сигналовdouble &ColorArray[], // цветовой индексный буферint ColorIndex, // индекс цвета в цветовом индескном буфере для подачи сигналаconstint Rates_total, // текущее количество баровconstint Prev_calculated, // количество баров на предыдущем тикеconstdouble &Close[], // цена закрытияconstint &Spread[]) // спред
{
//---staticuint counter= 0 ;
if (Rates_total!=Prev_calculated)
counter= 0 ;
bool BuySignal= false ;
bool SeriesTest= ArrayGetAsSeries (ColorArray);
int index,index1;
if (SeriesTest)
{
index= int (NumberofBar);
index1=index+ 1 ;
}
else
{
index=Rates_total- int (NumberofBar)- 1 ;
index1=index- 1 ;
}
if (SignMode==MODE_SIGNAL)
{
if (ColorArray[index1]!=ColorIndex && ColorArray[index]==ColorIndex)
BuySignal= true ;
}
else
{
if (ColorArray[index]==ColorIndex)
BuySignal= true ;
}
if (BuySignal && counter<=NumberofAlerts)
{
counter++;
MqlDateTime tm;
TimeToStruct ( TimeCurrent (),tm);
string text= TimeToString ( TimeCurrent (), TIME_DATE )+ " " + string (tm.hour)+ ":" + string (tm.min);
SeriesTest= ArrayGetAsSeries (Close);
if (SeriesTest)
index= int (NumberofBar);
else
index=Rates_total- int (NumberofBar)- 1 ;
double Ask=Close[index];
double Bid=Close[index];
SeriesTest= ArrayGetAsSeries (Spread);
if (SeriesTest)
index= int (NumberofBar);
else
index=Rates_total- int (NumberofBar)- 1 ;
Bid+= _Point *Spread[index];
string sAsk= DoubleToString (Ask, _Digits );
string sBid= DoubleToString (Bid, _Digits );
string sPeriod=GetStringTimeframe( ChartPeriod ());
if (SignMode==MODE_SIGNAL || (SignMode==MODE_TREND && ColorArray[index1]!=ColorIndex))
{
if (SoundON)
Alert ( "BUY signal \n Ask=" ,Ask, "\n Bid=" ,Bid, "\n currtime=" ,text, "\n Symbol=" , Symbol (), " Period=" ,sPeriod);
if (EMailON)
SendMail (SignalSirname+ ": BUY signal alert" , "BUY signal at Ask=" +sAsk+ ", Bid=" +sBid+ ", Date=" +text+ " Symbol=" + Symbol ()+ " Period=" +sPeriod);
if (PushON)
SendNotification (SignalSirname+ ": BUY signal at Ask=" +sAsk+ ", Bid=" +sBid+ ", Date=" +text+ " Symbol=" + Symbol ()+ " Period=" +sPeriod);
}
else
{
if (SoundON)
Alert ( "Up Trend signal \n Ask=" ,Ask, "\n Bid=" ,Bid, "\n currtime=" ,text, "\n Symbol=" , Symbol (), " Period=" ,sPeriod);
if (EMailON)
SendMail (SignalSirname+ ": Up Trend signal alert" , "BUY signal at Ask=" +sAsk+ ", Bid=" +sBid+ ", Date=" +text+ " Symbol=" + Symbol ()+ " Period=" +sPeriod);
if (PushON)
SendNotification (SignalSirname+ ": Up Trend signal at Ask=" +sAsk+ ", Bid=" +sBid+ ", Date=" +text+ " Symbol=" + Symbol ()+ " Period=" +sPeriod);
}
}
//---
}
//+------------------------------------------------------------------+//| Sell signal function |//+------------------------------------------------------------------+void SellSignal( string SignalSirname, // текст имени индикатора для почтовых и пуш-сигналовdouble &ColorArray[], // цветовой индексный буферint ColorIndex, // индекс цвета в цветовом индескном буфере для подачи сигналаconstint Rates_total, // текущее количество баровconstint Prev_calculated, // количество баров на предыдущем тикеconstdouble &Close[], // цена закрытияconstint &Spread[]) // спред
{
//---staticuint counter= 0 ;
if (Rates_total!=Prev_calculated)
counter= 0 ;
bool SellSignal= false ;
bool SeriesTest= ArrayGetAsSeries (ColorArray);
int index,index1;
if (SeriesTest)
{
index= int (NumberofBar);
index1=index+ 1 ;
}
else
{
index=Rates_total- int (NumberofBar)- 1 ;
index1=index- 1 ;
}
if (SignMode==MODE_SIGNAL)
{
if (ColorArray[index1]!=ColorIndex && ColorArray[index]==ColorIndex)
SellSignal= true ;
}
else
{
if (ColorArray[index]==ColorIndex)
SellSignal= true ;
}
if (SellSignal && counter<=NumberofAlerts)
{
counter++;
MqlDateTime tm;
TimeToStruct ( TimeCurrent (),tm);
string text= TimeToString ( TimeCurrent (), TIME_DATE )+ " " + string (tm.hour)+ ":" + string (tm.min);
SeriesTest= ArrayGetAsSeries (Close);
if (SeriesTest)
index= int (NumberofBar);
else
index=Rates_total- int (NumberofBar)- 1 ;
double Ask=Close[index];
double Bid=Close[index];
SeriesTest= ArrayGetAsSeries (Spread);
if (SeriesTest)
index= int (NumberofBar);
else
index=Rates_total- int (NumberofBar)- 1 ;
Bid+= _Point *Spread[index];
string sAsk= DoubleToString (Ask, _Digits );
string sBid= DoubleToString (Bid, _Digits );
string sPeriod=GetStringTimeframe( ChartPeriod ());
if (SignMode==MODE_SIGNAL || (SignMode==MODE_TREND && ColorArray[index1]!=ColorIndex))
{
if (SoundON)
Alert ( "SELL signal \n Ask=" ,Ask, "\n Bid=" ,Bid, "\n currtime=" ,text, "\n Symbol=" , Symbol (), " Period=" ,sPeriod);
if (EMailON)
SendMail (SignalSirname+ ": SELL signal alert" , "SELL signal at Ask=" +sAsk+ ", Bid=" +sBid+ ", Date=" +text+ " Symbol=" + Symbol ()+ " Period=" +sPeriod);
if (PushON)
SendNotification (SignalSirname+ ": SELL signal at Ask=" +sAsk+ ", Bid=" +sBid+ ", Date=" +text+ " Symbol=" + Symbol ()+ " Period=" +sPeriod);
}
else
{
if (SoundON)
Alert ( "Down trend signal \n Ask=" ,Ask, "\n Bid=" ,Bid, "\n currtime=" ,text, "\n Symbol=" , Symbol (), " Period=" ,sPeriod);
if (EMailON)
SendMail (SignalSirname+ ": Down trend signal alert" , "SELL signal at Ask=" +sAsk+ ", Bid=" +sBid+ ", Date=" +text+ " Symbol=" + Symbol ()+ " Period=" +sPeriod);
if (PushON)
SendNotification (SignalSirname+ ": Down trend signal at Ask=" +sAsk+ ", Bid=" +sBid+ ", Date=" +text+ " Symbol=" + Symbol ()+ " Period=" +sPeriod);
}
}
//---
}
//+------------------------------------------------------------------+//| Получение таймфрейма в виде строки |//+------------------------------------------------------------------+string GetStringTimeframe( ENUM_TIMEFRAMES timeframe)
{
//----return ( StringSubstr ( EnumToString (timeframe), 7 ,- 1 ));
//----
}
//+------------------------------------------------------------------+
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.
Guys. Help me bolt an alert to the indicator.
to the indicators in which:
int start()
int init()
int deinit()
screwing something on isn't respecting yourself or others...
take the trouble to redesign to modern interfaces
If you change a global variable in a function, it will change. But this is a dangerous way of programming, because in the code, as it grows, there will be unobvious assignments in different functions of the program.
There's a main function in the program, that's where you do the global variable assignment. And in other functions, do it this way:
Or like this:
I agree that in voluminous code, it's easy to miss the point of an unwanted variable change (X). From this point of view, calling the main function each time you need to find out what's wrong with X is correct. But here is the question. If the main function calculates and outputs several different values (X, Y, Z) and is quite large, while X is used repeatedly in the course of the program, won't this approach excessively consume computing power? I.e. in order to get X, we repeatedly run a whole block where we also recalculate Y and Z in addition to X , which, say, was needed only once. Therefore, if the algorithm contains sequential change and overwrite of X from one function to another, it may be more complicated for a programmer (requires more attention and checks for errors), but then it is easier for the machine.
to the indicators in which:
int start()
int init()
int deinit()
screwing something on isn't respecting yourself or others...
Take the trouble to redesign to modern interfaces
So show me how it must look like on modern interfaces. The man apparently has never coded (otherwise he would have figured out the Alert without us). He just found the code somewhere, brought it here and wants an alert.
But here is the question. If the main function calculates and outputs several different values (X, Y, Z) and is quite large, and X is used many times along the way
Show us how it should look like on modern interfaces. It seems that the man has never programmed (otherwise he would have figured out the alert without us). He just found the code somewhere, brought it here and wants an alert.
Where do you get such "indicators" and "advisors" from? but if you melt down, the source won't run out...
there's no such thing on the site for a long time.
If the maker of these indicators has not succeeded, the market has moved to the new MQL5(4). They will help and explain things there, and it will be useful to everyone.
or go to freelance
but if molasses
From the word molasses, is it?
Guys, help me attach an alert to the indicator.
Guys. help to fasten the alert to the indicator.
screwed - I do not remember the code from the code base and the author - to whom I need to say thanks! - if he recognizes his code - I say thank you to him!
and here is your indicator - I did it - only on MT5 with Alert.
How was it sucked in? Like this?