Also do some manual trading while running the strategy:
package jforex.orders;
import java.util.ArrayList;
import java.util.List;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.*;
/**
* The strategy demonstrates how to detect if an order got
* closed by the strategy itself or the close was done manually
* or from another strategy.
*
* Test its work by doing some manual trading in parallel.
*
*/
public class OrderClosedByStrategy implements IStrategy {
private IConsole console;
private IEngine engine;
private int counter;
List<IOrder> ordersClosedByStrategy = new ArrayList<IOrder>();
@Override
public void onStart(IContext context) throws JFException {
console = context.getConsole();
engine = context.getEngine();
}
@Override
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if(instrument != Instrument.EURUSD || period != Period.TEN_SECS){
return;
}
IOrder order = engine.submitOrder("myOrder"+counter++, Instrument.EURUSD, OrderCommand.BUY, 0.1, 0, 20, 0, 0, 0, this.getClass().getSimpleName() + " order");
order.waitForUpdate(2000, IOrder.State.FILLED); //wait for fill to close it
close(order);
}
private void close(IOrder order) throws JFException{
order.close();
ordersClosedByStrategy.add(order);
}
private void print(Object o){
console.getOut().println(o);
}
@Override
public void onMessage(IMessage message) throws JFException {
IOrder order = message.getOrder();
if(order == null || message.getType() != IMessage.Type.ORDER_CLOSE_OK){
return;
}
if(ordersClosedByStrategy.contains(order)){
print(String.format("order %s with comment \"%s\" was closed by strategy!", order, order.getComment()));
ordersClosedByStrategy.remove(order);
} else {
print(String.format("order %s was either closed manually or by another strategy!", order));
}
}
@Override
public void onTick(Instrument instrument, ITick tick) throws JFException {}
@Override
public void onAccount(IAccount account) throws JFException {
// TODO Auto-generated method stub
}
@Override
public void onStop() throws JFException {
// TODO Auto-generated method stub
}
}
See more on closing orders:
https://www.dukascopy.com/wiki/#Close_OrdersManaging orders:
https://www.dukascopy.com/wiki/#Order_ManagementAnd managing order state:
https://www.dukascopy.com/wiki/#Manage_Order_State