Python使用单个cod执行多个请求

2024-04-29 21:16:08 发布

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

我正在使用ibapi检索历史股票数据,我希望我的代码可以用不同的变量(不同的股票和时间段)运行多次。在

目前我正在使用以下代码:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract


def print_to_file(*args):
    with open('text6.txt', 'a') as fh:
        fh.write(' '.join(map(str,args)))
        fh.write('\n')
print = print_to_file


class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)


    Layout = "{!s:1} {!s:2} {!s:3} {!s:4} {!s:5} {!s:6} {!s:7} {!s:8} {!s:8} '\n'"
    print(Layout.format("Ticker;", "Date;", "None;", "Time;", "Open;", "High;", "Low;", "Close;", "Volume"))


    def historicalData(self, reqId, bar):
        print("AAPL", ";", bar.date.replace(' ', '; '), ";", bar.open, ";", bar.high, ";", bar.low, ";", bar.close, ";", bar.volume)


def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)

    contract = Contract ()
    contract.symbol = "AAPL"
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"

    app.reqHistoricalData(0, contract, "20180201 10:00:00", "1 M", "1 min", "TRADES", 0, 1, False, [])

    app.run()

if __name__ == "__main__":
    main()

我尝试过以下几种股票:

^{2}$

但这给了我一个错误信息:

No security definition has been found for the request

并使用以下代码表示时间和日期:

app.reqHistoricalData(0, contract, ["20180201 10:00:00", "20180301 10:00:00"], "1 M", "1 min", "TRADES", 0, 1, False, [])

显示错误消息:

Error validating request:-'bP' : cause - Historical data query end date/time string [['20180201 10:00:00', '20180301 10:00:00']] is invalid.  Format is 'YYYYMMDD{SPACE}hh:mm:ss[{SPACE}TMZ]'.

基本上,我希望这个.py文件在一次运行中运行多个请求,使用多个变量,这样我就可以在一次运行中接收多个股票的数据。在

这里有人能帮我实现这个目标吗?在

谢谢!在


Tags: 数据代码fromimportselfappmaindef
1条回答
网友
1楼 · 发布于 2024-04-29 21:16:08

您可以创建从协定类派生的类,以便一次创建多个协定对象。然后,创建一个循环,将契约对象传递到客户端以获取数据。您当前所做的与任何实际可行的实现相差甚远。查看此博客以获取有关工作系统设置的帮助->;https://qoppac.blogspot.com/2017/03/interactive-brokers-native-python-api.html 至于contract类,请查看文档中的相关参数,并根据需要创建一个类。下面是我的未来课程的一个例子:

class IBFutures(Contract):
    def __init__(self, symbol:str,  exchange:str, secType:str,
                 currency = 'USD', localSymbol = ""):
        Contract.__init__(self)

        self.symbol = symbol
        self.secType = secType
        self.exchange = exchange
        self.currency = currency
        self.localSymbol = localSymbol

然后,在客户端对象中,创建一个类似于以下内容的函数:

^{pr2}$

相关问题 更多 >