while (this.order.getState() == IOrder.State.CREATED || this.order.getState() == IOrder.State.OPENED){
order.waitForUpdate(2, TimeUnit.SECONDS, IOrder.State.FILLED );
}
If for some reason the order remains in state CREATED or OPENED, the above code is an
infinite loop. You have to avoid potentially infinite loops.
if (this.order != null && order.isLong()){
closeOrder();
print("Long position closed as SELL opportunity identified");
}
Once every
half hour when onBar is executed, the above code detects and attempts to close open order, but:
private void closeOrder() throws JFException{
if (this.order.getState() == IOrder.State.FILLED){
this.order.close();
order.waitForUpdate(2, TimeUnit.SECONDS, IOrder.State.CLOSED);
}
if (order.getState() == IOrder.State.CLOSED){
this.order = null;
}
}
The closeOrder method code, close
only filled trades, if not filled, the trade remains open. So you will be continuously repeated every half hour: "
Long position closed as SELL opportunity identified"
This method should be:
private void closeOrder() throws JFException{
if (order.getState() == IOrder.State.CLOSED){
this.order = null;
} else {
this.order.close();
order.waitForUpdate(2, TimeUnit.SECONDS, IOrder.State.CLOSED);
this.order = null;
}
}
Furthermore, the method isLong(), used in this way:
if (order.isLong()) ordps=1;
else ordps=-1;
It is not safe, and may cause errors when setting the TP and SL, should be implemented as follows:
if (order.getOrderCommand() == IEngine.OrderCommand.BUY) {
ordps=1;
} else if (order.getOrderCommand() == IEngine.OrderCommand.SELL) {
ordps=-1;
} else {
break; //if not BUY or SELL you not want that the FOR loop continues.
}
Best Regards.