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

BackTrader plots but does not calculate trades or profits what did I do wrong?



  • The Data is in Timestamp format from Bitmex using CCXT, I am testing a simple strategy from the docs and have followed a few threads to make changed an example output is :

    Starting Portfolio Value: 10000.00
    2 5
    2019-08-11, Close, 210.45
    2019-08-11, Close, 210.55
    2019-08-11, Close, 210.60
    2019-08-11, Close, 210.55
    2019-08-11, BUY CREATE, 210.55
    2019-08-11, Close, 210.60
    2019-08-11, Close, 210.65
    2019-08-11, Close, 210.65
    2019-08-11, Close, 210.50
    2019-08-11, Close, 210.05
    2019-08-11, Close, 210.05
    2019-08-11, Close, 210.20
    2019-08-11, Close, 209.95
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.05
    2019-08-11, Close, 210.05
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.05
    2019-08-11, Close, 209.90
    2019-08-11, Close, 209.95
    2019-08-11, Close, 210.05
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.25
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.20
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.10
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.15
    2019-08-11, Close, 210.30
    2019-08-11, Close, 210.70
    2019-08-11, Close, 210.85
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.95
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.95
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.95
    2019-08-11, Close, 210.95
    2019-08-11, Close, 210.95
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.90
    2019-08-11, Close, 210.90
    Final Portfolio Value: 10000.00
    

    One of the Issues I see both on the Matlib chart and on the responses are that the time is always the same date when the timestamps are not

    here is my code :

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    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
    import backtrader.feeds as btfeed
    import math
    
    
    
    class customCSV(btfeed.GenericCSVData):
        params = (
            ('nullvalue', float('NaN')),
            ('dtformat', lambda x: datetime.datetime.utcfromtimestamp(int(x[:-3]))),
            ('tmformat', '%yyy:%MM:%dd %H:%M:%S'),
            ('datetime', 1),
            ('time', -1),
            ('open', 2),
            ('high', 3),
            ('low', 4),
            ('close', 5),
            ('volume', 6),
            ('openinterest', -1),
            ('seperator',',')
        )
    
    
    class SmaCross(bt.SignalStrategy):
        params = (('pfast', 10), ('pslow', 21),)
    
        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
            
            
            sma1, sma2 = bt.ind.SMA(period=self.p.pfast), bt.ind.SMA(period=self.p.pslow)
            self.signal_add(bt.SIGNAL_LONG, bt.ind.CrossOver(sma1, sma2))
            self.signal_add(bt.SIGNAL_SHORT, bt.ind.CrossOver(sma2,sma1))
            self.buysig = bt.ind.CrossOver(sma1, sma2)
            self.sellsig = bt.ind.CrossOver(sma2,sma1)
            print(bt.SIGNAL_LONG,bt.SIGNAL_SHORT)
          
        def log(self, txt, dt=None):
            ''' Logging function for this strategy'''
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(), txt))  
                    
            
        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 enough 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')
            self.order = None
    
        def notify_trade(self, trade):
            if not trade.isclosed:
                return
    
            self.log('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:
            
                # buy signal
                if self.buysig > 0:
                    # BUY
                    self.log('BUY CREATE, %.2f' % self.dataclose[0])
                    # Keep track of the created order to avoid a 2nd order
                    self.order = self.buy()
                elif self.sellsig > 0:
                    #if len(self) >= (self.bar_executed + self.params.exitbars):
                        # Sell
                    self.log('SELL CREATE, %.2f' % self.dataclose[0])
                        # Keep track of the created order to avoid a 2nd order
                    self.order = self.sell(size=1000)
                    #else:
                        #return
                else:
                    return
            else:    # in a position        
                if self.buysig < 0:
                    # Buy Closed
                    self.log('BUY CLOSE, %.2f' % self.dataclose[0])
                    self.order = self.close()
                    self.order = self.sell(size=1000)
                # elif ignore zero case
                elif self.sellsig < 0:
                    # Sell Closed
                    self.log('SELL CLOSE, %.2f' % self.dataclose[0])
                    self.order = self.close()
                    self.order = self.buy()
                else:
                    return
                
    
    class maxRiskSizer(bt.Sizer):
        '''
        Returns the number of shares rounded down that can be purchased for the
        max rish tolerance
        '''
        params = (('risk', 0.20),)
    
        def __init__(self):
            if self.p.risk > 1 or self.p.risk < 0:
                raise ValueError('The risk parameter is a percentage which must be entered as a float. e.g. 0.5')
            
        def _getsizing(self, comminfo, cash, data, isbuy):
    
            position = self.broker.getposition(data)
    
            if not position:
                size = math.floor((cash * self.p.risk) /data.close[0])
            else:
                size = position.size
    
            return size
            
            
    startcash = 10000
           
            
            
    
    cerebro = bt.Cerebro()
    cerebro.addsizer(maxRiskSizer)
    cerebro.broker.setcommission(commission=0.001)
    data = customCSV(dataname='bitmex-ETHUSD-1m.csv')
    print(data)
    cerebro.broker.setcash(startcash)
    cerebro.adddata(data)
    cerebro.addstrategy(SmaCross)
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.run()
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.plot(style='candle')
    

    Here is my sample data:

    ,Timestamp,Open,High,Low,Close,Volume
    0,1565528940000,210.8,210.8,210.8,210.8,9200.0
    1,1565529000000,210.8,210.8,210.8,210.8,18693.0
    2,1565529060000,210.8,210.8,210.75,210.75,210.0
    3,1565529120000,210.75,210.75,210.75,210.75,14900.0
    4,1565529180000,210.75,210.75,210.75,210.75,1000.0
    5,1565529240000,210.75,210.8,210.75,210.75,6320.0
    6,1565529300000,210.75,210.75,210.65,210.65,16310.0
    7,1565529360000,210.65,210.65,210.55,210.55,22421.0
    8,1565529420000,210.55,210.5,210.5,210.5,4624.0
    

    There are 100 records 0 - 99



  • @Feather-BTC Another good note is this is minute OHLCV Data


  • administrators

    @Feather-BTC said in BackTrader plots but does not calculate trades or profits what did I do wrong?:

    Another good note is this is minute OHLCV Data

    And have you tried telling the platform that detail? See Community - FAQ - Look for timeframe and compression



  • @backtrader This worked, thank you , now I am just trying to get my time format to output the minutes/seconds of the trade so I can track duration lol, something to play with haha.


  • administrators


Log in to reply
 

});