IBAPI/TWS API异常循环:accountSummary被反复触发问题咨询
问题原因与解决方案
这是因为TWS API的reqAccountSummary请求默认是订阅模式——一旦发起请求,TWS会持续监控账户数据,只要账户信息有更新(哪怕是微小变动),或者每隔固定时间(就是你遇到的1-2分钟),就会主动推送账户汇总数据到accountSummary回调里,哪怕你只发起了一次请求。
解决办法:获取一次数据后主动取消订阅
你需要利用accountSummaryEnd回调——这个回调会在TWS完成当前批次的账户汇总数据推送后触发,此时调用cancelAccountSummary就能停止后续的自动推送,保证只打印一次数据,同时保持连接状态。
修改后的代码如下:
from time import sleep import ibapi from ibapi.client import * from ibapi.wrapper import * class BotApp(EClient, EWrapper): def __init__(self): EClient.__init__(self, self) def nextValidId(self, orderId: int): print("nextValidId", orderId) # 发起账户汇总请求 self.reqAccountSummary(1, "All", "NetLiquidation") def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str): super().accountSummary(reqId, account, tag, value, currency) print("AccountSummary. ReqId:", reqId, "Account:", account,"Tag: ", tag, "Value:", value, "Currency:", currency) def accountSummaryEnd(self, reqId: int): super().accountSummaryEnd(reqId) # 数据推送完毕后取消订阅,停止后续推送 self.cancelAccountSummary(reqId) print("已取消账户汇总订阅,后续不再接收推送") BotApp = BotApp() BotApp.connect(host="192.168.1.233", port=4002, clientId=166) BotApp.run()
补充说明
- 如果你之后还需要重新获取账户数据,可以再次调用
reqAccountSummary发起新的请求。 - 若你需要实时监控账户变动,那就保留订阅模式,不用取消,这样能及时收到数据更新。
内容的提问来源于stack exchange,提问作者orenong
相关产品推荐
相关产品推荐

