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

 
Taras Slobodyanik:

So do you need to define a holiday or a ban on trading?
Trade was allowed on the 27th.

if it is a weekend, then you need a news parser - to identify holidays/weekends.

It doesn't matter what the reason is for not trading on a particular symbol, you just need to see that it's not trading. And sorry, I'm not yet mature enough to understand the parser. What is it, and how is it spelled out in the code?

 
novichok2018:

Hello!

Thanks again toAlexey Viktorov for the tip on the quotes - everything works. This Monday we have a situation - Germans have traded, while Englishmen have a day off. It turned out that in condition for euro position opening old values of pound were used. Hence the request: advise how to set check in the code that both symbols are traded on this day?

Thank you.

#include <Trade\AccountInfo.mqh>
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- объект для работы со счетом
CAccountInfo account;
//--- получим номер счета, на котором запущен советник
   long login=account.Login();
   Print("Login=",login);
//--- выясним тип счета
   ENUM_ACCOUNT_TRADE_MODE account_type=account.TradeMode();
//--- если счет оказался реальным, прекращаем работу эксперта немедленно!
   if(account_type==ACCOUNT_TRADE_MODE_REAL)
     {
      MessageBox("Работа на реальном счете запрещена, выходим","Эксперт запущен на реальном счете!");
      return(-1);
     }
//--- выведем тип счета    
   Print("Тип счета: ",EnumToString(account_type));
//--- выясним, можно ли вообще торговать на данном счете
   if(account.TradeAllowed())
      Print("Торговля на данном счете разрешена");
   else
      Print("Торговля на счете запрещена: возможно, вход был совершен по инвест-паролю");
//--- выясним, разрешено ли торговать на счете с помощью эксперта
   if(account.TradeExpert())
      Print("Автоматическая торговля на счете разрешена");
   else
      Print("Запрещена автоматическая торговля с помощью экспертов и скриптов");
//--- допустимое количество ордеров задано или нет
   int orders_limit=account.LimitOrders();
   if(orders_limit!=0)Print("Максимально допустимое количество действующих отложенных ордеров: ",orders_limit);
//--- выведем имя компании и сервера
   Print(account.Company(),": server ",account.Server());
//--- напоследок выведем баланс и текущую прибыль на счете
   Print("Balance=",account.Balance(),"  Profit=",account.Profit(),"   Equity=",account.Equity());
   Print(__FUNCTION__,"  completed"); //---
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

  }

Source https://www.mql5.com/ru/articles/481

Торговые операции на MQL5 - это просто
Торговые операции на MQL5 - это просто
  • www.mql5.com
Почти все трейдеры приходят на рынок для того, чтобы заработать денег, хотя есть и доля тех, кому важен не сам торговый результат, а участие в процессе, драйв. Впрочем, получить удовольствие от процесса можно не только торгуя вручную, но и занимаясь разработкой автоматических торговых систем. Ведь создание торгового робота может быть таким же...
 
Sergey Voytsekhovsky:

Source https://www.mql5.com/ru/articles/481

I don't know what to say here. Thank you, but I think this is completely off-topic. And why"if the score turns out to be real, terminate the EA immediately!"? I suppose I'm missing something.

 
novichok2018:

I don't know what to say here. Thank you, of course, but I think this is completely off-topic. And why"if the score turns out to be real, terminate the EA immediately!"?

This is an example of the code from the article. The article covers an experimental code, not for trading, but the functions are the same. It's an old article, but it's a good one for beginners.

The output you're looking for cannot be calculated by the code. The trade was open, but the British did not trade and did not have normal quotes. Try to set "normality" for quotes and check if they are there. For example the spread, the tick volatility, the frequency of price updates, or whatever does not suit you. A flight of fancy.

 
novichok2018:

I don't know what to say here. Thanks of course, but I think this is completely beside the point.

The easiest way to find out about the output is from the properties of the account, there will be restrictions on the account, IMHO of course. That's why I gave the code block above as an example

//--- выясним, можно ли вообще торговать на данном счете
   if(account.TradeAllowed())
      Print("Торговля на данном счете разрешена");

And in national outputs there may be character restrictions. In fact, check out the article, there's one there too:

#include<Trade\SymbolInfo.mqh>
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- объект для получения свойств символа
CSymbolInfo symbol_info;
//--- зададим имя символа, для которого будем получать информацию
   symbol_info.Name(_Symbol);
//--- получим текущие котировки и выведем
   symbol_info.RefreshRates();
   Print(symbol_info.Name()," (",symbol_info.Description(),")",
         "  Bid=",symbol_info.Bid(),"   Ask=",symbol_info.Ask());
//--- получим значения минимальных отступов для торговых операций
   Print("StopsLevel=",symbol_info.StopsLevel()," pips, FreezeLevel=",
         symbol_info.FreezeLevel()," pips");
//--- получим количество знаков после запятой и размер пункта
   Print("Digits=",symbol_info.Digits(),
         ", Point=",DoubleToString(symbol_info.Point(),symbol_info.Digits()));
//--- информация о спреде
   Print("SpreadFloat=",symbol_info.SpreadFloat(),", Spread(текущий)=",
         symbol_info.Spread()," pips");
//--- запросим тип исполнения ордеров, нет ли ограничений
   Print("Ограничения на торговые операции: ",EnumToString(symbol_info.TradeMode()),
         " (",symbol_info.TradeModeDescription(),")");
//--- выясним режим заключения сделок
   Print("Режим исполнения сделок: ",EnumToString(symbol_info.TradeExecution()),
         " (",symbol_info.TradeExecutionDescription(),")");
//--- выясним способ вычисления стоимости контрактов
   Print("Вычисление стоимости контракта: ",EnumToString(symbol_info.TradeCalcMode()),
         " (",symbol_info.TradeCalcModeDescription(),")");
//--- размер контрактов
   Print("Размер стандартного контракта: ",symbol_info.ContractSize(),
         " (",symbol_info.CurrencyBase(),")");
//--- минимальный, максимальный размеры объема в торговых операциях
   Print("Volume info: LotsMin=",symbol_info.LotsMin(),"  LotsMax=",symbol_info.LotsMax(),
         "  LotsStep=",symbol_info.LotsStep());
//--- 
   Print(__FUNCTION__,"  completed");
//---
   return(0);
  }
 
novichok2018:

It doesn't matter what the reason is for not trading on a particular symbol, you just need to see that it's not trading. And I'm sorry, I'm not yet mature enough to understand the parser. What is it, and how is it written in the code?

What does "no trading" mean? ?
trading is allowed - trade as much as you like)

Parser means that you have to download a file with news, then parse it - and determine the holiday-weekend.

 
Taras Slobodyanik:

Trade is allowed - trade as much as you like)

Trade is allowed, but there is no trading - it's a holiday.

But I think I've found a solution:

if(SeriesInfoInteger("EURUSD",PERIOD_H1,SERIES_LASTBAR_DATE)==SeriesInfoInteger("GBPUSD",PERIOD_H1,SERIES_LASTBAR_DATE))

and then the position didn't open on the 27th.

Seems like a good solution to me. If anyone sees any pitfalls, I would be grateful to know. Thank you all.

 
novichok2018:

Trading is allowed but there is no trading - they are on holiday.

i don't know how it is if trading is allowed to take place
(even on a holiday and a weekend).

looked at the news at the brokers - didn't see anyone restricting the pound on the 27th

 
Taras Slobodyanik:

I don't see how, if trading is allowed, then trading takes place
(even on a holiday and a weekend)

looked at the news at the brokers - didn't see anyone restricting the pound on the 27th

Actually I was not interested in the pound but in the FTSE100 index. I simplified it this way: as long as the euro, let it be the pound))). So there is no index data on the 27th.

 
Confused. How do I get the real profit (loss) on an open order (not a pending order) on MT4, including all commissions, swaps, etc.? (OrderProfit() + OrderSwap() + OrderCommission() or justOrderProfit() or something else? I would like to earn something after the order is closed.
Совершение сделок - Торговые операции - MetaTrader 5
Совершение сделок - Торговые операции - MetaTrader 5
  • www.metatrader5.com
Торговая деятельность в платформе связана с формированием и отсылкой рыночных и отложенных ордеров для исполнения брокером, а также с управлением текущими позициями путем их модификации или закрытия. Платформа позволяет удобно просматривать торговую историю на счете, настраивать оповещения о событиях на рынке и многое другое. Открытие позиций...
Reason: