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

标签 python-3.x interactive-brokers tws

我是 Python 的新手,我想使用本地 TWS Python API (Interactive Brokers API) 在变量中获取证券列表的价格快照。 例如,对于 APPL、AMZN 和 NFLX 股票,我想获得类似于 snaphot = ['APPL', 195.2, 'AMZN', 1771.5, 'NFLX', 306] 的内容。

预先感谢您的帮助。

我发现 Interactive Brokers 的指南难以理解且缺乏示例。 他们提供的一个示例仅适用于一只股票,并且它永远不会停止运行。

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

import time

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

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

    def tickPrice(self, reqId, tickType, price, attrib):
        print("Tick Price. Ticker Id:", reqId, "tickType:",
TickTypeEnum.to_str(tickType), "Price:", price, end=' ')

    def tickSize(self, reqId, tickType, size):
        print("Tick Size. Ticker Id:", reqId, "tickType:",
TickTypeEnum.to_str(tickType), "Size:", size)

def main():
    app = TestApp()

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


    time.sleep(0.1)

    contract = Contract()
    contract.secType = "FUT"
    contract.exchange = "DTB"
    contract.currency = "EUR"
    contract.localSymbol = "FDXM SEP 19"

    app.reqMarketDataType(4) # 1 for live, 4 for delayed-frozen data if live is not available
    app.reqMktData(1, contract, "", True, False, [])

    app.run()

if __name__ == "__main__":
    main()

最佳答案

您只需要为股票定义合约对象,例如

Contract definition examples

appl_contract = Contract()
appl_contract.symbol = "AAPL"
appl_contract.secType = "STK"
appl_contract.exchange = "SMART"
appl_contract.primaryExchange = "ISLAND"
appl_contract.currency = "USD"

然后对每个 Contract 对象调用 reqMktData,为每个未完成的请求使用唯一的 tickerId 参数(意味着请求仍然有效)。在 tickPrice 回调中,您收到返回的价格数据,并使用 tickerId 将数据与原始请求匹配。如果您只想要最后交易价格,您可以过滤 tickType == 4。

Tick type definitions

在您收到列表中最后一个仪器的数据后,如果您想断开连接/结束程序,您可以调用 disconnect()。

您可能还对 Python TWS API Traders Academy Course 感兴趣在 IBKR 网站上:

关于python-3.x - 使用 native TWS Python APi(Interactive Brokers API),如何在变量中获取证券列表的价格快照?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57395772/

相关文章:

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

java - 来自交互式代理 API 的随机响应

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

django - python-social-auth 与 Django : ImportError: No module named 'social_django'

python-3.x - 从 pandas 数据框中删除\n 的问题

python - reqHistoricalData() 使用 IBpy 返回空值?

python-3.x - 如何将嵌入式列与 Keras 中的其他输入数据组合

python - 如何在 Python 中检查电子邮件是否存在?

java - Interactive Brokers 订单在 Gateway 和 TWS 中同步吗?