When coding your Strategy in Java it is important to be able to identify the orders that your Strategy 'owns' (i.e. created & is managing) - and not get those mixed up with Orders on the same Account that were created manually or by any other Strategy that is running at the same time.

So when you want to Count your Filled (and/or Pending) orders, or Close your open positions, you may need to ensure they were created by the ‘owning’ Strategy.

I do this by always creating Orders with a Label that starts with a unique Run_ID for the Strategy.
For example, take a Strategy called TrendRunner15b, I would set up a String identifying the Strategy Name & version, and then during onStart append the Start Date Time:

public class TrendRunner15b implements IStrategy {
public String Run_ID = "TR15b";
Run_Date = new SimpleDateFormat("yyMMdd_HHmmss").format(new Date());
Run_ID = Run_ID+"_"+Run_Date;

Then whenever I create an Order I construct the Label starting with this Run_ID and ending with a guaranteed unique number, as follows:

public String getLabel(Instrument instr) {
Lcount++;
return (Run_ID+"_"+instr.name()+Lcount+"_"+Long.toString(System.currentTimeMillis(),36));
}


In the middle I usually put the instrument name & an integer order counter for my own analysis purposes.
Now to identify Orders only created by the originating Strategy, I can test that the Order label starts with my Run_ID. I implement it like this to identify my Orders (e.g. to Count or Close):

private boolean isMyOrder(IOrder order) throws JFException {
if (order != null && order.getLabel().startsWith(Run_ID)) {
return true;
}
return false;
}

private int orderCount() throws JFException {
int Cntr=0;
for (IOrder order : engine.getOrders()) {
if (isMyOrder(order)) {
Cntr++;
}
}
return (Cntr);
}

private void closeAll() throws JFException {
if (engine.getOrders().size() == 0) return;
try {
for (IOrder order : engine.getOrders()) {
if (isMyOrder(order)) {
order.close();
order.waitForUpdate(2000, CLOSED, CANCELED);
}
}
} catch (Exception e) { console.getErr().println(e+" - closeAll error");}
}
Przetłumacz na Angielski Pokaż oryginał