如何避免使用ibapi得到OSError:[Errno 9]错误的文件描述符?

2024-04-26 02:32:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我将数据收集到名为ohlcv的dataframe作为函数,并将应用程序抛出到ib服务器:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
from ibapi.common import * #for TickerId type

import pandas as pd
from socket import error as SocketError
import errno

def read_ohlcv(reqId, symbol, sec_type, exch, prim_exch, curr, durationStr, barSizeSetting):

    contract = Contract()
    contract.symbol = symbol
    contract.secType = sec_type
    contract.exchange = exch
    contract.primaryExchange = prim_exch
    contract.currency = curr

    class TestApp(EWrapper, EClient):

        def __init__(self):
            EClient.__init__(self,self)

            self.historicaldata = pd.DataFrame([], columns = ['Open', 'High', 'Low', 'Close', 'Volume'])


        def error(self, reqId:TickerId, errorCode:int, errorString:str):
            if reqId > -1:
                print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)

        def historicalData(self,reqId, bar):

            self.historicaldata.index.name = 'Date'
            self.historicaldata.loc[bar.date] = bar.open, bar.high, bar.low, bar.close, bar.volume 

        def historicalDataEnd(self, reqId: int, start: str, end: str):
            super().historicalDataEnd(reqId, start, end)
            print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
            self.disconnect()


    app = TestApp()
    app.connect('127.0.0.1', 7497, 0)

    app.reqHistoricalData(reqId = reqId, 
                            contract = contract, 
                            endDateTime = '', 
                            durationStr = durationStr, 
                            barSizeSetting = barSizeSetting, 
                            whatToShow = 'TRADES',
                            useRTH = 1, # =1 for RTH data
                            formatDate = 1,
                            keepUpToDate = False,
                            chartOptions = [])

    ohlcv = app.historicaldata
    app.run()
    sleep(5)

    return ohlcv

当我调用函数时,代码运行良好,我将数据收集为dataframe。然而,我得到以下错误,我想了解并找到一种方法来避免它:

unhandled exception in EReader thread
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/ibapi/reader.py", line 34, in run
    data = self.conn.recvMsg()
  File "/usr/local/lib/python3.6/dist-packages/ibapi/connection.py", line 99, in recvMsg
    buf = self._recvAllMsg()
  File "/usr/local/lib/python3.6/dist-packages/ibapi/connection.py", line 119, in _recvAllMsg
    buf = self.socket.recv(4096)
OSError: [Errno 9] Bad file descriptor

Tags: infromimportselfappdeftypebar
1条回答
网友
1楼 · 发布于 2024-04-26 02:32:46

ibapi包与套接字断开连接,但读取器仍在尝试从套接字读取。源代码已经过修改,只是为了捕捉错误,但还没有发布。您可以像这里建议的那样修改源代码。 https://groups.io/g/twsapi/message/42580。你知道吗

相关问题 更多 >