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/

    Stoploss Strategy of looking back X number of candles to see if it breached Y% relative to filled price.

    General Code/Help
    2
    5
    380
    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.
    • J
      jennywestwong last edited by

      Hi fellow backtraders, I am trying to write a stoploss reversal strategy where it can look at the last 5 candles' price, and check if in total, breached 0.5% relative to the executed price.

      However, I am getting weird result where it would buy and sell every candle. I am guessing most likely it is the def long_stoploss and def_short_stoploss that is not written correctly. If someone can please shine some light on my codes, it would be much appreciated. Thank you in advance.

      class RSI(bt.Strategy):
      
          def log(self, txt, dt=None):
              # Logging function for this strategy
              dt = dt or self.datas[0].datetime.datetime(0)
              print('%s, %s' % (dt.isoformat(), txt))
      
          def __init__(self):
              self.rsi = bt.indicators.RSI_Safe(self.data.close, period=6)
              
              self.crossover = bt.indicators.CrossUp(self.smooth_rsi, 30)
              self.crossunder = bt.indicators.CrossDown(self.smooth_rsi, 70)
      
          def notify_order(self, order):
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log('BUY EXECUTED, Price: %.2f' % order.executed.price)
                      self.buyprice = order.executed.price
                  elif order.issell():
                      self.log('SELL EXECUTED, Price: %.2f' % order.executed.price)
                  self.bar_executed = len(self)
      
          def next(self):
              def long_stoploss():     #if high is 0.5% more than filled price for the past 5 candles
                  self.data.loc[self.data['high'] > self.order.executed.price * 1.005, 'long_stoploss'] = 1     
                  self.data.loc[self.data['high'] <= self.order.executed.price * 1.005, 'long_stoploss'] = 0
                  flipLong = sum(self.data.long_stoploss[-5:])     #look back last 5/5 candles breached 0.5%
      
              def short_stoploss():      #if low is 0.5% less than filled price for the past 5 candles
                  self.data.loc[self.data['low'] < self.order.executed.price * 1.005, 'short_stoploss'] = 1
                  self.data.loc[self.data['low'] >= self.order.executed.price * 1.005, 'short_stoploss'] = 0
                  flipshort = sum(self.data.short_stoploss[-5:])     #look back last 5/5 candles breached 0.5%
      
              if not self.position:
                  if self.crossover:    
                      self.buy()                
                  if self.crossunder:
                      self.sell()
      
              if self.position.size!=0:
                  if long_stoploss:
                      self.sell(size=2)     #sell 2 to reverse
                  if short_stoploss:
                      self.buy(size=2)     #buy 2 to reverse
                                             
      

      Results (only a small portion):

      2020-01-02T23:15:00, SELL EXECUTED, Price: 3263.00
      2020-01-02T23:15:00, SELL EXECUTED, Price: 3263.00
      2020-01-02T23:20:00, BUY EXECUTED, Price: 3262.50
      2020-01-02T23:20:00, BUY EXECUTED, Price: 3262.50
      2020-01-02T23:25:00, SELL EXECUTED, Price: 3262.50
      2020-01-02T23:25:00, SELL EXECUTED, Price: 3262.50
      2020-01-02T23:30:00, BUY EXECUTED, Price: 3262.25
      2020-01-02T23:30:00, BUY EXECUTED, Price: 3262.25
      2020-01-02T23:35:00, SELL EXECUTED, Price: 3262.25
      2020-01-02T23:35:00, SELL EXECUTED, Price: 3262.25
      2020-01-02T23:40:00, BUY EXECUTED, Price: 3262.00
      2020-01-02T23:40:00, BUY EXECUTED, Price: 3262.00
      2020-01-02T23:45:00, SELL EXECUTED, Price: 3261.75
      2020-01-02T23:45:00, SELL EXECUTED, Price: 3261.75
      2020-01-02T23:50:00, BUY EXECUTED, Price: 3261.75
      2020-01-02T23:50:00, BUY EXECUTED, Price: 3261.75
      2020-01-02T23:55:00, SELL EXECUTED, Price: 3261.25
      2020-01-02T23:55:00, SELL EXECUTED, Price: 3261.25
      2020-01-03T00:00:00, BUY EXECUTED, Price: 3261.00
      2020-01-03T00:00:00, BUY EXECUTED, Price: 3261.00
      

      Figure_0.png

      1 Reply Last reply Reply Quote 0
      • J
        jennywestwong last edited by

        @backtrader, @ab_trader, @vladisld, @run-out, @RandyT I see that you guys are the most skilled and active members on this community and would love to hear if you guys have any idea if this is approachable.

        1 Reply Last reply Reply Quote 0
        • run-out
          run-out last edited by

          You do have a lot going on that's probably causing you some trouble.

          1. You are including methods inside of another method. long_stoploss inside next. This is bad practice.
          2. You are trading self. data as a pandas object using .loc. It is not a pandas object.
          3. Where does self.smooth_rsi come from? Maybe it's a thing I don't know about.
          4. Your long_stoploss and short stoploss should be created as indicators.
          5. You are calling self.crossover in next without identifying the bar using [0]
          6. You are calling long_stoploss without using method () brackets.

          The fact that you are getting any results at all is a mystery to me. I'm not trying to be harsh. My best advice for you at this time would be to spend time in the docs and replicate the examples you see there. Backtrader has a bit of a learning curve and it's difficult to wing it.

          Good luck and come back again after you have a chance to absorb some of the material.

          RunBacktest.com

          1 Reply Last reply Reply Quote 2
          • J
            jennywestwong last edited by

            @run-out said in Stoploss Strategy of looking back X number of candles to see if it breached Y% relative to filled price.:

            self.smooth_rsi c

            Thank you for the reply @run-out . I am a python beginner and even my fundamentals are not in place. I have been trying hard to translate my TradingView strategy into python just for backtesting because TradingView's backtest is very limited.

            run-out 1 Reply Last reply Reply Quote 0
            • run-out
              run-out @jennywestwong last edited by

              @jennywestwong said in Stoploss Strategy of looking back X number of candles to see if it breached Y% relative to filled price.:

              number

              No problem. I'm sure if you spend a couple of weeks working through the docs, you'll be all set. I think this is how we all started. :o)

              RunBacktest.com

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