【问题标题】:How to return values from historicalData in TWS API Python如何在 TWS API Python 中从历史数据返回值
【发布时间】:2020-06-02 21:02:19
【问题描述】:
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from threading import Timer

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

    def error(self, reqId, errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)

    def nextValidId(self, orderId):
        self.start()

    def historicalData(self, reqId, bar):
        # print("HistoricalData. ", reqId, " Date:", ...., bar.average)
        return bar.high


    def start(self):
        contract = Contract()
        contract.symbol = "TSLA"
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
       x = self.reqHistoricalData(1, contract, "", "60 s", "1 min", "MIDPOINT", 0, 1, False, [])
        print(x)


    def stop(self):
        self.done = True
        self.disconnect()
def main():
    app = TestApp()
    app.nextOrderId = 0
    app.connect("127.0.0.1", 7497, 0)

    Timer(4, app.stop).start()
    app.run()


if __name__ == "__main__":
    main()

在这种情况下,我怎样才能返回 bar.high,而不是打印 HistoricalData?
它现在没有给我任何东西。
任何帮助表示赞赏。
我错过了什么?

非常感谢。

【问题讨论】:

    标签: python interactive-brokers tws ib-api


    【解决方案1】:

    您已向historicalData 添加了一个返回值,并希望通过reqHistoricalData 访问它。但它们是完全不同的功能。除非您愿意重写 API 的类,否则您不能像普通函数那样调用 historicalData。所以你不能访问它的返回值。

    在我的代码中,我使用像historicalData 这样的回调函数来设置包含类的成员变量。然后,在主线程中等待几秒钟后,我访问变量以获取历史数据。

    【讨论】:

    • 如何使用historyData这样的回调函数来设置包含类的成员变量?
    • 与常规变量不同,类内部的实例变量前面有self,代表类。你可以找到更多here。例如,您可以通过在__init__ 中插入self.high = 0.0 来定义一个名为high 的实例变量。然后,在historicalData 中,您可以设置self.high = bar.high。最后,等待数据到达后,您可以通过实例的high 变量访问该值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2020-10-28
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2013-08-29
    相关资源
    最近更新 更多