Skip to content

Instantly share code, notes, and snippets.

@jwsmithers
Last active December 2, 2022 17:42
Show Gist options
  • Save jwsmithers/0575fc78f9d54a93988ad29300dfe4b7 to your computer and use it in GitHub Desktop.
Save jwsmithers/0575fc78f9d54a93988ad29300dfe4b7 to your computer and use it in GitHub Desktop.
Function to download from IB
from ib_insync import *
import asyncio
import nest_asyncio
async def update_from_IB(stock):
"""
Asynchronous call example to update stocks from Interactive broker.
Args:
stock(str): Stock, I.e. AAPL
Note:
Remember to set the TWS/IB connection timezone to the current timezone if this is not done already.
Usage:
ib_insync always needs an event loop. So we create one. Something like
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# We need to patch asyncio to be able to use nested loops:
nest_asyncio.apply(loop)
task = loop.create_task(update_from_IB(stock))
loop.run_until_complete(task)
"""
# Initiate an IB object
ib = IB()
# These are the supported USD conversions supported on IB
currencies = ["CHFUSD","USDHKD","EURUSD","USDJPY","USDCNH","USDCZK",\
"USDDKK","USDHUF","USDPLN","USDRUB","USDSEK","USDSGD","USDTRY","USDZAR"]
# Some indexes like S&P 500, Volatility etc.
indexes = ["SPX","VIX","DJX","RUT"]
try:
if ib.isConnected()==False:
logger.debug("Connecting to TWS...")
# This means we have an open IB connection on port 7497 (7497 = Simulation, not live!)
ib.connect('127.0.0.1', 7497, clientId=1)
# Build a contract request
# Different stocks/indexes live on different exchanges.
if stock in indexes:
if stock == "RUT":
exchange="RUSSELL"
elif stock == "BANK":
exchange="NASDAQ"
else:
exchange = "CBOE"
contract=Index(stock, exchange=exchange, currency='USD')
whatToShow="Trades"
# Currencies live on IDEALPRO, I get their MIDPOINT
elif stock in currencies:
# pair is something like "EURUSD"
contract=Forex(pair=stock,exchange="IDEALPRO")
whatToShow="MIDPOINT"
else:
contract = Stock(stock, 'SMART', 'USD',primaryExchange="ISLAND")
whatToShow="Trades"
# Now request the bars using the contract
# https://interactivebrokers.github.io/tws-api/historical_bars.html
bars = ib.reqHistoricalData(
contract,
endDateTime="", # Blank for today
durationStr="600 D", # Go back 600 days
barSizeSetting="1 hour",
whatToShow=whatToShow,
useRTH=True,
formatDate=1,
keepUpToDate=False)
barsList = []
barsList.append(bars)
# Reverse the list to get earliest first
allBars = [b for bars in reversed(barsList) for b in bars]
df = util.df(allBars)
# You now have a dataframe to do with as you please!
...
except Exception as e:
logging.error(e)
if ib.isConnected():
ib.disconnect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment