Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    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 ?

    General Code/Help
    1
    2
    186
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Pavel Vasyl'ev
      Pavel Vasyl'ev last edited by

      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)
      
      1 Reply Last reply Reply Quote 0
      • Pavel Vasyl'ev
        Pavel Vasyl'ev last edited by

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

        1 Reply Last reply Reply Quote 0
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors