2

When using OrderSelect() in mql4, are the orders ordered according to the ticket number by default? My intention is to use OrderModify() on orders starting from the first that was opened to the most recent.

Paul Wakhungu
  • 322
  • 2
  • 18

3 Answers3

2

Never assume anything in MQL unless it's explicitly specified in the documentation. That said, you'll need to sort your ticket numbers before iterating them in order.

   CArrayInt tickets;
   for(int i=0; OrderSelect(i, SELECT_BY_POS); i++)
      tickets.Add(OrderTicket());
   tickets.Sort();
   for(int i=0; i<tickets.Total(); i++)
      if(OrderSelect(tickets[i], SELECT_BY_TICKET))
         ...
nicholishen
  • 2,602
  • 2
  • 9
  • 13
2
`enter code here`
int Magic = 12345;
// This reads the orders LIFO (last in...)
// the index is an integer and is incremented from 0 
// as the orders are placed. It is NOT 
// the ticket number. No sorting necessary.
for(int i=OrdersTotal()-1;i>=0;i--) 
    if(_Symbol=OrderSymbol() && Magic = OrderMagicNumber())
        if(OrderSelect(i, SELECT_BY_POS) {
            Print("Order Index: ",i,", Ticket: ",OrderTicket());
   
Oliver
  • 76
  • 1
0

You cannot call OrderSelect() function without parameters. You must specify id and the way the orders are selected. If you know an ID of the order, as it is seen it MT4 terminal window, you can call OrderSelect( order_id, SELECT_BY_TICKET), if you dont know or in case you loop over history trades you have to apply OrderSelect(i,SELECT_BY_POS) or OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) where i is integer between 0 and OrdersTotal() or OrdersHistoryTotal() respectfully. If you loop over the array of trades with i as an integer, you are strongly advised to loop from the maximum value to zero (and not vice versa), and you can obtain ticket id by calling OrderTicket() function after OrderSelect(*,*[,MODE_HISTORY]) is successful.

Daniel Kniaz
  • 4,603
  • 2
  • 14
  • 20
  • My question: Is it possible to process the orders in the order in which they were opened? – Paul Wakhungu Sep 19 '18 at 21:59
  • 1
    Yes and no. If you mean the way the orders were placed (both market and pending) - then yes. each order has its ticket-id and they are incrementing. it is also possible that a pending order is opened after a market order (first you put a limit order, then market, then limit is executed). in such a way limit order has earlier ticket id but later order open price. So it would be better to get orders as a class inherited of CObject and then sort them. – Daniel Kniaz Sep 20 '18 at 22:10
  • I don't do pending orders, so would that mean the rest are sorted? – Paul Wakhungu Sep 21 '18 at 21:02
  • 1
    yes they are sorted by order_id (and by order open time also). if you need to sort by orderclose price - need to store and implement your own algo. – Daniel Kniaz Sep 22 '18 at 08:43