How can i load historical data from IB api and append to realtime current bars ona 1 min chart? def get_front_month_contract(symbol, exchange="CME", currency="USD", secType="FUT"): ib = IB() st.info("Connecting to IBKR Gateway via IB Insync...") try: ib.connect('--------', 48879, clientId=1) except Exception as e: st.error(f"Error connecting to IBKR Gateway: {e}") return None contract = Future() contract.symbol = symbol contract.secType = secType contract.exchange = exchange contract.currency = currency st.info(f"Requesting contract details for {symbol} futures...") details = ib.reqContractDetails(contract) if not details: st.error(f"No contract details found for {symbol}.") ib.disconnect() return None today = datetime.today() valid_contracts = [] for d in details: expiry_str = d.contract.lastTradeDateOrContractMonth expiry_date = parse_expiry(expiry_str) if expiry_date and expiry_date > today: valid_contracts.append((expiry_date, d.contract)) if not valid_contracts: st.error(f"No active futures contracts found for {symbol}.") ib.disconnect() return None valid_contracts.sort(key=lambda x: x[0]) front_month_contract = valid_contracts[0][1] st.info(f"Selected front month contract: {front_month_contract.localSymbol}") ib.disconnect() return front_month_contract def get_historical_data(contract, durationStr, barSizeSetting, whatToShow='TRADES', useRTH=True): ib = IB() try: ib.connect('127.0.0.1', 4002, clientId=10) except Exception as e: st.error(f"Error connecting for historical data: {e}") return pd.DataFrame() bars = ib.reqHistoricalData( contract, endDateTime='', durationStr=durationStr, barSizeSetting=barSizeSetting, whatToShow=whatToShow, useRTH=useRTH, formatDate=1 ) ib.disconnect() if not bars: st.error("No historical data returned from IB.") return pd.DataFrame() data = [] for bar in bars: data.append({ "Datetime": pd.to_datetime(bar.date), "Open": bar.open, "High": bar.high, "Low": bar.low, "Close": bar.close, "Volume": bar.volume }) df = pd.DataFrame(data) df.set_index("Datetime", inplace=True) return Continue reading...