Ho Chuen Cheung
Ho Chuen Cheung

Reputation: 23

Fail to draw historical data from TWS API

def get_IB_historical_data(self, ibcontract, tickerid, durationStr, barSizeSetting):

    historic_data_queue = finishableQueue(self.init_historicprices(tickerid))

    self.reqHistoricalData(
        tickerid,  # tickerId,
        ibcontract,  # contract,
        datetime.datetime.today().strftime("%Y%m%d %H:%M:%S %Z"),  # endDateTime,
        durationStr,  # durationStr,
        barSizeSetting,  # barSizeSetting,
        "TRADES",  # whatToShow,
        1,  # useRTH,
        1,  # formatDate
        False,  # KeepUpToDate <<==== added for api 9.73.2
        [] ## chartoptions not used
    )


    MAX_WAIT_SECONDS = 10
    historic_data = historic_data_queue.get(timeout = MAX_WAIT_SECONDS)

    if historic_data_queue.timed_out():
        print("historic_data_queue.timed_out")

    self.cancelHistoricalData(tickerid)

    df = pd.DataFrame(historic_data)
    df.columns = ['Datetime', 'Open', 'High', 'Low', 'Close', 'Volume']

    return df

if name == 'main':

app = App_Class('127.0.0.1',7497, 11)
time.sleep(1234)

ibcontract = IBcontract()
ibcontract.secType = 'FUT'
ibcontract.lastTradeDateOrContractMonth = '20221129'
ibcontract.symbol = 'HSI'
ibcontract.exchange = 'HKFE'

resolved_ibcontract = app.resolve_ib_contract(ibcontract)
print(resolved_ibcontract)

df = app.get_IB_historical_data(resolved_ibcontract, 10, durationStr='30 D', barSizeSetting='1 D')
print(df)

I am new python learner. I dont know why i cant print the dataframe, I have subscribed the data.

My first run to run the program: 576501930,HSI,FUT,20221129,0.0,,50,HKFE,,HKD,HSIX2,HSI,False,,combo: ERROR 10 320 Error reading request. String index out of range: 0 historic_data_queue.timed_out ERROR -1 504 Not connected ValueError: Length mismatch: Expected axis has 0 elements, new values have 6 elements

My second time to run the program and when i rerun, they said" _queue.Empty"

Anyone know why and how to fix it, thanks.

Upvotes: 2

Views: 560

Answers (1)

Guest
Guest

Reputation: 11

'''Add''' ibcontract.includeExpired = True '''under contract details'''

'''change from''' datetime.datetime.today().strftime("%Y%m%d %H:%M:%S %Z"), # endDateTime, '''to''' datetime.datetime.today().strftime("%Y%m%d-%H:%M:%S"), # endDateTime, '''in def get_IB_historical_data'''

Upvotes: 0

Related Questions