python - 如何在 TWS API Python 中从历史数据返回值

标签 python interactive-brokers tws ib-api

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?
它现在没有给我任何东西。
任何帮助表示赞赏。
我错过了什么?

非常感谢。

最佳答案

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

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

关于python - 如何在 TWS API Python 中从历史数据返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60287712/

相关文章:

python - ibpy:提取多个合约的 API 响应

Python - 如何知道 Matlab 是否提示缺少免费网络许可证

interactive-brokers - 盈透证券交易代码列表

python - 使用 python ibPy 库获取你的投资组合的位置

python - 如何从盈透证券获取证券的 ISIN?

python-3.x - 使用 native TWS Python APi(Interactive Brokers API),如何在变量中获取证券列表的价格快照?

python - TWS API(盈透证券)-如何捕获事件并下订单

python - 如何使用Python编写 "Hello World"RESTful API然后使用它

python - 在 Python 中反转行和列转换

python - 将字符串列表转换为 int 或 float