简体   繁体   中英

Requesting market data using IB API works once at a time python

I've tried running a python script in VSCode to pull live market data and it will only run correctly once, giving me the output of ask price and bid price. However, when I try to run it again, nothing happens, no output. I need to restart my Trader Workstation for it to work again.

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):
        if tickType == 2 and reqId == 1:
            print("Ask price: ", price)
        if tickType == 1 and reqId == 1:
            print("Bid price: ", price)

def main():
    app = TestApp()
    app.connect("127.0.0.1", 7497, 1)

    contract = Contract()
    contract.symbol = "ES"
    contract.lastTradeDateOrContractMonth = "202109"
    contract.secType = "FUT"
    contract.exchange = "GLOBEX"
    contract.currency = "USD"

    app.reqMktData(1, contract, "", True, False, [])

    app.run()

if __name__ == "__main__":
    main()

You don't disconnect so TWS maintains a connection. The app.run() thread is still running. You can kill the program or disconnect after you get the data. Note for snapshots you can wait for a snapshotEnd event which should fire after 11 seconds and then you can call disconnect().

Here is an example with better asynchronous handling. https://stackoverflow.com/a/68026777/2855515

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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