python - 使用盈透证券 TWS API 将价格作为对象/变量返回 - Python

标签 python tws

正如标题所示,我试图从 TWS API 获取给定证券的价格,并将其用作我的程序中其他地方的变量。下面的代码(直接来自盈透证券的教程之一)将运行并在屏幕上打印价格,但我无法以一种可以创建包含价格的变量/对象的方式对其进行更改。该代码也大约每十次尝试才有效一次,如果我做错了什么,请告诉我。

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


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 main():
    app = TestApp()

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

    contract = Contract()
    contract.symbol = 'AAPL'
    contract.secType = 'STK'
    contract.currency = 'USD'
    contract.exchange = 'SMART'
    
    app.reqMarketDataType(1)
    app.reqMktData(1, contract, '', False, False, [])

    app.run()


if __name__ == '__main__':
    main()

最佳答案

该程序没有考虑 API 的异步性质。

#here you are asking to connect, you must wait for a connection
app.connect('127.0.0.1', 7496, 0)

contract...
# you may not have a connection and you're not listeneing for responses yet.
app.reqMarketDataType(1)
app.reqMktData(1, contract, '', False, False, [])

# here is where you start listening for responses, that's what run() does
app.run()

我会这样写

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

class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        # here you can add variables to the TestApp class, just use self.var in the class
        self.last = 0;
        
    # ib suggests waiting for this response to know that you have a connection
    def nextValidId(self, orderId:int):    
        self.reqMarketDataType(MarketDataTypeEnum.REALTIME) # or DELAYED
        contract = Contract()
        contract.symbol = "AAPL"
        contract.secType = "STK"
        contract.currency = "USD"
        contract.exchange = "SMART"
        self.reqMktData(1, contract, "", False, False, None)

    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)
            if tickType == TickTypeEnum.LAST or tickType == TickTypeEnum.DELAYED_LAST :
                self.last = price;
                print("disconnecting")
                self.disconnect() # just for testing, normally the program would do something

def main():
    app = TestApp()
    app.connect('127.0.0.1', 7497, 123)
    app.run() # this blocks the program until disconnect()
    print("app.last:", app.last) # now you refer to the variable by class.var

if __name__ == '__main__':
    main()

关于python - 使用盈透证券 TWS API 将价格作为对象/变量返回 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68025207/

相关文章:

python - 行未添加到数据库中

python - IB TWS API - reqHistoricalData - keepUpToDate

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

python - 用于下载股票基本数据的 TWS API 仅运行第一个数据条目,而忽略其他数据条目。这个问题找谁解决?

python - 在 MLFlow 管道中读取 csv 文件

python - 如何打印类内函数的返回值

python - 我怎样才能避免出现 OSError : [Errno 9] Bad file descriptor using ibapi?

python - tensorflow 错误无法导入名称 'export_saved_model'

python - 如何告诉ElasticSearch多重匹配查询我希望数字字段(以字符串形式存储)返回与数字字符串匹配的内容?