Skip to content

Instantly share code, notes, and snippets.

@jshelton31
Created April 28, 2017 23:48
Show Gist options
  • Save jshelton31/cf48d284a105bfc8058f48be57869ccc to your computer and use it in GitHub Desktop.
Save jshelton31/cf48d284a105bfc8058f48be57869ccc to your computer and use it in GitHub Desktop.
Interactive Brokers Send Order with Trailing Stop
public void sendOrder(String orderSide, int parentOrderId) {
new Thread(() -> {
System.out.print("before getting ids, nextOrderID = " + nextOrderID + ", nextValidId_prev = " + nextValidId_prev);
while (nextOrderID == nextValidId_prev) {
System.out.print("waiting for next valid id...");
client.reqIds(1);
System.out.print("waiting for next valid id done");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("new nextOrderID = " + nextOrderID);
nextValidId_prev = nextOrderID;
System.out.print("sendOrder is called");
Order order = new Order();
order.action(orderSide);
order.totalQuantity(20000);
//log.info("sendOrder, this.high = " + this.high);
DecimalFormat df = new DecimalFormat("0.0000"); // TODO get digit according
df.setDecimalSeparatorAlwaysShown(true);
String formatedEntryPrice = df.format(this.high);
formatedEntryPrice = formatedEntryPrice.replace(",", ".");
System.out.print("formatedEntryPrice = " + formatedEntryPrice);
order.lmtPrice(Double.valueOf(formatedEntryPrice)); // TODO stop limit at prior day high
order.orderType("LMT");
order.account(twsAccountNumber);
//int randomNum = ThreadLocalRandom.current().nextInt(1, 5564 + 1);
//log.info("after creating order");
String trailingOrderSide = "";
if(orderSide.equals("SELL")){
trailingOrderSide = "BUY";
}else if(orderSide.equals("BUY")){
trailingOrderSide = "SELL";
}
Order trailOrder = new Order();
trailOrder.action(trailingOrderSide);
//trailOrder.auxPrice(Double.valueOf("1.07000"));
trailOrder.trailingPercent(1);
trailOrder.orderType("TRAIL");
trailOrder.totalQuantity(20000);
trailOrder.parentId(nextOrderID);
trailOrder.transmit(true);
///
// order.orderType("TRAIL");
// order.totalQuantity(20000);
// order.trailingPercent(1);
// order.trailStopPrice(low);
// stopLoss.parentId(nextOrderID);
// order.transmit(true);
//client.reqIds(1);
client.placeOrder(nextOrderID, contract, order);
client.placeOrder(nextOrderID + 1, contract, trailOrder);
//attachOrder();
}).start();
System.out.print("sendOrder is finished");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment