double lostProfit(ulong ticket)
{
Print("****** "+__FUNCTION__+"******");
if(HistoryOrderSelect(ticket))
{
ulong pos_ID = HistoryOrderGetInteger(ticket,ORDER_POSITION_ID);
if(my_History.SelectByIndex(pos_ID)) // possible loss of data due to type conversion
{
Print("****** "+string(equity_plus[arr_size-1] - my_History.TakeProfit())+" ******");
return(equity_plus[arr_size-1] - my_History.TakeProfit());
}
elsePrint("--- Не выбрана позиция по ID "+string(pos_ID));
}
elsePrint("--- Не выбран ордер по тикету "+string(ticket));
return(0.0);
}
Позиция с магиком 2810292634423737, тикетом 2 и лотом 0.1 успешно закрыта.
****** lostProfit******
--- Не выбрана позиция по ID 2
Не следует путать между собой ордера из торговой истории и действующие отложенные ордера, которые отображаются на вкладке "Торговля" в панели "Инструменты". Список ордеров, которые были отменены или привели к проведению торговой операции, можно посмотреть в закладке "История" на панели "Инструменты" клиентского терминала. Функция...
For myself, I already realized that programming is not mine, but I managed to make friends with the MQL5 Master. However, when compiling some modules of trading signals, warnings appear. How critical are these warnings, and if not difficult, then tell me what needs to be corrected in the code of the trading signals module in order to eliminate the warnings shown in the picture.
With best regards, Vladimir.
Trading signals module code
//+------------------------------------------------------------------+//| SampleSignal.mqh |//| Copyright 2010, MetaQuotes Software Corp. |//| http://www.mql5.com |//+------------------------------------------------------------------+#property copyright"Copyright 2010, MetaQuotes Software Corp."#property link"http://www.mql5.com"//+------------------------------------------------------------------+//| включаемые файлы |//+------------------------------------------------------------------+#include <Expert\ExpertSignal.mqh>
// wizard description start//+------------------------------------------------------------------+//| Description of the class |//| Title=Сигнал по пересечению ценой скользящей средней |//| со входом на последующем откате |//| Type=SignalAdvanced |//| Name=Sample |//| Class=CSampleSignal |//| Page= |//| Parameter=PeriodMA,int,12 |//| Parameter=ShiftMA,int,6 |//| Parameter=MethodMA,ENUM_MA_METHOD,MODE_EMA |//| Parameter=AppliedMA,ENUM_APPLIED_PRICE,PRICE_CLOSE |//| Parameter=Limit,double,0.0 |//| Parameter=StopLoss,double,50.0 |//| Parameter=TakeProfit,double,50.0 |//| Parameter=Expiration,int,10 |//+------------------------------------------------------------------+// wizard description end//+------------------------------------------------------------------+//| Класс CSampleSignal. |//| Назначение: Класс генератора торговых сигналов по пересечению |//| ценой скользящей средней |//| со входом на последующем откате. |//| Является производным от класса CExpertSignal. |//+------------------------------------------------------------------+class CSampleSignal : public CExpertSignal
{
protected :
CiMA m_MA; // объект для доступа к значениям скользящей средней
CiOpen m_open; // объект для доступа к ценам открытия баров
CiClose m_close; // объект для доступа к ценам закрытия баров//--- параметры настройкиint m_period_ma; // период усреднения средней скользящейint m_shift_ma; // смещение средней скользящей по оси времениENUM_MA_METHOD m_method_ma; // метод усреднения средней скользящейENUM_APPLIED_PRICE m_applied_ma; // объект усреднения средней скользящейdouble m_limit; // уровень установки отложенного ордера относительно средней скользящейdouble m_stop_loss; // уровень установки ордера "stop loss" относительно цены открытияdouble m_take_profit; // уровень установки ордера "take profit" относительно цены открытияint m_expiration; // время "жизни" отложенного ордера в барахpublic :
CSampleSignal();
//--- методы установки параметров настройкиvoid PeriodMA( int value) { m_period_ma=value; }
void ShiftMA( int value) { m_shift_ma=value; }
void MethodMA( ENUM_MA_METHOD value) { m_method_ma=value; }
void AppliedMA( ENUM_APPLIED_PRICE value) { m_applied_ma=value; }
void Limit( double value) { m_limit=value; }
void StopLoss( double value) { m_stop_loss=value; }
void TakeProfit( double value) { m_take_profit=value; }
void Expiration( int value) { m_expiration=value; }
//--- метод проверки параметров настройкиvirtualbool ValidationSettings();
//--- метод проверки параметров настройкиvirtualbool InitIndicators(CIndicators* indicators);
//--- методы генерации сигналов входа в рынокvirtualbool CheckOpenLong( double & price, double & sl, double & tp, datetime & expiration);
virtualbool CheckOpenShort( double & price, double & sl, double & tp, datetime & expiration);
//--- методы генерации сигналов модификации отложенных ордеровvirtualbool CheckTrailingOrderLong(COrderInfo* order, double & price);
virtualbool CheckTrailingOrderShort(COrderInfo* order, double & price);
protected :
//--- метод инициализации объектовbool InitMA(CIndicators* indicators);
bool InitOpen(CIndicators* indicators);
bool InitClose(CIndicators* indicators);
//--- методы доступа к данным объектовdouble MA( int index) { return (m_MA.Main(index)); }
double Open( int index) { return (m_open.GetData(index)); }
double Close( int index) { return (m_close.GetData(index)); }
};
//+------------------------------------------------------------------+//| Конструктор CSampleSignal. |//| INPUT: нет. |//| OUTPUT: нет. |//| REMARK: нет. |//+------------------------------------------------------------------+void CSampleSignal::CSampleSignal()
{
//--- установка значений по-умолчанию
m_period_ma = 12 ;
m_shift_ma = 6 ;
m_method_ma = MODE_EMA ;
m_applied_ma = PRICE_CLOSE ;
m_limit = 0.0 ;
m_stop_loss = 50.0 ;
m_take_profit= 50.0 ;
m_expiration = 10 ;
}
//+------------------------------------------------------------------+//| Проверка параметров настройки. |//| INPUT: нет. |//| OUTPUT: true-если настройки правильные, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::ValidationSettings()
{
//--- проверка параметровif (m_period_ma<= 0 )
{
printf ( __FUNCTION__ + ": период скользящей средней должен быть больше нуля" );
return ( false );
}
//--- успешное завершениеreturn ( true );
}
//+------------------------------------------------------------------+//| Инициализация индикаторов и таймсерий. |//| INPUT: indicators - указатель на объект-коллекцию |//| индикаторов и таймсерий. |//| OUTPUT: true-в случае успешного завершения, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::InitIndicators(CIndicators* indicators)
{
//--- проверка указателяif (indicators== NULL ) return ( false );
//--- инициализация скользящей среднейif (!InitMA(indicators)) return ( false );
//--- инициализация таймсерии цен открытияif (!InitOpen(indicators)) return ( false );
//--- инициализация таймсерии цен закрытияif (!InitClose(indicators)) return ( false );
//--- успешное завершениеreturn ( true );
}
//+------------------------------------------------------------------+//| Инициализация скользящей средней. |//| INPUT: indicators - указатель на объект-коллекцию |//| индикаторов и таймсерий. |//| OUTPUT: true-в случае успешного завершения, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::InitMA(CIndicators* indicators)
{
//--- инициализация объекта скользящей среднейif (!m_MA.Create(m_symbol.Name(),m_period,m_period_ma,m_shift_ma,m_method_ma,m_applied_ma))
{
printf ( __FUNCTION__ + ": ошибка инициализации объекта" );
return ( false );
}
m_MA.BufferResize( 3 +m_shift_ma);
//--- добавление объекта в коллекциюif (!indicators.Add( GetPointer (m_MA)))
{
printf ( __FUNCTION__ + ": ошибка добавления объекта" );
return ( false );
}
//--- успешное завершениеreturn ( true );
}
//+------------------------------------------------------------------+//| Инициализация таймсерии цен открытия. |//| INPUT: indicators - указатель на объект-коллекцию |//| индикаторов и таймсерий. |//| OUTPUT: true-в случае успешного завершения, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::InitOpen(CIndicators* indicators)
{
//--- инициализация объекта таймсерииif (!m_open.Create(m_symbol.Name(),m_period))
{
printf ( __FUNCTION__ + ": ошибка инициализации объекта" );
return ( false );
}
//--- добавление объекта в коллекциюif (!indicators.Add( GetPointer (m_open)))
{
printf ( __FUNCTION__ + ": ошибка добавления объекта" );
return ( false );
}
//--- успешное завершениеreturn ( true );
}
//+------------------------------------------------------------------+//| Инициализация таймсерии цен закрытия. |//| INPUT: indicators - указатель на объект-коллекцию |//| индикаторов и таймсерий. |//| OUTPUT: true-в случае успешного завершения, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::InitClose(CIndicators* indicators)
{
//--- инициализация объекта таймсерииif (!m_close.Create(m_symbol.Name(),m_period))
{
printf ( __FUNCTION__ + ": ошибка инициализации объекта" );
return ( false );
}
//--- добавление объекта в коллекциюif (!indicators.Add( GetPointer (m_close)))
{
printf ( __FUNCTION__ + ": ошибка добавления объекта" );
return ( false );
}
//--- успешное завершениеreturn ( true );
}
//+------------------------------------------------------------------+//| Проверка выполнения условия для покупки. |//| INPUT: price - ссылка для размещения цены открытия, |//| sl - ссылка для размещения цены stop loss, |//| tp - ссылка для размещения цены take profit, |//| expiration - ссылка для размещения времени истечения. |//| OUTPUT: true-если условие выполнено, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::CheckOpenLong( double & price, double & sl, double & tp, datetime & expiration)
{
//--- подготовка данныхdouble spread=m_symbol.Ask()-m_symbol.Bid();
double ma =MA( 1 );
double unit =PriceLevelUnit();
//--- проверка условияif (Open( 1 )<ma && Close( 1 )>ma && ma>MA( 2 ))
{
price=m_symbol.NormalizePrice(m_symbol.Bid()+m_limit*unit);
sl =m_symbol.NormalizePrice(price-m_stop_loss*unit);
tp =m_symbol.NormalizePrice(price+m_take_profit*unit);
expiration+=m_expiration* PeriodSeconds (m_period);
//--- условие выполненоreturn ( true );
}
//--- условие не выполненоreturn ( false );
}
//+------------------------------------------------------------------+//| Проверка выполнения условия для продажи. |//| INPUT: price - ссылка для размещения цены открытия, |//| sl - ссылка для размещения цены stop loss, |//| tp - ссылка для размещения цены take profit, |//| expiration - ссылка для размещения времени истечения. |//| OUTPUT: true-если условие выполнено, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::CheckOpenShort( double & price, double & sl, double & tp, datetime & expiration)
{
//--- подготовка данныхdouble ma =MA( 1 );
double unit=PriceLevelUnit();
//--- проверка условияif (Open( 1 )>ma && Close( 1 )<ma && ma<MA( 2 ))
{
price=m_symbol.NormalizePrice(m_symbol.Bid()+m_limit*unit);
sl =m_symbol.NormalizePrice(price+m_stop_loss*unit);
tp =m_symbol.NormalizePrice(price-m_take_profit*unit);
expiration+=m_expiration* PeriodSeconds (m_period);
//--- условие выполненоreturn ( true );
}
//--- условие не выполненоreturn ( false );
}
//+------------------------------------------------------------------+//| Проверка выполнения условия для модификации ордера на покупку. |//| INPUT: order - указатель на объект-ордер, |//| price - ссылка для размещения новой цены открытия. |//| OUTPUT: true-если условие выполнено, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::CheckTrailingOrderLong(COrderInfo* order, double & price)
{
//--- проверка указателяif (order== NULL ) return ( false );
//--- подготовка данныхdouble spread =m_symbol.Ask()-m_symbol.Bid();
double ma =MA( 1 );
double unit =PriceLevelUnit();
double new_price=m_symbol.NormalizePrice(ma-m_limit*unit+spread);
//--- проверка условияif (order.PriceOpen()==new_price) return ( false );
price=new_price;
//--- условие выполненоreturn ( true );
}
//+------------------------------------------------------------------+//| Проверка выполнения условия для модификации ордера на продажу. |//| INPUT: order - указатель на объект-ордер, |//| price - ссылка для размещения новой цены открытия. |//| OUTPUT: true-если условие выполнено, иначе false. |//| REMARK: нет. |//+------------------------------------------------------------------+bool CSampleSignal::CheckTrailingOrderShort(COrderInfo* order, double & price)
{
//--- проверка указателяif (order== NULL ) return ( false );
//--- подготовка данныхdouble ma =MA( 1 );
double unit=PriceLevelUnit();
double new_price=m_symbol.NormalizePrice(ma+m_limit*unit);
//--- проверка условияif (order.PriceOpen()==new_price) return ( false );
price=new_price;
//--- условие выполненоreturn ( true );
}
//+------------------------------------------------------------------+
I have already understood that programming is not for me, but I have managed to make friends with the MQL5 Wizard. However, when compiling some modules of trading signals, I get warnings. How critical are these warnings and, if possible, please advise on what to change in the code of the trading signals module to avoid the warnings shown in the picture.
You have created such an excellent tool like the MQL5 Wizard for people with no programming knowledge that can generate Expert Advisors based on trading modules. The MQL5 website contains a lot of interesting trading signal modules that were written a few years ago by MQL5 professionals and other MQL5 forum members. By the way,thank you all for your work! However, there is a little "but" that keeps hampering the full power of the MQL5 Wizard.
Due to the fact that the programming language is under constant development, I ask you to create a branch reflecting all the nuances of these changes and describing the necessary actions in terms of code corrections, for example, in trading signals modules to avoid such issues:
MrBrooklin:
Hello!
Please advise what you should fix in the code of the Trading Signals module to avoid the compiler warning in that line, which is highlighted in yellow.
Sincerely, Vladimir.
If my suggestion is acceptable, this topic could be titled, for instance, "Revision of Trading Signals Modules".
Please advise what you should correct in the code of the trading signals module to exclude the compiler warning in the line highlighted in yellow.
Sincerely, Vladimir.
Why do you address the "m_symbol" object in one place
int Bars_=Bars(m_symbol.Name(),m_Ind_Timeframe);
and then suddenly to Symbol():
int Bars_=Bars(Symbol(),m_Ind_Timeframe); // ПРЕДУПРЕЖДЕНИЕ В ЭТОЙ СТРОКЕ КОДА: deprecated behavior, hidden method calling will be disabled in a future MQL compiler version
You shouldn't do it that way.
To understand why there is suddenly a warning about calling the hidden method, just put the mouse cursor on Symbol and press the middle mouse button: you will see that there is such a method in
in the ExpertBase file.
Therefore, you should use m_symbol in the signals module.
Why do you access the "m_symbol" object in one place
and then suddenly to Symbol():
You should not do that.
Thanks, Vladimir, for the tip!
The thing is that this module was downloaded from the website and simply compiled into MetaEditor. I haven't performed any other operations (e.g., code changes, etc.) withthe trading signals module and the warning was generated by the compiler itself.
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.
Hello.
Can you please tell me if there is any ready-made solution for backtesting by news?
Can you tell me what's wrong?
How do I know the profit of a closed position on a ticket?
Can you tell me what's wrong?
How do I know the profit of a closed position on a ticket?
Select all trades in the ticketed position and add up the trade's profit, commission and swap.
Hello!
For myself, I already realized that programming is not mine, but I managed to make friends with the MQL5 Master. However, when compiling some modules of trading signals, warnings appear. How critical are these warnings, and if not difficult, then tell me what needs to be corrected in the code of the trading signals module in order to eliminate the warnings shown in the picture.
With best regards, Vladimir.
Trading signals module code
Hello!
I have already understood that programming is not for me, but I have managed to make friends with the MQL5 Wizard. However, when compiling some modules of trading signals, I get warnings. How critical are these warnings and, if possible, please advise on what to change in the code of the trading signals module to avoid the warnings shown in the picture.
Best regards, Vladimir.
Trading Signal Module Code
The language is developing.
Make substitutions: (ctrl+h)
m_open -> m_open_sample
m_close -> m_close_sample
m_expiration -> m_expiration_sample
The language is evolving.
Make substitutions: (ctrl+h)
m_open -> m_open_sample
m_close -> m_close_sample
m_expiration -> m_expiration_sample
Thank you, Vladimir, for your quick and clear answer. All warnings have been eliminated.
Sincerely, Vladimir.
Hello!
Please advise what you should correct in the code of the trading signals module to exclude the compiler warning in the line highlighted in yellow.
Best regards, Vladimir.
Hello, dear developers of MQL5!
You have created such an excellent tool like the MQL5 Wizard for people with no programming knowledge that can generate Expert Advisors based on trading modules. The MQL5 website contains a lot of interesting trading signal modules that were written a few years ago by MQL5 professionals and other MQL5 forum members. By the way,thank you all for your work! However, there is a little "but" that keeps hampering the full power of the MQL5 Wizard.
Due to the fact that the programming language is under constant development, I ask you to create a branch reflecting all the nuances of these changes and describing the necessary actions in terms of code corrections, for example, in trading signals modules to avoid such issues:
Hello!
Please advise what you should fix in the code of the Trading Signals module to avoid the compiler warning in that line, which is highlighted in yellow.
Sincerely, Vladimir.
If my suggestion is acceptable, this topic could be titled, for instance, "Revision of Trading Signals Modules".
Sincerely, Vladimir.
Hello!
Please advise what you should correct in the code of the trading signals module to exclude the compiler warning in the line highlighted in yellow.
Sincerely, Vladimir.
Why do you address the "m_symbol" object in one place
and then suddenly to Symbol():
You shouldn't do it that way.
To understand why there is suddenly a warning about calling the hidden method, just put the mouse cursor on Symbol and press the middle mouse button: you will see that there is such a method in
in the ExpertBase file.
Therefore, you should use m_symbol in the signals module.
Why do you access the "m_symbol" object in one place
and then suddenly to Symbol():
You should not do that.
Thanks, Vladimir, for the tip!
The thing is that this module was downloaded from the website and simply compiled into MetaEditor. I haven't performed any other operations (e.g., code changes, etc.) withthe trading signals module and the warning was generated by the compiler itself.
Sincerely, Vladimir.