跳转到内容

使用 Client Portal Gateway 建立 WebSocket

Client Portal Gateway 模式适合个人开发和桌面环境调试。用户在浏览器登录 Gateway,程序再连接这套 Gateway 暴露的 WebSocket 地址。

  1. 启动 Gateway。
  2. 浏览器打开 https://localhost:5000
  3. 输入 IBKR 用户名、密码并完成 2FA。
  4. 调用 /iserver/auth/status,确认 authenticated=trueconnected=true
  5. 连接 wss://localhost:5000/v1/api/ws
  6. 发送 topic,例如 ech+hbsmd+265598+{"fields":["31"]}

先安装 WebSocket 客户端库:

Terminal window
python -m pip install websocket-client
import ssl
import websocket
WS_URL = "wss://localhost:5000/v1/api/ws"
def on_open(ws):
# 发送心跳,确认 WebSocket 后端链路可用
ws.send("ech+hb")
def on_message(ws, message):
# 返回内容可能是行情、心跳、错误或系统消息,真实项目里应按 topic / message 字段分派处理
print(message)
def on_error(ws, error):
print("WebSocket error:", error)
def on_close(ws, status_code, reason):
print("WebSocket closed:", status_code, reason)
ws = websocket.WebSocketApp(
WS_URL,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close,
)
# 仅限开发调试;Gateway 默认自签名证书会导致普通证书校验失败。
# 正式环境请配置受信任证书,不要无条件关闭证书校验。
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

运行后如果只能看到连接建立但没有业务消息,先发送 ech+hb 检查链路,再发送具体 topic,例如行情 smd+265598+{"fields":["31"]}

问题说明
WebSocket 连接不等于已经授权连接后还要发送 topic 才会触发后端事件。
REST 会话和 WebSocket 心跳是两回事/tickle 维持 Gateway / REST 会话,ech+hb 检查 WebSocket 连接。
Gateway 每天需要重新认证IBKR 通常要求至少每日重新登录。
浏览器登录状态很关键如果 Gateway 页面退出,WebSocket 也会失效。
账号信息不要写进代码用户名、密码和 cookie 都不应硬编码。