I don't know whether this is the simplest way, but it should work. I have not tested it.
//Function to find 2nd last order int Find2ndOrder() { int as=0; int ot=OrdersTotal(); int ticketarray[]; ArrayResize(ticketarray,as,ot); datetime datearray[]; ArrayResize(datearray,as,ot); for(int x=ot-1;x>=0;x--) { if(OrderSelect(x,SELECT_BY_POS,MODE_TRADES)) if(OrderMagicNumber()==MagicNumber) { as++; ArrayResize(ticketarray,as); ticketarray[as-1]=OrderTicket(); ArrayResize(datearray,as); datearray[as-1]=OrderOpenTime(); } } if(as<2) return(0); int index=ArrayMaximum(datearray,WHOLE_ARRAY,0); datearray[index]=0; index=ArrayMaximum(datearray,WHOLE_ARRAY,0); return(ticketarray[index]); }
But at least it may give you something to think about. This obviously doesn't work with closed orders, you will need to modify if you need to include closed orders.
Hi GumRai,
Thanks very much - it appears to be working correctly on backtester. I'll test on demo to be certain.
Your a legend, exactly what I was looking for.
Cheers
Richard
I have been looking for the same,for some time now. Did it work out well for you richy562?
Yes it all seems good
GumRai: I don't know whether this is the simplest way, but it should work.
SimplerNot compiled, not tested
See also Could EA Really Live By Order_History Alone? - MQL4 forum
//Function to find nTh order int Find2ndOrder(int nTh=0){ // 0 last int ticketarray[][2]; int count=0; for(int x=OrdersTotal()-1;x>=0;x--) if( OrderSelect(x,SELECT_BY_POS,MODE_TRADES)) && OrderMagicNumber()==MagicNumber ){ ArrayResize(ticketarray,count+1); ticketarray[count][0] = OrderOpenTime(); ticketarray[count][1] = OrderTicket(); ++count; } if(count<nTh) return(0); ArraySort(ticketarray, WHOLE_ARRAY, 0, MODE_DESCEND); return ticketArray[nTh][1]; }Not compiled, not tested

You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
Hi all,
Trying to make some code that uses OrderSelect() to get the ticket number of the 2nd last order that has been opened by my EA on the current pair. (EA has a magic number).
Looked around but everyone is just selecting the last order.
Thanks for any input.
Cheers
Richard