erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.81k stars 753 forks source link

Request Historical News on Bar Update #697

Open NimaMPH opened 7 months ago

NimaMPH commented 7 months ago

I was wondering how I could request historical news on each bar updates. Here is my code:

def on_historical_data_update_async(_bars, _has_new_bar, _contract, _timeframe): symbol = _contract.symbol if _has_new_bar: try:

Assuming there's an async equivalent or workaround

        historical_news = ib_obj.reqHistoricalNews(
            conId=_contract.conId,
            providerCodes=provider_codes,
            startDateTime='',
            endDateTime='',
            totalResults=10
        )

        if historical_news and len(historical_news) > 0:
            print(historical_news[0].headline)
        else:
            print(f"No historical news found for {symbol}.")
    except Exception as e:
        print(f"Error fetching historical news for {symbol}: {e}")

Request bars data----------------------------------------------------------------------------------------------------------------------

        bars = ib_obj.reqHistoricalData(
                                        contract       = contract,
                                        endDateTime    = '',
                                        durationStr    = functions.get_duration_str_func(_timeframe_str = timeframe[1]),
                                        barSizeSetting = timeframe[1],
                                        whatToShow     = 'TRADES',
                                        useRTH         = True,
                                        formatDate     = 1,
                                        keepUpToDate   = True
                                        )

Call on_historical_data_update_func if there is new bar--------------------------------------------------------------------------------

        def on_historical_data_update_wrapper_func(
            _bars,
            _has_new_bar,
            _contract  = contract,
            _timeframe = tf
        ):

            on_historical_data_update_func(
                _bars        = _bars,
                _has_new_bar = _has_new_bar,
                _contract    = _contract,
                _timeframe   = _timeframe
            )

        bars.updateEvent += on_historical_data_update_wrapper_func

But I receive an error related to asynchronous run.