You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IB_Insync对接TWS首单正常后续订单失败问题求助

问题:TWS交易机器人首单正常后续订单失败

我正在开发基于IB_Insync、Asyncio、NGROK、Flask和Redis的TWS交易机器人,目前遇到以下问题:

  • 首条webhook负载可正常传输至TWS并下单,但后续订单均无法提交
  • 无报错信息,webhook数据可通过NGROK正常传输并在Asyncio中显示
  • 重启脚本后首单可恢复正常,但后续订单仍失败

起初怀疑是TWS需要唯一orderId,尝试了ib.client.getReqId()、IB_API的EWrapper nextValidID等方法,但无法在异步函数中生效。查阅IB_Insync作者Erwald deWit的说明,该库会自动分配唯一orderId,验证后每个订单确实有唯一ID,因此orderId并非问题所在。

现在怀疑问题出在异步函数内的下单逻辑,但缺乏相关经验无法调整代码。希望能排查代码问题,或提供将订单逻辑移出异步函数仍能接收消息数据的方案,也欢迎有类似经验的用户分享解决办法。

相关代码

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import Order
import redis, json
from ib_insync import *
import asyncio, time, random

class TradingApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def nextValidId(self, orderId):
        super().nextValidId(orderId)
        self.nextValidId = orderId
        print("NextValidId:", orderId)


# connect to Interactive Brokers 
ib = IB()
ib.connectAsync('127.0.0.1', 7497, clientId=1)

# connect to Redis and subscribe to tradingview messages
r = redis.Redis(host='localhost', port=6379, db=0)
p = r.pubsub()
p.subscribe('tradingview')

async def check_messages():
    print(f"{time.time()} - checking for tradingview webhook messages")
    message = p.get_message()
    if message is not None and message['type'] == 'message':
        print(message)

        message_data = json.loads(message['data'])

        future = Future(message_data ['ticker'], message_data['contractExpDate'], 'CME') # Future(message_data['ticker'], message_data['secId'], message_data['exchange']) 
        order = LimitOrder(message_data['strategy']['order_action'], message_data['strategy']['order_contracts'], message_data['strategy']['limit_price'])
        #order.orderId = ib.client.getReqId() # get new orderID
        #order = MarketOrder(message_data['strategy']['order_action'], message_data['strategy']['order_contracts'])
        trade = ib.placeOrder(future, order)

async def run_periodically(interval, periodic_function):
    while True:
        await asyncio.gather(asyncio.sleep(interval), periodic_function())

asyncio.run(run_periodically(1, check_messages))

ib.run()

内容的提问来源于stack exchange,提问作者Trent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:07:45