0

我正在尝试连接 IB Api 以下载一些历史数据。我注意到我的客户端连接到 API,然后在很短的时间内(约几秒钟)自动断开连接。

这是服务器中的日志:

socket connection for client{10} has closed.
Connection terminated.

这是我启动应用程序的主要代码:

class TestApp(TestWrapper, TestClient):
 def __init__(self):
    TestWrapper.__init__(self)
    TestClient.__init__(self, wrapper=self)
    self.connect(config.ib_hostname, config.ib_port, config.ib_session_id)
    self.session_id = int(config.ib_session_id)
    self.thread = Thread(target = self.run)
    self.thread.start()
    setattr(self, "_thread", self.thread)
    self.init_error()

 def reset_connection(self):
    pass

 def check_contract(self, name, exchange_name, security_type, currency):
    self.reset_connection()
    ibcontract = IBcontract()
    ibcontract.secType = security_type
    ibcontract.symbol = name
    ibcontract.exchange = exchange_name
    ibcontract.currency = currency
    return self.resolve_ib_contract(ibcontract)

def resolve_contract(self, security):
    self.reset_connection()
    ibcontract = IBcontract()
    ibcontract.secType = security.security_type()
    ibcontract.symbol=security.name()
    ibcontract.exchange=security.exchange()
    ibcontract.currency = security.currency()
    return self.resolve_ib_contract(ibcontract)

 def get_historical_data(self, security, duration, bar_size, what_to_show):
    self.reset_connection()
    resolved_ibcontract=self.resolve_contract(security)
    data = test_app.get_IB_historical_data(resolved_ibcontract.contract, duration, bar_size, what_to_show)
    return data



def create_app():
 test_app = TestApp()
 return test_app

关于可能是什么问题的任何建议?如果需要,我可以从调试中显示更多错误消息。

4

2 回答 2

1

如果您仅通过更改客户端 ID 就可以毫无问题地连接,通常这表明之前的连接没有正确关闭并且 TWS 认为它仍然处于打开状态。要断开 API 客户端,您应该显式调用 EClient.disconnect 函数,在您的示例中重写为:

test_app.disconnect()

虽然不必在每项任务后断开/重新连接,但您可以长时间保持连接打开。

如果在连接后立即调用 API 函数(例如 reqHistoricalData),您有时可能会遇到问题。最好在启动连接后稍作停顿以等待回调,nextValidID以确保连接完成后再继续。

http://interactivebrokers.github.io/tws-api/connection.html#connect

我不确定该函数init_error()在您的示例中的用途是什么,因为它总是在创建 TestApp 对象时被调用(无论是否有错误)。

于 2020-04-11T23:13:12.163 回答
0

安装最新版本的 TWS API (v 9.76) 解决了这个问题。

https://interactivebrokers.github.io/#

于 2020-04-12T12:35:45.497 回答