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

FixedReverser not working



  • Hello.
    I am just trying to get used to Backtrader.
    First of all, I would like to deliver my thanks to all developers of Backtrader.
    My problem is that a BUY order executed once but there no further BUY orders are applied.
    So I used the FixedReverser. But the problem is not solved.
    Can you help me to address this issue?
    What I want is that BUY order are executed until all the money with a broker is ran out.
    Thank you in advance.

    class TestStrategy(bt.Strategy):
    params = (
    ('maperiod', 15),
    ('printlog', True),
    )

    def log(self, txt, dt=None, doprint=False):
        ''' Logging function fot this strategy'''
        if self.params.printlog or doprint:
            dt = dt or self.datas[0].datetime.date(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
    
        # Add a MovingAverageSimple indicator
        self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.maperiod)
        # print('0 : ',self.sma)
        self.talibb = bt.talib.MACD(self.datas[0], fastperiod=12, slowperiod=26, signalperiod=9,plotname='WOW')        
        # print('1 : ',talibb)
        # print('2 : ',type(talibb))
        # print('3 : ',self.talibb.macd)
    
        # Indicators for the plotting show
        # bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
        # bt.indicators.WeightedMovingAverage(self.datas[0], period=25,
        #                                     subplot=True)
        # bt.indicators.StochasticSlow(self.datas[0])
        # bt.indicators.MACDHisto(self.datas[0])
        # rsi = bt.indicators.RSI(self.datas[0])
        # bt.indicators.SmoothedMovingAverage(rsi, period=10)
        # bt.indicators.ATR(self.datas[0], plot=False)
    
    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return
    
        # Check if an order has been completed
        # Attention: broker could reject order if not enougth cash
        if order.status in [order.Completed]:
            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)
    
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')
    
        # Write down: no pending order
        self.order = None
    
    def notify_trade(self, trade):
        if not trade.isclosed:
            return
    
        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])
        # self.log('MACD, %.2f' % self.talibb.macd[0])
        # Check if an order is pending ... if yes, we cannot send a 2nd one
        if self.order:
            return
    
        # # Check if we are in the market
        # if not self.position:
    
        # Not yet ... we MIGHT BUY if ...
        if not self.position:
            if  ((self.talibb.macd[0] > self.talibb.macdsignal[0]) and (self.talibb.macd[-1] <= self.talibb.macdsignal[-1])) :
                pass
                # 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 = self.buy()
                # print('BUYBUYBUBYUBY????')
        # else:
        #     # print('OKKKKOOKOKOKKOK????')
        #     self.log('SELL CREATE, %.2f' % self.dataclose[0])
        #     self.order = self.sell(size=5)
        # else:
        #     if self.dataclose[0] < self.sma[0]:
        #         #SELL, SELL, SELL!!! (with all possible default parameters)
        #         self.log('SELL CREATE, %.2f' % self.dataclose[0])
    
        #         # Keep track of the created order to avoid a 2nd order
        #         self.order = self.sell()   
    
    
        # else:
        #     pass
    
            # if self.dataclose[0] < self.sma[0]:
            #     # SELL, SELL, SELL!!! (with all possible default parameters)
            #     self.log('SELL CREATE, %.2f' % self.dataclose[0])
    
            #     # Keep track of the created order to avoid a 2nd order
            #     self.order = self.sell()
    
    # def stop(self):
    #     self.log('(MA Period %2d) Ending Value %.2f' %
    #              (self.params.maperiod, self.broker.getvalue()), doprint=True)
    

    if name == 'main':
    # Create a cerebro entity
    cerebro = bt.Cerebro()

    # Add a strategy
    cerebro.addstrategy(TestStrategy)
    # strats = cerebro.optstrategy(
    #     TestStrategy,
    #     maperiod=range(10, 31))
    
    
    # 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, '../../datas/orcl-1995-2014.txt')
    
    # Create a Data Feed
    # data = bt.feeds.YahooFinanceCSVData(
    #     dataname=datapath,
    #     # Do not pass values before this date
    #     fromdate=datetime.datetime(2000, 1, 1),
    #     # Do not pass values before this date
    #     todate=datetime.datetime(2000, 12, 31),
    #     # Do not pass values after this date
    #     reverse=False)
    data=bt.feeds.PandasData(dataname=old_df)
    
    
    # Add the Data Feed to Cerebro
    cerebro.adddata(data)
    
    
    # Set our desired cash start
    cerebro.broker.setcash(1000000.0)
    
    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.FixedReverser, stake=1)
    
    # Set the commission
    cerebro.broker.setcommission(commission=0.0)
    
    # Print out the starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
    # Run over everything
    cerebro.run(maxcpus=1)
    
    # Print out the final result
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
    # Plot the result
    cerebro.plot()

  • administrators

    Note: See the top of the forum for formatting your code (Place ``` in a line before and *after your code)

    You only issue buy orders if not in the market, so once in the market you won't execute any more orders.


Log in to reply
 

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