簡體   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