盈透证券 Java API

Interactive Broker Java API

每次我向 IB 下新订单之前,我需要向 IB 请求下一个有效的 orderId,然后 Thread.Sleep(500) 休眠 0.5 秒并等待 IB API回调函数 nextValidId 到 return 最新的 orderID。如果我想下多个订单,那么我必须天真地多次执行 thread.sleep,这不是处理这个问题的好方法,因为 orderID 可能已经更早更新,因此新订单可能已经放置较早。如果 orderID 的更新时间比线程休眠时间长,这将导致错误。

有没有更高效、更优雅的方法来做到这一点?

理想情况下,我希望程序阻止 运行ning placeNewOrder,直到更新最新可用的 orderID,然后通知程序 运行 placeNewOrder.

我不太了解 Java 数据同步,但我认为使用 synchronizedwait-notifylocking 或 [=22= 可能会有更好的解决方案].

我的代码:

// place first order
ib_client.reqIds(-1);
Thread.sleep(500);
int currentOrderId = ib_wrapper.getCurrentOrderId();
placeNewOrder(currentOrderId, orderDetails); // my order placement method 
// place 2nd order
ib_client.reqIds(-1);
Thread.sleep(500);
int currentOrderId = ib_wrapper.getCurrentOrderId();
placeNewOrder(currentOrderId, orderDetails); // my order placement method 

IB 电子包装器:

public class EWrapperImpl implements EWrapper {
    ...
    protected int currentOrderId = -1;
    ...
    public int getCurrentOrderId() {
        return currentOrderId;
    }

    public void nextValidId(int orderId) {
        System.out.println("Next Valid Id: ["+orderId+"]");
        currentOrderId = orderId;
    }
    ...
}

您永远不需要索取身份证件。每个订单加一。

当您第一次连接时,nextValidId 是第一个或第二个要接收的消息,只需跟踪 id 并不断递增即可。

orderId 的唯一规则是使用整数并始终递增一定数量。这是每个 clientId,因此如果您连接到一个新的 clientId,那么最后一个 orderId 是其他东西。

我总是使用 max(1000, nextValidId) 来确保我的 ID 从 1000 或更多开始,因为我使用 <1000 进行数据请求。它只是帮助解决具有 ID 的错误。

您也可以通过某种方式重置序列。

https://interactivebrokers.github.io/tws-api/order_submission.html

This means that if there is a single client application submitting orders to an account, it does not have to obtain a new valid identifier every time it needs to submit a new order. It is enough to increase the last value received from the nextValidId method by one.