跳转到内容

请求管理账户

reqManagedAccts() 用来请求登录会话可见的账户列表。它没有参数,也不需要 reqId

app.reqManagedAccts()

请求成功后,TWS 会调用:

managedAccounts(accountsList)
检查项原因
TWS 或 IB Gateway 已登录账户列表来自登录会话
API Socket 已开启程序需要能连接到 TWS API 端口
已收到 nextValidId()表示基础连接已经可用
日志具备脱敏逻辑回调会返回真实账户号

这个接口一般不需要市场数据订阅,也不涉及交易权限。但如果账户权限、登录状态或 API 设置异常,可能收不到回调。

连接 TWS / IB Gateway
-> 等待 nextValidId()
-> reqManagedAccts()
-> managedAccounts(accountsList)
-> 解析账户列表
-> disconnect()

因为没有 reqId,程序通常用事件或状态变量等待 managedAccounts() 回调到达。

import threading
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
INFO_CODES = {2100, 2104, 2106, 2158}
class RequestManagedAccountsApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.ready = threading.Event()
self.managed_ready = threading.Event()
self.account_count = 0
self.info_codes = []
self.errors_seen = []
def nextValidId(self, orderId):
self.ready.set()
def managedAccounts(self, accountsList):
accounts = [item for item in (accountsList or "").split(",") if item]
self.account_count = len(accounts)
self.managed_ready.set()
def error(self, reqId, errorTime, errorCode, errorString, advancedOrderRejectJson=""):
if errorCode in INFO_CODES:
self.info_codes.append(errorCode)
else:
self.errors_seen.append((reqId, errorCode, errorString))
app = RequestManagedAccountsApp()
try:
app.connect("127.0.0.1", 7497, clientId=982)
thread = threading.Thread(target=app.run, daemon=True)
thread.start()
if not app.ready.wait(8):
raise RuntimeError("等待 nextValidId 超时")
app.reqManagedAccts()
callback_received = app.managed_ready.wait(8)
finally:
if app.isConnected():
app.disconnect()
print("REQUEST_SENT=True")
print(f"MANAGED_CALLBACK_RECEIVED={callback_received}")
print(f"ACCOUNT_COUNT={app.account_count}")
print("INFO_CODES=" + (",".join(map(str, sorted(set(app.info_codes)))) if app.info_codes else "NONE"))
print(f"NON_INFO_ERROR_COUNT={len(app.errors_seen)}")
print(f"IS_CONNECTED_AFTER_DISCONNECT={app.isConnected()}")
REQUEST_SENT=True
MANAGED_CALLBACK_RECEIVED=True
ACCOUNT_COUNT=1
INFO_CODES=2104,2106,2158
NON_INFO_ERROR_COUNT=0
IS_CONNECTED_AFTER_DISCONNECT=False

请求页只验证请求是否发出、回调是否到达和返回账户数量。真实账户号的解析和脱敏展示放在接收页讲。

账户列表由 TWS 登录会话决定,不需要你传账户号。程序只要连接到正确的 TWS 或 IB Gateway,就能请求可见账户。

reqManagedAccts() 不是持续订阅型接口。它请求一次、返回一次账户列表,不需要取消。

建议等 nextValidId() 到达后再调用。这样能避免连接刚建立、事件循环还没准备好时发业务请求。

IBKR Campus: TWS API Documentation