For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

How to Get Live Data from IB



  • Dear friends , I want to get the live data from IB TWS , I consult all the discussion topic and try the demo . but can't get the right data still. I think it's not the IB pemission , I tried the IB Api and can get the data. Can you help me ? Thanks a lot!

    My BT code:
    import backtrader as bt
    import datetime as dt
    import pytz as pytz
    import datetime

    class Test_Strategy (bt.Strategy):
    def log (self, text):
    print (self.data.datetime.datetime(0),": ", text)
    txt = []
    txt.append('{}'.format(len(self))
    )
    txt.append('{}'.format(self.data.datetime.datetime(0).isoformat())
    )
    txt.append('{:.2f}'.format(self.data.open[0]))
    txt.append('{:.2f}'.format(self.data.high[0]))
    txt.append('{:.2f}'.format(self.data.low[0]))
    txt.append('{:.2f}'.format(self.data.close[0]))
    txt.append('{:.2f}'.format(self.data.volume[0]))
    print(','.join(txt))

    def __init__(self):
        print ("Strategy initialization finished.")
    
    def next (self):
        print('next begin')
        self.log (self.data.close[0])
        if not self.data_live:
            return
    
        if not self.bought:
            self.bought = len(self) #keep entry bar
            self.buy()
        elif not self.sold:
            if len(self) == (self.bought + 3):
                self.sell()
    
    
    def notify_data(self, data, status):
        print('*' * 5, 'DATA NOTIF:', data._getstatusname(status))
       
    def notify_order(self,order):
        if order.status == order.completed:
            buysell = 'BUY' if order.isbuy() else 'SELL'
            txt = '{} {} @{}'.format(buysell,order.executed.size,order.executed.price)
            print(txt)
        bought = 0
        sold = 0
    

    if name == 'main':
    #cerebro = bt.Cerebro(stdstats=False) # I don't want the default plot objects
    cerebro = bt.Cerebro()
    cerebro.broker.set_cash(1000000) # Set our starting cash to $1,000,000
    cerebro.broker.setcommission(0.02)

    start = datetime.datetime(2020, 4, 1)
    end = datetime.datetime(2020, 5, 28)
    
    # create the data
    usestore = False     
    
    storekwargs = dict(
            host= '127.0.0.1', port=7497,
            clientId=None, timeoffset=False,
            reconnect=3, timeout=3.0,
            notifyall=False, _debug=False
    )
    ibstore = bt.stores.IBStore(**storekwargs)
    print ("Using IBstore")
    
    broker = ibstore.getbroker()
    IBDataFactory = ibstore.getdata if usestore else bt.feeds.IBData
    dtfmt = '%Y-%m-%dT%H:%M:%S.%f'
    datakwargs = dict(
            timeframe= bt.TimeFrame.TFrame("Minutes"), compression=1,
            historical=True, fromdate=start, todate = end,     ## mod todate here
            rtbar=False,
            qcheck=0.5,
            what=None,
            backfill_start=True,
            backfill=False,
            latethrough=False,
            tz=None,
            useRTH = True
    )
    
    data0 = IBDataFactory(dataname='PDD', **datakwargs)
    data0.plotinfo.plotmaster = data0
    
    cerebro.resampledata(data0, timeframe=bt.TimeFrame.Minutes, compression=2)
    
    #cerebro.adddata(data)    # Give the data to cerebro
    
    print("Data added to cerebro")
    
    class AcctValue(bt.Observer):
        alias = ('Value',)
        lines = ('value',)
    
        plotinfo = {"plot": True, "subplot": True}
    
        def next(self):
            self.lines.value[0] = self._owner.broker.getvalue()    # Get today's account value (cash + stocks)
    
    cerebro.addobserver(AcctValue)
    cerebro.addstrategy(Test_Strategy)
    #cerebro.addsizer(PropSizer)
    
    cerebro.broker.getvalue()
    
    cerebro.run()
    

    The log :
    Using IBstore

    Data added to cerebro
    
    Server Version: 76
    
    TWS Time at connection:20200609 03:40:25 AWST
    
    Strategy initialization finished.
    
    ***** DATA NOTIF: DISCONNECTED
    
    请按任意键继续. . .
    

    The IB Api code :

    import pymysql
    
    import pandas as pd
    
    from ib_insync import *
    
    #from config import configs
    
    # util.startLoop()  # uncomment this line when in a notebook
    ib = IB()
    ib.connect('127.0.0.1', 7497, clientId=1)
    code = "PDD"
    contract = Stock(code, exchange="SMART")
    
    bars = ib.reqHistoricalData(contract, endDateTime='20200609 18:30:00', durationStr='1 D',
    
            barSizeSetting='30 secs', whatToShow='MIDPOINT', useRTH=True)
    
    # convert to pandas dataframe:
    
    df = util.df(bars)
    
    print(df[['date', 'open', 'high', 'low', 'close']])
    

    The result :
    date open high low close

    0   2020-06-08 21:30:00  72.435  72.445  71.730  72.185
    
    1   2020-06-08 21:30:30  72.185  72.430  72.075  72.430
    
    2   2020-06-08 21:31:00  72.430  72.475  72.115  72.245
    
    3   2020-06-08 21:31:30  72.245  72.245  71.790  71.870
    
    4   2020-06-08 21:32:00  71.870  72.140  71.870  72.050
    
    ..                  ...     ...     ...     ...     ...
    
    762 2020-06-09 03:51:00  68.485  68.485  68.400  68.450
    
    763 2020-06-09 03:51:30  68.450  68.485  68.405  68.425
    
    764 2020-06-09 03:52:00  68.425  68.425  68.395  68.410
    
    765 2020-06-09 03:52:30  68.410  68.425  68.395  68.405
    
    766 2020-06-09 03:53:00  68.405  68.440  68.395  68.400
    
    
    
    [767 rows x 5 columns]
    
    请按任意键继续. . .


  • @songcl said in How to Get Live Data from IB:
    I've run your code almost unchanged (up to some syntax errors) and it seems to be working ok:

    Using IBstore
    Data added to cerebro
    Server Version: 76
    TWS Time at connection:20200613 12:40:05 
    Strategy initialization finished.
    ***** DATA NOTIF: DELAYED
    next begin
    2020-04-01 13:30:00 :  35.62
    1,2020-04-01T13:30:00,35.50,35.81,35.42,35.62,966.00
    next begin
    2020-04-01 13:32:00 :  35.6
    2,2020-04-01T13:32:00,35.73,36.16,35.60,35.60,592.00
    next begin
    2020-04-01 13:34:00 :  35.92
    3,2020-04-01T13:34:00,35.68,36.20,35.67,35.92,502.00
    next begin
    2020-04-01 13:36:00 :  36.16
    4,2020-04-01T13:36:00,35.89,36.44,35.88,36.16,576.00
    

    Please check if there is a problem with your TWS account or client is not running. You may also examine the TWS API logs for some errors.


Log in to reply
 

});