fetch_historical_data

fetch_historical_data(contract, endDateTime='', durationStr='1 D', barSizeSetting='1 hour', whatToShow='Trades', useRTH=True, host='127.0.0.1', port=7497, client_id=9999, timeout=3)

Fetch historical data for a tradable asset

Creates a temporary IBKR client socket at the specified host, port, and client_id, then makes a query for the historical data specified by the input parameters, receives the response, closes the socket, formats the response, and returns the result.

If timeout number of seconds elapse before receiving historical data, then fetch_historical_data returns None.

Parameters

Name Type Description Default
contract Contract The Contract object for which you want data required
endDateTime Ending datetime string formatted as “YYYYMMDD HH:mm:ss TMZ” specifying the end of the time period for which you want historical data. Leave it as the default “” to get historical data up to the current present moment. ''
durationStr A Duration String that specifies how far back in time you want to fetch data. '1 D'
barSizeSetting A Bar Size that specifies how fine-grained you want your historical data to be (daily, weekly, every 30 seconds, etc). '1 hour'
whatToShow You may select from any of the Historical Data Types but for most cases you’ll probably be happy with one of “BID_ASK”, “MIDPOINT”, or “TRADES”. 'Trades'
useRTH “Use Regular Trading Hours”. Set to False if you want the historical data to include after-hours/pre-market trading True

Examples

import shinybroker as sb

historical_data = sb.fetch_historical_data(
    contract=sb.Contract({
        'symbol': "AAPL",
        'secType': "STK",
        'exchange': "SMART",
        'currency': "USD"
    })
)

print(historical_data)

#### Try an example with a bad barSizeSetting
#### fetch_historical_data prints an informative error message and returns None
historical_data_bad_barsize = sb.fetch_historical_data(
    contract=sb.Contract({
        'symbol': "AAPL",
        'secType': "STK",
        'exchange': "SMART",
        'currency': "USD"
    }),
    barSizeSetting="1 hrs"
)
print(historical_data_bad_barsize)