[Python] how to retrieve Interactive Brokers historical data iteratively in Python?

Discussão em 'Python' iniciado por Stack, Abril 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am beginner of Interactive Brokers native API user. Now, my trading system needs to retrieve Interactive Brokers historical data iteratively like every one hour bar data . Now My problem is that the final data list append all of the once requested historical data even though the init configuration in the class of ibapi is to be [].

    it should download historical 60 1-minute bars in the first minute. next minute, it is still so far 60 1-minute bars. next next minute, 60 bars. but the result is 60 bars. next minute , 120 bars. next next minute, 180 bars. it append all the once request historical data

    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.contract import Contract
    import datetime
    import threading
    import time
    import pandas
    from ibapi.order import Order
    class IBapi(EWrapper, EClient):
    def __init__(self):
    EClient.__init__(self, self)
    self.data =[]# Initialize variable to store candle

    def historicalData(self, reqId, bar):
    print(f'DateTime: {bar.date} Open: {bar.open} High: {bar.high} Close: {bar.close} Low: {bar.low} Volume: {bar.volume}')
    self.data.append([bar.date, bar.open,bar.high,bar.close,bar.low,bar.volume])

    def run_loop():
    app.run()

    app = IBapi()
    app.connect('127.0.0.1', 7497, 123)

    # Start the socket in a thread
    api_thread = threading.Thread(target=run_loop, daemon=True)
    api_thread.start()

    time.sleep(1) # Sleep interval to allow time for connection to server

    # Create contract object
    contract = Contract()
    contract.symbol = 'N225M'
    contract.secType = 'FUT'
    contract.exchange = 'OSE.JPN'
    contract.currency = 'JPY'
    contract.lastTradeDateOrContractMonth = '202310'


    starttime = time.time()
    timeout = time.time() + 60*60*6
    while (time.time() <= timeout ):

    if (datetime.datetime.now().minute % 1==0 )and (datetime.datetime.now().second<10):
    app.reqHistoricalData(1, contract, '', '3600 S', '1 min', 'TRADES', 0, 1, False, [])
    #
    time.sleep(2) # sleep to allow enough time for data to be returned
    # headers = ['DateTime', 'Open', 'High', 'Low', 'Close','Volume']
    # print(dict(zip(headers, app.data)))
    # df_data = {}
    df = pandas.DataFrame(app.data)
    df.columns=['DateTime','Open','High','Close','Low','Volume']
    # df['Datetime'] = df['Datetime'].dt.tz_convert('Asia/Shanghai')
    print( len(df))
    print(df)

    Continue reading...

Compartilhe esta Página