Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14331

IBKR API: How do I capture and store the Close price from streaming data?

$
0
0

I want to connect to IBKR API streaming data for a futures instrument, grab the prior date's closing price for a specific contract, store it, then close the connection and proceed to the next contract.

I need to do this using "Delayed Frozen" data because I don't have a market data subscription (so setting 'Snapshot' to 'True' or using Historical Data isn't an option).

This code sort of gets part of the way there (using Live Cattle Futures as an example):

from ibapi.client import *from ibapi.wrapper import *import timeclass TestApp(EClient, EWrapper):    def __init__(self):        EClient.__init__(self, self)    def nextValidId(self, orderId: int):        mycontract = Contract()        mycontract.symbol = 'LE'        mycontract.secType = 'FUT'        mycontract.exchange = 'CME'        mycontract.currency = 'USD'        mycontract.lastTradeDateOrContractMonth = '202406'        self.reqMarketDataType(4)        self.reqMktData(orderId, mycontract, '', False, False, [])        time.sleep(10)        app.disconnect()    def tickPrice(self, reqId, tickType, price, attrib):        if TickTypeEnum.to_str(tickType) == 'DELAYED_CLOSE' and reqId == 1:            print('The previous Close price is: ', price)            print(f'tickPrice. reqId: {reqId}, tickType: {TickTypeEnum.to_str(tickType)}, tickType: {tickType}, price: {price}, attribs: {attrib}')app = TestApp()app.connect('127.0.0.1', 4002, 1000)app.run()

When I run it I get:

The previous Close price is:  184.5tickPrice. reqId: 1, tickType: DELAYED_CLOSE, tickType: 75, price: 184.5, attribs: CanAutoExecute: 0, PastLimit: 0, PreOpen: 0The previous Close price is:  184.5tickPrice. reqId: 1, tickType: DELAYED_CLOSE, tickType: 75, price: 184.5, attribs: CanAutoExecute: 0, PastLimit: 0, PreOpen: 0

It produces the 'DELAYED_CLOSE' value, but it keeps streaming until the 'sleep(10)' time is reached, resulting in duplicate lines. Ideally, I'd like the stream to stop as soon as a valid 'tickType' of 75 is received instead of using the 'time.sleep()' line.

Then, how can I store the Close price so that I can output it to a .csv file? I'm assuming something like a dictionary {contract:Close}...?

My eventual goal is to loop through the contracts of an instrument and store the Close price for each contract.


Viewing all articles
Browse latest Browse all 14331

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>