我正在撰寫一個服務來通過基于 Python 語言的 TWS API 作業。獲取歷史資料時遇到問題。底線是,當您使用正確的引數請求 app.reqHistoricalData() 時,腳本運行沒有問題并在執行后退出。如果將錯誤引數傳遞給 app.reqHistoricalData()(例如,contract.currency = 'US'),那么在這種情況下,我會在控制臺中收到錯誤“ERROR 123 321 Request validation failed. -'bS':原因 -不允許使用美元”。腳本不會結束并在此狀態下掛起,直到手動停止。也許您遇到過這樣的問題,可以建議如何處理這種情況?下面是我的腳本的代碼。
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import Order
import pandas as pd
import threading
import time
class IBapi(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.open_orders = list()
self.historical_data = list()
self.df = None
self.data_end = False
def nextValidId(self, orderId: int):
super().nextValidId(orderId)
self.nextorderId = orderId
print('The next valid order id is: ', self.nextorderId)
def openOrder(self, orderId, contract, order, orderState):
# print('OpenOrder ID:', orderId, contract.symbol, contract.secType, '@', contract.exchange, ':', order.action,
# order.orderType, order.totalQuantity, orderState.status)
self.open_orders.append(('OpenOrder ID:', orderId, contract.symbol, contract.secType, '@',
contract.exchange, ':', order.action, order.orderType, order.totalQuantity,
orderState.status))
def historicalData(self, reqId, bar):
self.historical_data.append(vars(bar))
def historicalDataUpdate(self, reqId, bar):
line = vars(bar)
self.df.loc[pd.to_datetime(line.pop('date'))] = line
def historicalDataEnd(self, reqId: int, start: str, end: str):
self.df = pd.DataFrame(self.historical_data)
self.data_end = True
class Connect:
app = None
def __init__(self):
self.app = IBapi()
self.app.connect('127.0.0.1', 7497, 123)
# self.app.nextorderId = None
# Start the socket in a thread
api_thread = threading.Thread(target=self.run_loop, daemon=True)
api_thread.start()
time.sleep(1) # Sleep interval to allow time for connection to server
print('Соединились')
def run_loop(self):
self.app.run()
def get_historical_data(symbol, sectype, exchange, currency, duration=None, barsize=None,
whattoshow=None, enddatetime=None, userth=None, format_date=None) -> list:
print('\nGET HISTORY\n-------------------------------')
app = Connect().app
contract = Contract() # Создание объекта Contract, который описывает интересующий актив
contract.symbol = symbol # символ актива
contract.secType = sectype # 'CASH' # тип ценной бумаги
contract.exchange = exchange # 'IDEALPRO' # биржа
contract.currency = currency # 'USD' # валюта базового актива
if format_date is None:
format_date = 1 # 1- datetime, 2 - unix
if enddatetime is None:
enddatetime = ''
if barsize is None:
barsize = '1 hour'
if duration is None:
duration = '1 D'
if whattoshow is None:
whattoshow = 'BID'
if userth is None:
userth = 1 # 1 - обычные торговые часы, 0 - предторговля
app.reqHistoricalData(reqId=123, contract=contract, endDateTime=enddatetime, durationStr=duration,
barSizeSetting=barsize, whatToShow=whattoshow, useRTH=userth, formatDate=format_date,
keepUpToDate=False, chartOptions=[])
while not app.data_end:
time.sleep(1)
result = app.df.to_dict('records')
print(result)
app.disconnect()
return result
if __name__ == '__main__':
# get_historical_data(symbol='EUR', sectype='CASH', exchange='IDEALPRO', currency='USD')
get_historical_data(symbol='EUR', sectype='CASH', exchange='IDEALPRO', currency='US') # wrong params
uj5u.com熱心網友回復:
data_end僅設定為 True ,historicalDataEnd因此如果出現錯誤,它將永遠不會被呼叫,并且程式將永遠休眠。
從不使用睡眠的另一個原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532678.html
