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

在Jupyter Notebook中通过API连接IB TWS报错Error 1 504排查

问题原因分析及解决方案

核心原因:代码错误

你遇到的Error 1 504 Not connected主要是代码逻辑错误导致的,具体问题如下:

  • 线程未实际启动:api_thread.start缺少括号,正确写法是api_thread.start()。这会导致IB的消息循环根本没运行,无法和TWS/IB Gateway建立有效连接,直接触发连接错误。
  • 语法缩进错误:tickPrice方法里的print语句没有缩进,属于语法错误,会中断代码执行流程。
  • 连接等待逻辑不可靠:单纯依赖time.sleep(1)的固定时长,无法确保连接真正建立完成。

交易时段与Jupyter的影响

这两者并非当前问题的诱因:

  • 交易时段:即使不在美股交易时段,TWS/IB Gateway只会返回“市场关闭”类提示,不会抛出连接错误。
  • Jupyter Notebook:只要代码逻辑正确,Jupyter本身不会阻碍API连接,仅需注意内核未被其他任务阻塞即可。

修正后的代码

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

import threading
import time

class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.connected = False  # 添加连接状态标记

    def tickPrice(self, reqId, tickType, price, attrib):
        if tickType == 2 and reqId == 1:
            print('当前卖价为: ', price)  # 修复缩进

    def connectAck(self):
        self.connected = True  # 收到连接确认后标记状态

def run_loop():
    app.run()

app = IBapi()
app.connect('127.0.0.1', 7496, 10)

# 修复线程启动逻辑
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

# 等待连接确认,替代固定sleep
while not app.connected:
    time.sleep(0.1)

# 创建合约对象
apple_contract = Contract()
apple_contract.symbol = 'AAPL'
apple_contract.secType = 'STK'
apple_contract.exchange = 'SMART'
apple_contract.currency = 'USD'

# 请求市场数据
app.reqMktData(1, apple_contract, "", False, False, [])

time.sleep(10)  # 等待数据返回
app.disconnect()

额外检查项

  • 确认TWS/IB Gateway已启动,API端口设置为7496(实盘默认7496,模拟盘默认7497,不要混淆)。
  • 在TWS/IB Gateway的API设置中,勾选“Enable Active X and Socket Clients”,并允许本地IP连接。
  • 确保代码中的客户端ID(10)未被其他连接占用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:50:33