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

No order execution?



  • Code so far:

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    import datetime
    import os.path
    import sys
    
    import pandas as pd
    import backtrader as bt
    
    
    class CommInfoFractional(bt.CommissionInfo):
        def getsize(self, price, cash):
            """Returns fractional size for cash operation @price"""
            return self.p.leverage * (cash / price)
    
    
    class MeanReversionSpecial(bt.Strategy):
        lines = ('kama', 'src', 'top', 'bot', 'top2', 'bot2', 'top3', 'bot3', 'top4')
    
        params = (
            ('period', 30),
            ('fast', 2),
            ('slow', 30),
            ('perc', 0.17),
            ('perc2', 0.44),
            ('perc3', 0.66),
            ('perc4', 1.1),
            ('target', 0.35),
            ('target2', 0.70),
            ('target3', 1.40),
            ('target4', 2.80)
        )
    
        def log(self, txt, dt=None):
            """ Logging function fot this strategy"""
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(), txt))
    
        def __init__(self):
            self.bar_executed = len(self)
            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.ama = bt.indicators.AdaptiveMovingAverage(period=self.p.period,
                                                           fast=self.p.fast,
                                                           slow=self.p.slow,
                                                           plotname='AdaptiveMovingAverage')
    
            #  Create upper & lower band 1
            self.l.top = self.ama * (1 + self.p.perc / 100)
            top = bt.LinePlotterIndicator(self.l.top, name='top', subplot=False)
            top.plotinfo.plotname = 'top'
    
            self.l.bot = self.ama * (1 - self.p.perc / 100)
            bot = bt.LinePlotterIndicator(self.l.bot, name='bot', subplot=False)
            bot.plotinfo.plotname = 'bot'
    
            #  Create upper & lower band 2
            self.l.top2 = self.ama * (1 + self.p.perc2 / 100)
            top2 = bt.LinePlotterIndicator(self.l.top2, name='top2', color='cyan', subplot=False)
            top2.plotinfo.plotname = 'top2'
    
            self.l.bot2 = self.ama * (1 - self.p.perc2 / 100)
            bot2 = bt.LinePlotterIndicator(self.l.bot2, name='bot2', color='cyan', subplot=False)
            bot2.plotinfo.plotname = 'bot2'
    
            #  Create upper & lower band 3
            self.l.top3 = self.ama * (1 + self.p.perc3 / 100)
            top2 = bt.LinePlotterIndicator(self.l.top3, name='top3', color='red', subplot=False)
            top2.plotinfo.plotname = 'top3'
    
            self.l.bot3 = self.ama * (1 - self.p.perc3 / 100)
            bot2 = bt.LinePlotterIndicator(self.l.bot3, name='bot3', color='red', subplot=False)
            bot2.plotinfo.plotname = 'bot3'
    
            #  Create upper & lower band 4
            self.l.top4 = self.ama * (1 + self.p.perc4 / 100)
            top2 = bt.LinePlotterIndicator(self.l.top4, name='top4', color='orange', subplot=False)
            top2.plotinfo.plotname = 'top4'
    
            self.l.bot4 = self.ama * (1 - self.p.perc4 / 100)
            bot2 = bt.LinePlotterIndicator(self.l.bot4, name='bot4', color='orange', subplot=False)
            bot2.plotinfo.plotname = 'bot4'
    
        def notify_order(self, order):
            if order.status in [order.Submitted, order.Accepted]:
                return
    
            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))
    
            elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                self.log('Order Canceled/Margin/Rejected')
    
            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])
    
            # 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:
                if self.dataclose[0] <= self.l.bot:
                    self.log('ENTER LONG, %.2f' % self.dataclose[0])
                    self.order = self.order_target_percent(target=self.l.target)
                elif self.dataclose[0] >= self.l.top:
                    self.log('EXIT LONG, %.2F' % self.dataclose[0])
                    self.order = self.order_target_percent(target=-self.l.target)
    
    
    if __name__ == '__main__':
        cerebro = bt.Cerebro()
    
        btc = pd.read_csv('/home/dev/PycharmProjects/Backtesting/csvdata/BTCUSDT-1m-data.csv',
                          index_col='timestamp',
                          parse_dates=True
                          )
    
        feed = bt.feeds.PandasData(
            dataname=btc,
    
            fromdate=datetime.datetime(2020, 5, 1),
            todate=datetime.datetime(2020, 5, 2),
    
            timeframe=bt.TimeFrame.Minutes,
    
        )
    
        cerebro.adddata(feed)
        cerebro.addstrategy(MeanReversionSpecial)
        cerebro.broker.setcash(100000)
        cerebro.broker.addcommissioninfo(CommInfoFractional(leverage=50))
        cerebro.broker.setcommission(commission=0.0025)
    
        # Print out the starting conditions
        print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
        # Run over everything
        cerebro.run()
    
        # Print out the final result
        print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
        cerebro.plot()
    
    

    I'm trying to make it go long when closing price reaches indicator x with the value of a(in this case 0.35% of total balance)
    And sell the long when price reaches indicator z.
    It clearly reaches each indicator several times in the 1day im
    testing it but no buys or sells executed in the output.
    Could the issue be either leverage, my CommInfo module or what do you guys think?
    Output snippet:

    2020-05-01, Close, 8850.41
    2020-05-01, Close, 8851.77
    2020-05-01, Close, 8855.00
    2020-05-01, Close, 8867.35
    2020-05-01, Close, 8865.07
    2020-05-01, Close, 8864.96
    2020-05-01, Close, 8868.37
    2020-05-01, Close, 8870.04
    2020-05-01, Close, 8866.29
    2020-05-01, Close, 8874.88
    2020-05-01, Close, 8878.04
    2020-05-01, Close, 8891.51
    2020-05-01, Close, 8874.80
    2020-05-01, Close, 8875.99
    2020-05-01, Close, 8878.05
    2020-05-01, Close, 8872.99
    2020-05-01, Close, 8879.86
    2020-05-01, Close, 8877.24
    2020-05-01, Close, 8876.48
    2020-05-01, Close, 8880.48
    2020-05-01, Close, 8870.15
    2020-05-01, Close, 8857.86
    2020-05-01, Close, 8875.25
    2020-05-01, Close, 8866.09
    2020-05-01, Close, 8868.46
    2020-05-01, Close, 8867.00
    2020-05-01, Close, 8863.84
    2020-05-01, Close, 8851.45
    2020-05-01, Close, 8864.89
    2020-05-01, Close, 8855.84
    2020-05-01, Close, 8858.92
    2020-05-01, Close, 8846.97
    2020-05-01, Close, 8833.40
    2020-05-01, Close, 8826.87
    2020-05-01, Close, 8837.50
    2020-05-01, Close, 8828.72
    2020-05-01, Close, 8814.94
    2020-05-01, Close, 8807.62
    2020-05-01, Close, 8819.56
    2020-05-01, Close, 8816.54
    
    

Log in to reply
 

});