繁体   English   中英

使用盈透证券交易平台 API - Python 将价格作为对象/变量返回

[英]Return price as an object/variable using Interactive Brokers TWS API - Python

正如标题所示,我试图从 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()

(我知道我不是想寻求帮助/澄清,但我没有发表评论所需的声誉)

你能建议我应该如何为我的代码做到这一点吗? 例如,我正在尝试将我的帐户余额打印在一个字符串中(我可以在定义它时成功打印它,但是将它打印为一个字符串将是在其他情况下如何做的有用演示)。

在此先感谢您的帮助!

from ibapi.client import EClient  # handles outgoing requests
from ibapi.wrapper import EWrapper  # handles incoming messages

class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.contract_details = {}
        self.bardata = {}  # initialise directory to store bar data
        self.USD_cash_balance = 0
    
    def accountSummary(self, reqId: int, account: str, tag: str, value: str,
                       currency: str):
        if tag == "CashBalance":
            print(value)
        self.USD_cash_balance = value

def run_loop():
    app.run()  # starts communication with TWS


app = IBapi()
app.nextorderId = None
app.connect('127.0.0.1', 7497, 123)

# Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)  # Algo doesn't have "daemon=True"
api_thread.start()

# Check if the API is connected via orderid
while True:
    if isinstance(app.nextorderId,
                  int):  # the IB API sends out the next available order ID as soon as connection is made
        # The isinstance() function returns True if the specified object is of the specified type, otherwise False.
        print('connected')
        break
    else:
        print('waiting for connection')
        time.sleep(2)

app.reqAccountSummary(9001, "All", "$LEDGER:USD")
print("My account balance in USD is: " + str(app.USD_cash_balance))````

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM