I am looking to get the open price of today for around 30 symbols as early as possible.
It can be done by the following process:
- Wait until the market opens, time is after 9:30:00
- Use reqHistoricalData to get one day's daily candle
- Grap the open price of today
The problem is that if I reqHistoricalData within 5 seconds after the market is open, the daily candle will be the previous day's data.
I have to wait until the time is after 9:30:05 instead of 9:30:00 to request the daily data.
May I ask if you have any suggestions to get the open price data from IB avoiding waiting 5 seconds after the market is open?
import datetime
import pandas as pd
from ib_insync import *
def wait_until_market_open():
#get open time
now = datetime.datetime.now()
openTime = now.replace(hour=9, minute=30, second=5, microsecond=0)
#return if market is open
while True:
now = datetime.datetime.now()
if( now >= openTime ):
return
time.sleep(0.3)
if __name__ == "__main__":
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=10)
wait_until_market_open()
symbs = ['AAPL', 'TSLA', 'SPY']
for symb in symbs:
contract = Stock(symb, 'SMART', 'USD', primaryExchange='ISLAND')
bars = ib.reqHistoricalData(contract,
endDateTime='',
durationStr='1 D',
barSizeSetting='1 day',
whatToShow='TRADES',
useRTH=True,
formatDate=1)
df = util.df(bars)
print(symb, df.iloc[0]['open'])
ib.disconnect()