DEV Community

Omais Ali
Omais Ali

Posted on

Capping open positions per EA in MQL5 without the same tick race

"Never hold more than three positions" sounds like a one line rule. In practice many EAs break it, usually on fast days when two signals arrive close together.

The naive version

Most implementations loop over PositionsTotal(), count positions with the EA's magic number, and allow a new order if the count is below the limit. That works until two orders are sent before the first one appears in the position list. On a market order this window is short, but with a slow server, a requote or an order that fills in parts, the EA can send a second order while the first is still pending, and both pass the check.

Count what is in flight too

A safer count includes three things:

  1. Open positions with your magic number and symbol.
  2. Pending orders with your magic number, if your strategy uses them, since they can become positions without warning.
  3. Requests you sent that have not shown up yet.

The third part needs a little state. Keep a small list of order tickets you sent that have not produced a deal yet. Add the ticket right after a successful OrderSend, and remove it in OnTradeTransaction when the matching deal arrives or the order is cancelled or rejected. Matching by ticket also means another EA's deals on the same account cannot change your count.

input int    InpMaxPositions = 3;
input long   InpMagic        = 240511;

ulong g_inflight[];

int CountMine()
{
   int n = 0;
   for(int i = 0; i < PositionsTotal(); i++)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(PositionGetInteger(POSITION_MAGIC) != InpMagic) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
      n++;
   }
   for(int j = 0; j < OrdersTotal(); j++)
   {
      ulong ticket = OrderGetTicket(j);
      if(ticket == 0) continue;
      if(OrderGetInteger(ORDER_MAGIC) != InpMagic) continue;
      if(OrderGetString(ORDER_SYMBOL) != _Symbol) continue;
      n++;
   }
   return n + ArraySize(g_inflight);
}

bool CanOpen()
{
   return CountMine() < InpMaxPositions;
}

void RememberSent(ulong order_ticket)
{
   int k = ArraySize(g_inflight);
   ArrayResize(g_inflight, k + 1);
   g_inflight[k] = order_ticket;
}

void Forget(ulong order_ticket)
{
   for(int i = 0; i < ArraySize(g_inflight); i++)
      if(g_inflight[i] == order_ticket)
      {
         ArrayRemove(g_inflight, i, 1);
         return;
      }
}

void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
{
   if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
      Forget(trans.order);
   if(trans.type == TRADE_TRANSACTION_HISTORY_ADD &&
      (trans.order_state == ORDER_STATE_CANCELED ||
       trans.order_state == ORDER_STATE_REJECTED ||
       trans.order_state == ORDER_STATE_EXPIRED))
      Forget(trans.order);
}
Enter fullscreen mode Exit fullscreen mode

After a successful OrderSend, call RememberSent(result.order). For an order that fills in parts you may see several deals; removing the ticket on the first deal is fine here, because from that moment the position itself shows up in the count.

Reset on restart

The in flight list lives in memory. After a terminal restart it starts empty, which is fine because anything that was in flight is now either a position or gone. The loops over positions and orders cover the rest.

Netting accounts

On a netting account there is only one position per symbol, so "max positions" usually really means "max adds". Count your own deals since the position opened instead, or store the add count in the position comment or a global variable.

Small details like this decide whether a risk rule exists only in the settings or actually holds on the worst day.

Top comments (0)