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

Using Timer to Buy and different indicator to Sell Strategy Help

  • Hi, I'm new to backtrader so thank you in advance for answering a probably obvious question.

    My example strategy is to execute a buy on a given day (weekday 4), and sell according to an indicator (when RSI >70) .

    I am having trouble getting these 2 actions to tie together correctly. I can run the code successfully, but it seems as though it isn't taking into account the buy day.

    Any help / further guidance is appreciated.

    import backtrader as bt
    import datetime
    class firstStrategy(bt.Strategy):
        def __init__(self):
            self.rsi = bt.indicators.RSI_SMA(, period=21)
            timername='buytimer', # in case the day is a non-trading day the timer should kick in on the next trading day
        def notify_timer(self, timer, when, *args, **kwargs):
            if not self.position:
        def next(self):
    #        if not self.position:
    #            self.notify_timer(timer,when)
    #        else:
            if self.rsi > 70:
    #Variable for our starting cash
    startcash = 100000
    #Create an instance of cerebro
    cerebro = bt.Cerebro()
    #Add our strategy
    data = bt.feeds.YahooFinanceCSVData(
        fromdate=datetime.datetime(2019, 5, 1),   #2014, 9, 21
        todate=datetime.datetime(2020, 7, 8)
    #Add the data to Cerebro
    # Set our desired cash start
    # Run over everything
    #Get final portfolio Value
    portvalue =
    pnl = portvalue - startcash
    #Print out the final result
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('P/L: ${}'.format(pnl))
    #Finally plot the end results

  • Just a few things to tidy up your code.

    @Liz said in Using Timer to Buy and different indicator to Sell Strategy Help:


    Weekdays is plural.

    Check if there's an open order in:

     def notify_timer(self, timer, when, *args, **kwargs):
            if not self.position or not self.order:

    Use close instead of sell in next:

     if self.position and self.rsi > 70:

Log in to reply