Organising the order cycle - page 14

 
Andrey Khatimlianskii:

Is OrderClose guaranteed to close the trade?

Not guaranteed, but there is a check in the code for this. Each OnTick call is independent of the previous one.

 
fxsaber:

Not guaranteed, but there is a check in the code for this case. Each OnTick call is independent of the previous one.

OK, closing on the next tick will do.

 
@Artyom Trishkin,@Andrey Khatimlianskii, Thanks for your participation! It's a pity no one else has commented on the MT5 code. Apparently they think everything is fine.
 
fxsaber:
@Artyom Trishkin,@Andrey Khatimlianskii, Thanks for participating! It's a pity nobody has commented on MT5 code. Apparently they think everything is fine.

Of course, the example was given to answer that all is not well at all in MT5. Example showing the problem

// Пример неправильного считывания торгового окружения на каждом тике
// Скрипт эмулирует два тика ТС, которая должна открыть одну позицию, если ее нет.

#include <Trade/Trade.mqh>

// Возвращает количество позиций по символу
int GetAmountPositions( const string Symb )
{
  int Res = 0;
  
  // Этот MQL5-код с ошибкой
  for (int i = PositionsTotal() - 1; i >= 0; i--)
    if (PositionGetSymbol(i) == Symb)
      Res++;

/*
  // В MT4 такой код выполняется без ошибки
  for (int i = OrdersTotal() - 1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS) && (OrderType() <= OP_SELL) && (OrderSymbol() == Symb))
      Res++;
*/      
  return(Res);
}

// Пример OnTick
void ExampleOnTick()
{
  static CTrade Trade;
  
  // Если нет позиции, открываем
  if (!GetAmountPositions(_Symbol))
    Trade.Buy(1);    
}

// Эмуляция прихода двух Tick-событий
void OnStart()
{
  ExampleOnTick(); 
  
  Sleep(10); // Между двумя тиками ~10 мс.
  
  ExampleOnTick();
}

What do you think, if you run this script on a symbol with no positions, what will happen in the end?

The correct answer is that one or two positions will be opened.

 
fxsaber:

Of course, the example was given to answer that all is not well at all in MT5. Example showing the problem

What do you think, if you run this script on a symbol with no positions, what will happen in the end?

The correct answer is that one or two positions will be opened.

As a consequence, the vast majority of MT5 Expert Advisors in Kodobase are not written correctly!

 
fxsaber:
Few will argue with this statement

This is a universal rule. But not many people think about its implementation in MT5. That's why I wrote a template of most uncomplicated TS (in kodobase almost all of them are like that)

For some reason some people write more code for the same TS. But in fact this code does just as well. Most TCs only require writing BuySignal and SellSignal. Nothing else is needed.

The template example is specifically written with SB. So question for MT5 experts, is the code correct?

I came to this thread by accident and actually wanted to start a thread to discuss strategy templates. Your template is close enough to what I think is correct (readable for me), but still I don't like when a call of one function is inserted into OnTick, which hides a whole mining mill.

At one time I even wrote MetaEditor: Relying on the power of templates. Since then the language has changed, no template editor. It would be interesting to discuss this issue (could be in a separate thread), and also get an article on the subject. I believe that when writing code one should try to make the strategy readable at a glance without having to get into class or macro methods.

 
fxsaber:

As a consequence - the vast majority of MT5 Expert Advisors in Kodobaz are not written correctly!

As always - categorically. Can't be, although I haven't read your code.

 
Rashid Umarov:

I've been wanting to start a thread to discuss strategy templates for a long time now. Your template is close enough to what I think is correct (readable for me), but I still don't like it when a call of one function is inserted into OnTick, which hides the whole mining mill.

If you make OnTick == Strategy, the template will shrink/shrink to an obscene size.

At one time I even wrote an article MetaEditor: Building on the power of templates. Since then the language has changed, no template editor. It would be interesting to discuss this issue (could be in a separate thread), and also get an article on the subject. I believe that when writing code one should try to make the strategy readable at a glance without having to get into class or macro methods.

This is how the template for both platforms showed. It is so simple that it is hard to discuss it, although for MT5 it is fundamentally wrong. But you have CExpert. I haven't looked there myself - it's scary.

 
Rashid Umarov:

As always - categorical. Can't be, although I haven't read your code.

You read it, your opinion is very interesting.

 
fxsaber:

Of course, the example was given to answer that all is not well at all in MT5. Example showing the problem

What do you think, if you run this script on a symbol with no positions, what will happen in the end?

The correct answer is that one or two positions will be opened.

And if we replace GetAmountPositions with standard OnTradeTransaction?

Approximately like this:

#include <Trade/Trade.mqh>
  int Res = 0;

// Возвращает количество позиций по символу
/*********************TradeTransaction function*********************/
void OnTradeTransaction(const MqlTradeTransaction& trans,
                        const MqlTradeRequest& request,
                        const MqlTradeResult& result)
{
  if(trans.type == TRADE_TRANSACTION_DEAL_ADD && trans.symbol == _Symbol)
   {
    /******************** Если открылась позиция********************/
    if(PositionSelectByTicket(trans.position))
     Res++;
    /******************** Если закрылась позиция********************/
    if(!PositionSelectByTicket(trans.position))
     Res--;
   }
}/*******************************************************************/

// Пример OnTick
void ExampleOnTick()
{
  static CTrade Trade;
  
  // Если нет позиции, открываем
  if (Res == 0)
    Trade.Buy(1);    
}

// Эмуляция прихода двух Tick-событий
void OnStart()
{
  ExampleOnTick(); 
  
  Sleep(10); // Между двумя тиками ~10 мс.
  
  ExampleOnTick();
}