gpt4 book ai didi

python - Interactive Brokers API (IBAPI) - 使用 threading.Timer 对象在数据连接断开时自动退出

转载 作者:行者123 更新时间:2023-12-05 07:06:34 31 4
gpt4 key购买 nike

我一直在尝试实现一种请求实时数据(例如 reqRealTimeBars)并在数据连接断开时自动退出脚本的机制。

我一直在用 threading.Timer 对象 ( https://docs.python.org/3/library/threading.html#timer-objects ) 进行测试,在这个方向上显示出良好的前景:例如,该脚本(如下)是一个无限循环,就像 Eclient.run() 一样,但它会在 3 秒后退出,正如计时器所预期的那样

import threading
import time
import sys
import _thread

def exit():
_thread.interrupt_main()

if __name__ == '__main__':
t = threading.Timer(3.0, exit)
t.start()
while True:
time.sleep(3)

但是,当我尝试将相同的逻辑应用于 Eclient 本身时,它似乎不起作用。下面是我的代码的简化版本。逻辑是当应用程序启动时,计时器设置为 10 秒的超时(或任何超过实时条之间 5 秒时间跨度的持续时间)。然后,每次收到新柱时,计时器将被取消,然后以相同的超时时间重新创建。这意味着通常代码永远不会达到超时,除非与 tws 服务器的连接断开。

要测试下面的代码:启动他的 tws,然后启动这个脚本。它应该开始在控制台中打印数据。然后,手动关闭 tws。那将断开连接。通常在 10s 之后,还没有“刷新”的计时器应该触发 exit 函数并使程序停止,就像上面的例子一样。但是,它只是保持空闲状态,仍在等待传入的数据。如果有人可以看看,那就太棒了。

我认为这种技术可能是一种非常灵活且不错的方法,可以使任何实时数据收集应用程序变得健壮。它只需要与每 x 分钟运行一次该脚本的 cronjob 相结合,然后在开始时添加一些额外的逻辑以防止它再次运行,以防它已经这样做了。

from ibapi.wrapper import EWrapper
from ibapi.client import EClient
from ibapi.contract import Contract
from datetime import timedelta, datetime as dt

import threading
import _thread


def exit():
_thread.interrupt_main()


class App(EWrapper, EClient):

def __init__(self):
EWrapper.__init__(self)
EClient.__init__(self, wrapper=self)
self.timeout = threading.Timer(10.0, exit)
self.timeout.start()


def realtimeBar( self, reqId, datetime, open_, high, low, close, volume, wap, count):
bar = {
'open' : open_,
'high' : high,
'low' : low,
'close' : close,
'volume' : volume
}
print(bar)
self.refresh_timeout(reqId)


def refresh_timeout(self, reqId):
self.timeout.cancel()
self.timeout = threading.Timer(10.0, exit)
self.timeout.start()


def make_contracts(app):
contract = Contract()
contract.__dict__.update({'symbol' : 'CL', 'exchange' : 'NYMEX', 'secType': 'FUT', 'lastTradeDateOrContractMonth' : '202008'})
app.reqRealTimeBars(i, contract, 5, "TRADES", 0, [])


if __name__ == '__main__':
app = App()
app.connect("127.0.0.1", 4002, clientId=0)
make_contracts(app)
app.run()

请注意,我已经做了一个试验,我将超时设置为小于 5 秒的值(例如 3 秒)——在这种情况下,脚本确实会退出计时器……

最佳答案

这并不是对问题的真正回答,但元问题的元答案是:使用 ib-insync并快乐。

关于python - Interactive Brokers API (IBAPI) - 使用 threading.Timer 对象在数据连接断开时自动退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62420129/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com