开云体育

ctrl + shift + ? for shortcuts
© 2025 开云体育

Re: Duplicate Order ID


 

The group cannot fix large chunks of code for you, but I hope we can give you pointers so you can do that yourself. In that spirit a few observations.

TWS log is always very helpful since it tells you what is going on from the TWS/IBGW point of view. But it does not tell you why your client makes these requests so you will need to find a way to add logging to your code. It is very unlikely that the source of and reason for the second order request is anywhere other than in your VBA code.

One area I'd review is the code that determines the next order ID. As the chapter of the API Reference Guide suggests, clients generally maintain their own sequence of order IDs and do not make API calls for the nextOrderId unless they somehow lose the sequence. During the initial connection request, clients are automatically informed of the next valid order ID and, from that point on, simply increment an internal nextOrderId field as needed. Doing so would reduce your order placement complexity (and increase the speed) since you eliminate the request-wait-response cycle through the API and all the way to TWS/IBGW. According to the logs it currently takes nearly three seconds from when TWS sends the nextValidOrderId to when it sees the first placeOrder request.

And finally (frequent readers of my posts will know where this is going - so hold on to your seats) a big red flag is when you say "First i make a request ... [then]? I'm waiting 1 sec for the answer ". That is wrong and I would not be surprised if this contributes to your code placing two identical orders. The TWS API is event driven and completely asynchronous with no guarantee as to the time it takes between a request and the corresponding answer nor to the order in which answers arrive in case there are multiple outstanding requests or subscriptions to data feeds. Your code needs to be structured event oriented as well and needs to wait for the arrival of a callback (or the corresponding error) and not sleep for a fix period of time after the request.

When sleep is used to synchronize requests and responses you'd expect to get exactly what you see: 99% of the time it works correctly and some times it does not. That is when the "sleep" time was too short and the response had not come in yet. And the fix is not to simply increase the sleep time. The fix is to restructure the code and to eliminate the "sleep".

By maintaining the nextOrderId in your client you will naturally avoid this issue, but it would still be interesting for you to review your current code to see what happens if the "sleep 1 second" expires before the nextOrderId callback has come in. Will your code place two orders? One right after the sleep and one triggered by when the nextOrderId callback comes later?

Hope this helps,

闯ü谤驳别苍

Join [email protected] to automatically receive all group messages.