First open position

 

Dear all,


I need your help on a code that allows me to know what is the first openned trade.

i.e. Assuming we have 5-6 trades open, how can I know what was the first of them that was openned?


Sorry for my English


Regards


Paulo

 
 
batalhadematos:

I need your help on a code that allows me to know what is the first openned trade.

Your question is ambiguous if you are using pending orders (i.e. OP_BUYSTOP, OP_SELLLIMIT etc). The "open time" in MT4 can mean either the time a pending order was placed with the broker, or the time that an order was filled.


Assuming that you want the earliest filled order, then possible code goes as follows. This avoids any assumption about whether or not you are using pending orders. It will return the ticket/position/time of the first order to be filled regardless of whether you are using pending orders or not.


   if (OrdersTotal() == 0) {
      // No open or pending orders 
   } else {
      // At least one open or pending order. Record the earliest open time, its ticket, and its current position between 0 and OrdersTotal() - 1
      datetime dtEarliestOrder = D'2019/12/31';   // Will stop working at about the time MT5 comes out of beta
      int lEarliestTicket = -1;
      int lPositionOfEarliest = -1;

      for (int iScan = OrdersTotal() - 1; iScan >= 0; iScan--) {
         if (!OrderSelect(iScan, SELECT_BY_POS)) {
            // OrderSelect() failed. Weird.
         } else {
            // On the assumption that we want to ignore pending orders...
            if (OrderType() != OP_BUY && OrderType() != OP_SELL) {
               // A pending order. Remove this if condition to look at placement time rather than fill time 
            } else {
               if (dtEarliestOrder >= OrderOpenTime()) {
                  // Earlier than (or equal to) the earliest order found so far 
                  dtEarliestOrder = OrderOpenTime();
                  lEarliestTicket = OrderTicket();
                  lPositionOfEarliest = iScan;  
               } else {
                  // Selected order is later than the earliest found so far 
               }  
            }
         }
      }

      // At this point, lEarliestTicket holds the ticket number of the earliest order found,
      // and lPositionOfEarliest holds its current zero-based index for use with SELECT_BY_POS.
      // The dtEarliestOrder variable contains the open-time of the relevant order.
      // If the code remains configured to ignore pending orders, then lEarliestTicket and
      // lPositionOfEarliest can contain -1 if there are pending orders but no filled orders.
   }
 

Dear CB and JJC,


Thank you very much.

JJC, it was my mistake, that's exactly what I want (the filled orders).

I will try the conde sample you send me.


Best regards and thank you very much both of you


Paulo

Reason: