The great and terrible MT4 forever (or how to strategise a transition) - page 16

 

this works out well - (depending on what purpose!?)

#include <Trade\Trade.mqh>
CTrade Trade;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   int total=PositionsTotal();
   int Ordertotal=OrdersTotal();
   while(!IsStopped() && (total <= 1))  // Закончим, когда появится более одной позиции.
      if(total == 1)
         Trade.PositionClose(PositionGetTicket(0)); // Если есть позиция - закрываем.
      else
         if(Ordertotal!=0)
            Trade.Buy(0.01); // Если нет позиции и ордера - открываем позицию.
  }
//+------------------------------------------------------------------+
 
SanAlex:

that works out well - (depending on what purpose!?)

Don't get involved. They have a special DC there who builds all sorts of intrigues to catch the MT bugs.

 
Alexey Viktorov:

A special DC who builds all sorts of intrigues to catch the MT bugs.

Most brokers work according to the same scheme: Result.deal == 0.

For example, Signals is the most popular broker for scalping.

Among reputable brokers it is quite difficult to find where MT5 works according to a different scheme.

 
SanAlex:

this works out well - (depending on what purpose!?)


What exactly "works well"?
You have an error in your code, which has already been pointed out above.
 
fxsaber:

Most brokers work according to the same scheme: Result.deal == 0.

Signals, for example, is the most popular broker for scalping.

Among known brokers it is quite difficult to find where MT5 works according to a different scheme.

I don't know what kind of scalping works so much that you don't have time to close a position...

If you don't mind, still try to add checking the number of positions

    else if(!PositionsTotal() && !OrdersTotal())

I think the two positions are open and close. It wouldn't hurt to try and get the types of these two positions. If they are differently directed, it would confirm my suspicions...

 
Ihor Herasko:

Done:

Result:

Well get the status of this order.If the ticket is known.

The trade failed, the execution price is 0.

Structure of trade request result (MqlTradeResult)

In response to a trade request, the trade server returns data containing the trade request processing result as a special predefined structure MqlTradeResult.

struct MqlTradeResult
  {
   uint     retcode;          // Код результата операции
   ulong    deal;             // Тикет сделки, если она совершена
   ulong    order;            // Тикет ордера, если он выставлен
   double   volume;           // Объем сделки, подтверждённый брокером
   double   price;            // Цена в сделке, подтверждённая брокером
   double   bid;              // Текущая рыночная цена предложения (цены реквота)
   double   ask;              // Текущая рыночная цена спроса (цены реквота)
   string   comment;          // Комментарий брокера к операции (по умолчанию заполняется расшифровкой кода возврата торгового сервера)
   uint     request_id;       // Идентификатор запроса, устанавливается терминалом при отправке 
   uint     retcode_external; // Код ответа внешней торговой системы
  };

 
Rashid Umarov:

So get the status of this order. If the ticket is known.

The trade failed, the execution price is 0.

That's the thing: it has passed. When the script finishes executing, one or two positions are left hanging (depending on how many prints you insert in the code).

Code:

#define  PRINT(A) Print(#A + " = " + (string)(A))

#include <Trade\Trade.mqh>

void OnStart()
{
  CTrade Trade;
  
  while (!IsStopped() && (PositionsTotal() <= 1)) // Закончим, когда появится более одной позиции.
    if (PositionsTotal() == 1)
    {
      Trade.PositionClose(PositionGetTicket(0)); // Если есть позиция - закрываем.
      Print("Закрытие, т. к. PositionsTotal() равно 1");
    }
    else if (!OrdersTotal())
    {
      printf("Перед открытием. PositionsTotal: %d, OrdersTotal: %d", PositionsTotal(), OrdersTotal());
      Trade.Buy(0.01); // Если нет позиции и ордера - открываем позицию.
      PRINT(Trade.ResultRetcodeDescription());
      PRINT(Trade.ResultDeal());
      PRINT(Trade.ResultOrder());
      PRINT(Trade.ResultComment());
      if (OrderSelect(Trade.ResultOrder()))
         PRINT(OrderGetInteger(ORDER_STATE));
      printf("После открытия. PositionsTotal: %d, OrdersTotal: %d", PositionsTotal(), OrdersTotal());
    }
    
  Print("Выход. PostionsTotal: ", PositionsTotal());
}

Result:

2021.05.05 14:25:14.738 Test (EURUSD,M1)        Перед открытием. PositionsTotal: 0, OrdersTotal: 0
2021.05.05 14:25:14.821 Test (EURUSD,M1)        Trade.ResultRetcodeDescription() = done at 0.00000
2021.05.05 14:25:14.821 Test (EURUSD,M1)        Trade.ResultDeal() = 0
2021.05.05 14:25:14.821 Test (EURUSD,M1)        Trade.ResultOrder() = 2249888681
2021.05.05 14:25:14.821 Test (EURUSD,M1)        Trade.ResultComment() = Request executed
2021.05.05 14:25:14.821 Test (EURUSD,M1)        EnumToString(ENUM_ORDER_STATE(OrderGetInteger(ORDER_STATE))) = ORDER_STATE_PLACED
2021.05.05 14:25:14.821 Test (EURUSD,M1)        После открытия. PositionsTotal: 1, OrdersTotal: 1
2021.05.05 14:25:14.899 Test (EURUSD,M1)        Закрытие, т. к. PositionsTotal() равно 1
2021.05.05 14:25:14.899 Test (EURUSD,M1)        Выход. PostionsTotal: 2
 
Alexey Viktorov:

I don't know what kind of scalping works so hard that you can't close a position in time...

Everything is in time there. Just an architectural feature of MT5.

If you don't mind, try to add checking the number of positions

This check is present in the source code.

I think that the two positions are open and close. It would also help to try to get the types of these two positions. If they are differently directed, it would confirm my suspicions...

There is no such thing as a closing position.

 
fxsaber:

I haven't got round to posting it yet. I will post it within 24 hours.

It didn't work, I found problems.

 
fxsaber:

Didn't work out, found problems.

Looking forward to it. If there is anything you need to help with, please write.