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

Daily strategy, best way to trade at open... timer.



  • I'm trying to implement a daily strategy. Ideally I would like to check the prices at open, adjust the size of my order, and send the order. I've used cheat-on-open in back testing and it worked fine.

    Now trying to trade in paper with IB. When I run the algorithm, it automatically executes all the instructions within the timer function right away instead of waiting for the timer. I'm sure I'm missing a setting or misunderstanding how this works.

    Here is my relevant code... cheat is cancelled in this run.

    class DoubleTrendLS(bt.Strategy):
        """
        Back test implementation of trading strategy called Double Trend Long/Short Strategy
        """
    
        params = dict(
            # when=(datetime.now() + timedelta(seconds=60)).time(),
            when=time(15, 44, 0, 0), # 5 minutes ahead of run time.
            # when=bt.timer.SESSION_START,
            timer=True,
            cheat=False,
            offset=timedelta(),
            repeat=timedelta(),
            weekdays=[1, 2, 3, 4, 5],
            weekcarry=False,
            monthdays=[],
            monthcarry=True,
            buffer=0.2,
        )
    
        def __init__(self):
            """Set up indicators line level"""
            # Create timer
            self.cheating = self.cerebro.p.cheat_on_open
            self.data_live = False
    
            if self.p.timer:
                self.add_timer(
                    when=self.p.when,
                    offset=self.p.offset,
                    repeat=self.p.repeat,
                    weekdays=self.p.weekdays,
                    weekcarry=self.p.weekcarry,
                    monthdays=self.p.monthdays,
                    monthcarry=self.p.monthcarry,
                    # tzdata=self.datas[0],
                )
            if self.cheating:
                self.add_timer(
                    when=self.p.when,
                    offset=self.p.offset,
                    repeat=self.p.repeat,
                    weekdays=self.p.weekdays,
                    weekcarry=self.p.weekcarry,
                    monthdays=self.p.monthdays,
                    monthcarry=self.p.monthcarry,
                    # tzdata=self.datas[0],
                    cheat=True,
                )
    
       def notify_timer(self, timer, when, *args, **kwargs):
    
            if not self.data_live:
                return
    
            print(
                "strategy notify_timer with tid {}, when {} cheat {}".format(
                    timer.p.tid, when, timer.p.cheat
                )
            )
    
            self.logdata("Timer:")
            self.operate() # this has the algorithm
    
    def next(self):
        # just prints logs...
    
    def operate(self):
        # does stuff and trades...
    
    def run_strat(args=None):
        # Cerebro create
        cerebro = bt.Cerebro(stdstats=False, cheat_on_open=False) # currently trying it without cheat...
    
        # Open the IB Store.
        store = bt.stores.IBStore(host="127.0.0.1", port=7497, clientId=147)
        cerebro.broker = store.getbroker(**eval("dict(" + args.broker + ")"))
    
        stockkwargs = dict(
            timeframe=bt.TimeFrame.Days,
            rtbar=False,  # use RealTime 5 seconds bars
            historical=bool(int(args.historical)),  # only historical download
            what="TRADES",
            useRTH=False,  # historical - download only Regular Trading Hours
            qcheck=0.5,  # timeout in seconds (float) to check for events
            backfill_start=True,  # do backfilling at the start
            backfill=True,  # do backfilling when reconnecting
            fromdate=date_start,  # get data from..
            todate=date_end,  # get data from..
            latethrough=False,  # let late samples through
            tradename=None,  # use a different asset as order target
        )
    
        # Add Nasdaq data line.
        data0 = store.getdata(dataname=args.data0, **stockkwargs)
        cerebro.adddata(data0)
    
        # Add S&P500 data line.
        data1 = store.getdata(dataname=args.data1, **stockkwargs)
        cerebro.adddata(data1)
    
        # Add S&P short data line.
        data2 = store.getdata(dataname=args.data2, **stockkwargs)
        cerebro.adddata(data2)
    
    

    And running:

    main_live.py --buffer 0.025 --data0 TQQQ-STK-ISLAND-USD --data1 SPXL-STK-ISLAND-USD --data2 SPXS-STK-ISLAND-USD --historical 0 --cerebro "optreturn=False, optdatas=True, stdstats=False" --broker "coo=False" --ploton 0
    

    With no active positions, and the timer set to 5 minutes ahead of run time, when run, the order fills immediately.

    Print from next: 2019-08-31 03:59:59, TQQQ-STK-ISLAND-USD, close: 60.3  
    Print from next: 2019-09-03 00:00:00, TQQQ-STK-ISLAND-USD, close: 58.69  
    ***** DATA NOTIF: LIVE
    ***** DATA NOTIF: LIVE
    strategy notify_timer with tid 0, when 2019-09-03 15:44:00 cheat False
    Called from: Timer:
    TQQQ-STK-ISLAND-USD, 557, 2019-09-03, 58.69, 58.69, 58.69, 58.69, 1.00
    SPXL-STK-ISLAND-USD, 557, 2019-09-02, 48.75, 49.17, 48.00, 48.64, 3139.00
    SPXS-STK-ISLAND-USD, 557, 2019-09-02, 18.62, 18.82, 18.40, 18.59, 16446.00
    Nasdaq 30 day: 59.03, S&P 12 mo: 46.41
    This is the 'unrate': 3.7 and unrate indicator: 3.75, -0.05
    
    
    Called from: Operate
    TQQQ-STK-ISLAND-USD, 557, 2019-09-03, 58.69, 58.69, 58.69, 58.69, 1.00
    SPXL-STK-ISLAND-USD, 557, 2019-09-02, 48.75, 49.17, 48.00, 48.64, 3139.00
    SPXS-STK-ISLAND-USD, 557, 2019-09-02, 18.62, 18.82, 18.40, 18.59, 16446.00
    Nasdaq 30 day: 59.03, S&P 12 mo: 46.41
    This is the 'unrate': 3.7 and unrate indicator: 3.75, -0.05
    
    
    2019-09-03 Send BUY for SPXL-STK-ISLAND-USD,  value: 10000.00,	size:205,	close 48.64
    Print from next: 2019-09-03 19:42:53, TQQQ-STK-ISLAND-USD, close: 58.69  
    Print from next: 2019-09-03 19:42:56, TQQQ-STK-ISLAND-USD, close: 58.68  
    ***** DATA NOTIF: LIVE
    Print from next: 2019-09-03 19:43:01, TQQQ-STK-ISLAND-USD, close: 58.69  
    Print from next: 2019-09-03 19:43:02, TQQQ-STK-ISLAND-USD, close: 58.68  
    Print from next: 2019-09-03 19:43:02, TQQQ-STK-ISLAND-USD, close: 58.68  
    Print from next: 2019-09-03 23:59:59, TQQQ-STK-ISLAND-USD, close: 58.68  
    Print from next: 2019-09-03 23:59:59, TQQQ-STK-ISLAND-USD, close: 58.68  
    2019-09-03, SPXL-STK-ISLAND-USD Order 1 Status Partial
    Print from next: 2019-09-03 23:59:59, TQQQ-STK-ISLAND-USD, close: 58.68  
    Print from next: 2019-09-03 23:59:59, TQQQ-STK-ISLAND-USD, close: 58.65  
    Print from next: 2019-09-03 23:59:59, TQQQ-STK-ISLAND-USD, close: 58.65  
    2019-09-03, SPXL-STK-ISLAND-USD Order 1 Status Completed
    2019-09-03, BUY EXECUTED for SPXL-STK-ISLAND-USD, Price: 48.65, Cost: 9972.25, Comm 1.54
    -- No longer alive main Ref
    Print from next: 2019-09-03 23:59:59, TQQQ-STK-ISLAND-USD, close: 58.65  
    
    

    As always, appreciate any advice and guidance.

    run-out


  • administrators

    If you want a 1-day timeframe/compression with Interactive brokers in real-time that isn't the way. Please read the documentation: https://www.backtrader.com/docu/live/ib/ib/ where it is clearly indicated that resampling/replaying is needed due to how IB delivers data. Else, you are getting plain ticks.

    Also here: https://medium.com/@danjrod/interactive-brokers-in-python-with-backtrader-23dea376b2fc

    With regards to the timer and if you use daily data it seems pointless to say you want to execute some minutes before the open, because the data feed will only deliver clock information when it opens.

    @run-out said in Daily strategy, best way to trade at open... timer.:

    When I run the algorithm, it automatically executes all the instructions within the timer function right away instead of waiting for the time

    In any case, I fail to understand this statement. Unless you call the logic yourself, it is called from the timer.



  • @backtrader Thanks!


Log in to reply
 

});