在以下代码中,我正在将数据收集到称为ohlcv的 Pandas 数据帧中,并将该应用程序运行到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

当我调用该函数时,代码运行良好,并且我将数据收集为pandas数据框。但是我得到以下错误,我想理解并找到避免该错误的方法:
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

最佳答案

ibapi软件包与套接字断开连接,但阅读器仍在尝试从套接字读取。源代码已被修改为仅捕获错误,但尚未将其发布。您可以按照此处的建议修改源代码。
https://groups.io/g/twsapi/message/42580

关于python - 我如何避免得到OSError : [Errno 9] Bad file descriptor using ibapi?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58619155/

10-12 02:37