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

无法通过Python API连接Interactive Brokers TWS问题求助

无法连接Interactive Brokers TWS API的问题排查

问题详情

我尝试使用以下Python代码通过API连接Interactive Brokers的TWS:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper


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


# 建立API连接
# app.connect(ipAddress, portNumber, clientId)
app = App()
app.connect("127.0.0.1", 7497, 999)
app.run()

运行代码后出现如下错误:

ERROR -1 502 Couldn't connect to TWS. Confirm that "Enable ActiveX and Socket EClients" 
is enabled and connection port is the same as "Socket Port" on the 
TWS "Edit->Global Configuration...->API->Settings" menu. Live Trading ports: 
TWS: 7496; IB Gateway: 4001. Simulated Trading ports for new installations 
of version 954.1 or newer:  TWS: 7497; IB Gateway: 4002

我已开启"Enable ActiveX and Socket EClients"并将端口设置为7497,且同一代码在其他电脑可正常连接,请问该问题是否与我的设备有关?该如何解决?

排查与解决步骤

  • 确认TWS登录状态:必须确保TWS客户端处于已登录状态,未登录时API连接会被直接拒绝。
  • 检查防火墙/杀毒软件拦截:本地防火墙或杀毒软件可能阻断了7497端口的连接,可临时关闭防火墙或将Python程序加入信任列表后重试。
  • 验证端口占用情况:
    • Windows系统:执行命令netstat -ano | findstr :7497查看端口是否被其他进程占用
    • Mac/Linux系统:执行命令lsof -i :7497查看端口占用情况
      若端口被占用,更换未被使用的端口(需同时修改TWS配置和代码中的端口号)。
  • 检查TWS API的IP访问权限:在TWS的API设置中,若未勾选"Allow connections from localhost only",需确认IP白名单包含本地IP(127.0.0.1);若勾选此选项,确保代码中使用的是127.0.0.1而非其他IP。
  • 重启相关程序:重启TWS客户端和Python运行环境,清除临时进程或缓存导致的异常。
  • 确认版本兼容性:确保本地安装的ibapi库版本与TWS客户端版本匹配,可通过pip install ibapi --upgrade升级库版本后重试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:23:27