TWS IB网关(版本972/974),客户端不断断开连接

问题描述 投票:0回答:1

我正在尝试与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

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

python client-server tws ib-api
1个回答
0
投票

如果您仅通过更改客户端ID即可毫无问题地进行连接,则通常表明先前的连接未正确关闭,并且TWS认为其仍处于打开状态。要断开API客户端的连接,您应该显式调用EClient.disconnect函数,该示例在您的示例中将其覆盖为:

test_app.disconnect()

尽管不必在每个任务之后都断开连接/重新连接,但是您可以长时间保持连接断开状态。

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.