[英]Interactive Brokers API (IBAPI) - Using threading.Timer object to auto exit when the data connection is broken
我一直在嘗試實現一種請求實時數據的機制(例如reqRealTimeBars
)並自動使腳本退出以防數據連接中斷。
我一直在用threading.Timer
object ( https://docs.python.org/3/library/that script顯示腳本很好的方向) ) 就像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。 那會斷開連接。 通常在 10 秒后,尚未“刷新”的計時器應該觸發exit
function 並使程序停止,就像上面的示例一樣。 但是,它只是保持空閑狀態,仍在等待傳入的數據。 如果有人可以看看,那就太棒了。
我認為這種技術可能是一種非常靈活且很好的方法,可以使任何實時數據收集應用程序變得健壯。 它只需要與每 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()
請注意,我已經進行了試驗,我將超時設置為 < 5s(例如 3s)的值 - 在這種情況下,腳本確實將 thx 退出到計時器......
這並不是對上述問題的真正答案,但對元問題的元答案是:使用ib-insync
並快樂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.