Algotopian is starting. Let it be the future of backtrader. Check it out!
For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

optstrategy not working in Jupyter

  • Im trying to run a simple example using optstrategy in a Jyputer notebook and it simply just hangs. Any ideas?

    Here is the code:

    import datetime  # For datetime objects
    import os.path  # To manage paths
    import sys  # To find out the script name (in argv[0])
    # Import the backtrader platform
    import backtrader as bt
    # Create a Stratey
    class TestStrategy(bt.Strategy):
        params = (('BBandsperiod', 20),)
        def log(self, txt, dt=None):
            ''' Logging function fot this strategy'''
            dt = dt or self.datas[0]
    #         print('%s, %s' % (dt.isoformat(), txt))
        def __init__(self):
            # Keep a reference to the "close" line in the data[0] dataseries
            self.dataclose = self.datas[0].close
            # To keep track of pending orders and buy price/commission
            self.order = None
            self.buyprice = None
            self.buycomm = None
            self.redline = None
            self.blueline = None
            # Add a BBand indicator
            self.bband = bt.indicators.BBands(self.datas[0], period=self.params.BBandsperiod)
        def notify_order(self, order):
            if order.status in [order.Submitted, order.Accepted]:
                # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            # Check if an order has been completed
            # Attention: broker could reject order if not enougth cash
            if order.status in [order.Completed, order.Canceled, order.Margin]:
                if order.isbuy():
    #                 self.log(
    #                     'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
    #                     (order.executed.price,
    #                      order.executed.value,
    #                      order.executed.comm))
                    self.buyprice = order.executed.price
                    self.buycomm = order.executed.comm
                else:  # Sell
    #                 self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
    #                          (order.executed.price,
    #                           order.executed.value,
    #                           order.executed.comm))
                self.bar_executed = len(self)
            # Write down: no pending order
            self.order = None
        def notify_trade(self, trade):
            if not trade.isclosed:
            #self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
            #         (trade.pnl, trade.pnlcomm))
        def next(self):
            # Simply log the closing price of the series from the reference
            #self.log('Close, %.2f' % self.dataclose[0])
            # Check if an order is pending ... if yes, we cannot send a 2nd one
            if self.order:
            if self.dataclose < and not self.position:
            	self.redline = True
            if self.dataclose > and self.position:
            	self.blueline = True
            if self.dataclose > self.bband.lines.mid and not self.position and self.redline:        	
            	# BUY, BUY, BUY!!! (with all possible default parameters)
                #self.log('BUY CREATE, %.2f' % self.dataclose[0])
                # Keep track of the created order to avoid a 2nd order
                self.order =
            if self.dataclose > and not self.position:
                # BUY, BUY, BUY!!! (with all possible default parameters)
                #self.log('BUY CREATE, %.2f' % self.dataclose[0])
                # Keep track of the created order to avoid a 2nd order
                self.order =
            if self.dataclose < self.bband.lines.mid and self.position and self.blueline:
                # SELL, SELL, SELL!!! (with all possible default parameters)
                #self.log('SELL CREATE, %.2f' % self.dataclose[0])
                self.blueline = False
                self.redline = False
                # Keep track of the created order to avoid a 2nd order
                self.order = self.sell()
    if __name__ == '__main__':
        # Create a cerebro entity
        cerebro = bt.Cerebro()
        # Add a strategy
        cerebro.optstrategy(TestStrategy, BBandsperiod=(18, 22))
        # Datas are in a subfolder of the samples. Need to find where the script is
        # because it could have been called from anywhere
        # modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
        # datapath = os.path.join(modpath, 'TSLA-USD.csv')
        # Create a Data Fee
        data = bt.feeds.GenericCSVData(
            # dtformat='%Y-%m-%d %H:%M:%S',
            # dtformat='%d.%m.%Y %H:%M:%S.%f',
            # tmformat='%H%M%S',  # already the default value
            # datetime=0,  # position at default
            time=-1,  # position of time
            open=1,  # position of open
            openinterest=-1,  # -1 for not present
        # Add the Data Feed to Cerebro
        # Set our desired cash start
        # Add a FixedSize sizer according to the stake
        cerebro.addsizer(bt.sizers.FixedSize, stake=5)
        # Set the commission
        # Print out the starting conditions
        #print('Starting Portfolio Value: %.2f' %
        # Run over everything
        # Print out the final result
        #print('Final Portfolio Value: %.2f' %
        # Plot the result

    Here is the output from the Jupyter console:


  • @Søren-Pallesen I've heard that jupyter doesn't support multiprocessing. This can be a reason of the error.

  • See this:

    Any shell which hijacks the initialization of the Python kernel is bound to have problems with the multiprocessing module under Windows. Google shows some other references from the past:

  • Thx for prompt answers. Love this community for that. Any way to use optstrategy without multiprocessing?

    • Option 1: maxcpus=1 (disable using multiple cores)
    • Option 2: You give GvR a call and tell him that in 2017 (with 2018 not being that far away) the GIL may no longer be such a good idea. It may be worth a try.

  • Funny and knowleble. Rare combo 🤣. Thx again will give maxcpus a shot. Shame though when you have a 12 core i7 ...

Log in to reply

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.