【问题标题】:Using the native TWS Python APi (Interactive Brokers API), how do I get in a variable the price snapshot of a list of securities?使用本机 TWS Python APi(Interactive Brokers API),我如何在变量中获取证券列表的价格快照?
【发布时间】:2019-12-15 04:07:25
【问题描述】:

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

提前感谢您的帮助。

我发现盈透证券的指南难以理解并且缺乏示例。 他们提供的一个例子是只针对一只股票,它永远不会停止运行。

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()

【问题讨论】:

    标签: python-3.x interactive-brokers tws


    【解决方案1】:

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

    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()。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      相关资源
      最近更新 更多