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

How i can add standart or custom SL/TP ?



  • Hey guys!
    Now I have a problem with setting the usual stop loss and take profit, depending on the current price when executing the order. My code does not work correctly, and I can’t understand what the problem is, please help.

    I am also interested in how I can get out of a position, for example, crossing the upper lane of the Bollinger channel (if I'm in a long position), or when enough pips are gathered.
    My code is presented below.
    Thank you in advance.

    import backtrader.plot as plt
    %pylab qt
    import backtrader as bt
    
    # Create a Data Feed
    data = bt.feeds.GenericCSVData(
        dataname='data/ltcusdt_last.csv', # rename file
        nullvalue = 0.0,
        datetime=6,
        timeframe=bt.TimeFrame.Minutes,
        compression=1,
        dtformat=('%Y-%m-%d %H:%M'),
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1)
    
    cerebro = bt.Cerebro()
    cerebro.broker.setcash(10000.0)
    cerebro.adddata(data)
    
    
    # Create a Stratey
    class RSI_ADX_BB(bt.Strategy):
        
        params = (
            ('rsiperiod', 9),
            ('bbperiod', 200),
            ('bbstd', 2.0),
            ('rsi_up_level', 80.0),
            ('rsi_bot_level', 20.0),
            ('adxperiod', 14),
            ('stoploss', 2),
            ('takeprofit', 5)
        )
        
        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):
            # Keep a reference to the "close" line in the data[0] dataseries
            self.dataclose = self.datas[0].close
            
            self.rsi = bt.ind.RSI(self.dataclose, period=self.params.rsiperiod, upperband=self.params.rsi_up_level,
                                 lowerband=self.params.rsi_bot_level)
         
            self.bband = bt.ind.BollingerBands(self.dataclose, period=self.params.bbperiod)
            
            self.adx = bt.ind.AverageDirectionalMovementIndex(period=self.params.adxperiod)
            
            self.order_dict = {}
    
            # To keep track of pending orders
            self.order = None
    
        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, %.2f' % order.executed.price)
                elif order.issell():
                    self.log('SELL EXECUTED, %.2f' % order.executed.price)
    
                self.bar_executed = len(self)
    
            # Write down: no pending order
            self.order = None
    
    
        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:
                
                data_value = self.dataclose
                
                # Not yet ... we MIGHT BUY if ...
                if (self.rsi < self.params.rsi_bot_level) and (self.adx < 32) and (self.dataclose < self.bband.lines.bot): 
                    self.log('BUY CREATE, %.2f' % self.dataclose[0])
                    
                    tp_buy = data_value * (1.0 + self.p.takeprofit/100)
                    sl_buy = data_value * (1.0 - self.p.stoploss/100)
                    
                    self.order = self.buy(exectype=bt.Order.Stop, price=sl_buy)
    
            else:
                
                data_value = self.dataclose
                
                if (self.rsi > self.params.rsi_up_level) and (self.adx < 32) and (self.dataclose > self.bband.lines.top): 
                    self.log('SELL CREATE, %.2f' % self.dataclose[0])
                    
                    tp_sell = data_value * (1.0 - self.p.takeprofit/100)
                    sl_sell = data_value * (1.0 + self.p.stoploss/100)
    
                    self.order = self.sell(exectype=bt.Order.Stop, price=sl_sell)
        
        def notify_trade(self, trade):
            if not trade.isclosed:
                return
            self.log('OPERATION PROFIT, GROSS {}, NET {}'.format(trade.pnl, trade.pnlcomm))
                    
    cerebro.addstrategy(RSI_ADX_BB)
    
    cerebro.addsizer(bt.sizers.FixedSize, stake=100)
    cerebro.broker.setcommission(commission=0.001)
    
    print('Start Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.run()
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.plot(iplot=False)
    


  • Guys, please help, I really need this...


Log in to reply
 

});