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

IB API TWS连接显示已接受却报504 Not connected错误求助

IB API 连接错误:-1 504 Not connected 问题解决

多次编写IB API代码(包括IBKR学院教程示例),均触发-1 504 Not connected error。已完成以下TWS全局设置检查:

  • 勾选Enable ActiveX & Socket
  • Socket端口设置为7497
  • Client ID与代码保持一致
  • 允许本地连接
  • 将127.0.0.1和localhost:5000添加至可信IP列表

TWS数据连接表显示端口7497、Client ID 1的连接已被接受,但运行代码无响应,调试时输出错误:

PS C:\TWS API\source\pythonclient\ibapi> & 'c:\Users\JV\AppData\Local\Programs\Python\Python312\python.exe' 'c:\Users\JV.vscode\extensions\ms-python.debugpy-2024.2.0-win32-x64\bundled\libs\debugpy\adapter/../..\debugpy\launcher' '60548' '--' 'c:\TWS API\source\pythonclient\tests\TestApp.py'

ERROR -1 504 Not connected

PS C:\TWS API\source\pythonclient\ibapi>

附问题代码

from ibapi.client import *
from ibapi.wrapper import *
import time

class TestApp(EClient, EWrapper):

    def __init__(self):
        EClient.__init__(self, self)

    def contractDetails(self, reqId, contractDetails):
        print(f"contract details: {contractDetails}")

    def contractDetailsEnd(self, reqId):
        print("End of contractDetails")
        self.disconnect()

def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 1)

    mycontract = Contract()
    mycontract.symbol = "AAPL"
    mycontract.secType = "STK"
    mycontract.exchange = "SMART"
    mycontract.currency = "USD"
    mycontract.primaryExchange = "ISLAND"

    time.sleep(3)

    app.reqContractDetails(1, mycontract)

    app.run

if __name__ == "__main__":
    main()

问题排查与修复方案

  1. 修复代码核心错误
    代码最后一行app.run缺少括号,必须调用app.run()启动API消息循环。没有这一步,API无法接收和处理TWS返回的数据,直接导致连接状态异常。

  2. 优化连接逻辑,移除无效sleep
    不要用time.sleep(3)等待连接,改用nextValidId回调确认连接成功后再发送请求,避免因连接未就绪导致的请求失败。修改后的代码示例:

from ibapi.client import *
from ibapi.wrapper import *

class TestApp(EClient, EWrapper):
    def __init__(self):
        EClient.__init__(self, self)
        self.next_order_id = None

    def nextValidId(self, orderId: int):
        self.next_order_id = orderId
        # 连接确认后再发起合约详情请求
        self.request_contract_details()

    def contractDetails(self, reqId, contractDetails):
        print(f"contract details: {contractDetails}")

    def contractDetailsEnd(self, reqId):
        print("End of contractDetails")
        self.disconnect()

    def request_contract_details(self):
        mycontract = Contract()
        mycontract.symbol = "AAPL"
        mycontract.secType = "STK"
        mycontract.exchange = "SMART"
        mycontract.currency = "USD"
        mycontract.primaryExchange = "ISLAND"
        self.reqContractDetails(1, mycontract)

def main():
    app = TestApp()
    app.connect("127.0.0.1", 7497, 1)
    app.run()  # 此处必须添加括号

if __name__ == "__main__":
    main()
  1. 验证TWS配置细节

    • 区分TWS版本:模拟版默认端口7497,实盘版默认7496,确认端口与使用版本匹配。
    • 清理可信IP:仅需添加127.0.0.1,无需附带端口(如localhost:5000是错误写法)。
    • 确保TWS已登录:未登录状态下,即使连接被接受也无法处理API请求。
  2. 检查Python环境兼容性
    IB API Python客户端与Python 3.12可能存在兼容性问题,建议降级到Python 3.10或3.11测试;同时确保IB API客户端版本与TWS版本一致。

内容的提问来源于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 19:33:17