2022-12-13

IBAPI get historical bars continuously

I'm new in programming, sorry if somwhere make simplemistakes or do not get something.

I try to use IBApi for build script. Main point - request historical data continuously(one time in 15 sec for last week timerange, as example), convert it to dataframe and make further calculations.

But i can't do that as guide shows, it does not work that way.

I guess there is a way to do it simply, as with ib_insync.

To get code example, how i can request bars data from IB using IBApi and convert to dataframe

import time

from ibapi.client import *
from ibapi.wrapper import *
from ibapi.contract import Contract
import pandas as pd
from datetime import timedelta
import mplfinance as mpf


    class TestApp(EClient, EWrapper):
        # put number of candles for plot(check timerange in "self.reqHistoricalData" - must be bigger than this value
        cnadles_plot = 10000
    
        # Simply shift hours forward+ or back-
        hours_change = -5
    
    
        def __init__(self):
            EClient.__init__(self, self)
    
        def nextValidId(self, orderId: int):
            mycontract = Contract()
            mycontract.symbol = "TSLA"
            mycontract.secType = "STK"
            mycontract.exchange = "SMART"
            mycontract.currency = "USD"
            self.reqMarketDataType(4)
            self.reqMktData(orderId, mycontract, "", 0, 0, [])
            self.histbars = []
    
            self.reqHistoricalData(orderId, mycontract, "20221010-15:00:00", "5 D", "1 min", "TRADES", 0, 1, 0, [])
    
    
        def historicalData(self, reqId: int, bar: BarData):
            bardict = {"HistoricalData": reqId, "Date": bar.date, "Open": bar.open, "High": bar.high, "Low": bar.low,
                       "Close": bar.close, "Volume": bar.volume, "Count": bar.barCount}
            self.histbars.append(bardict)
    
    
    
        def historicalDataEnd(self, reqId: int, start: str, end: str):
            print(f"End of request")
            print(f"Start: {start}, End {end}")
    
            df = pd.DataFrame.from_records(self.histbars)
            df["Date"] = df["Date"].str.split().str[:2].str.join(' ')
            df["Date"] = pd.to_datetime(df["Date"])
    
            df["Date"] = df["Date"] + timedelta(hours=self.hours_change)
            df.set_index("Date", inplace=True)
            df["Volume"] = pd.to_numeric(df["Volume"])
    
            def vwap(df):
                high = df.High.values
                low = df.Low.values
                vol = df.Volume.values
                return df.assign(vwap=((high + low) / 2 * vol).cumsum() / vol.cumsum())
            df = df.groupby(df.index.date, group_keys=False).apply(vwap)
    
    
            print(df.tail(self.cnadles_plot))
            print(df.dtypes)
            apdict = mpf.make_addplot(df['vwap'])
            mpf.plot(df, type="candle", volume=True,tight_layout=True,show_nontrading=True, addplot=apdict)
    
    
    
    
    
    
    
    
    app = TestApp()
    app.connect("127.0.0.1", 7496, 1000)
    while True:
        app.run()
        time.sleep(20)


No comments:

Post a Comment