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/

    Buy and sell on same candle

    Indicators/Strategies/Analyzers
    python 3 backtrader
    1
    1
    139
    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.
    • Misbah Asif 0
      Misbah Asif 0 last edited by

      I have to create strategy which will buy and sell on the same candle using stoploss or takeprofit.
      I did some code but am not getting the desired output actually am new to backtrader so may be I am missing something.
      I am using data from yahoofinance.

      def next(self):
          self.starttime = self.data.datetime.time()
          self.new_time = timedelta(hours=self.starttime.hour+5, minutes=self.starttime.minute+30)
          self.curr_time = datetime.strptime(str(self.new_time), '%H:%M:%S').time()
          if not self.position and self.trade <= self.p.total_trades and self.entry_time <= self.curr_time <= self.exit_time:
              if self.rsi > 30 and self.p.position_type in ["long", "both"]:
                  self.order = self.buy()
                  # exectype=bt.Order.StopLimit ,price=self.data.open[0]
                  print("Long buy entry")
                  self.have_position = True
              elif self.rsi < 70 and self.p.position_type in ["short", "both"]:
                  self.order = self.sell()
                  print("Short sell entry")
                  self.have_position = True
      
          elif self.position:
              if self.ord_type == "BUY":
                  if self.data.close <= self.stoploss:
                      self.order = self.sell()
                      self.trade = self.trade+1
                      print("Long sell on stoploss")
                      self.have_position = False
                  elif self.data.close >= self.takeprofit:
                      self.order = self.sell()
                      self.trade = self.trade + 1
                      print("Long sell on takeprofit")
                      self.have_position = False
                  elif self.curr_time >= self.exit_time:
                      self.order = self.sell()
                      self.trade = self.trade + 1
                      print("Long sell on exit time")
                      self.have_position = False
      
              elif self.ord_type == "SELL":
                  if self.data.close >= self.stoploss:
                      self.order = self.buy()
                      self.trade = self.trade + 1
                      print("Short buy on stoploss")
                      self.have_position = False
      
                  elif self.data.close <= self.takeprofit:
                      self.order = self.buy()
                      self.trade = self.trade + 1
                      print("Short buy on takeprofit")
                      self.have_position = False
      
                  elif self.curr_time >= self.exit_time:
                      self.order = self.sell()
                      self.trade = self.trade + 1
                      print("Short buy on exit time")
                      self.have_position = False
      
      
      
      def notify_order(self, order):
          if order.status in[order.Submitted, order.Accepted]:
              # print("Order Accepted")
              return
          elif order.status in [order.Completed]:
      
              if order.isbuy():
                  self.buyprice = order.executed.price
                  self.buycomm = order.executed.comm
                  # self.stoploss = self.buyprice - self.p.stoploss
                  # self.takeprofit = self.buyprice + self.p.takeprofit
                  self.stoploss = order.executed.price * (1.0 - (0.1/100))
                  self.takeprofit = order.executed.price * (1.0 + (0.1/100))
                  self.ord_type = "BUY"
              if order.issell():
                  self.sellprice = order.executed.price
                  # self.stoploss = self.sellprice + self.p.stoploss
                  # self.takeprofit = self.sellprice - self.p.takeprofit
                  self.stoploss = order.executed.price * (1.0 + (0.1/100))
                  self.takeprofit = order.executed.price * (1.0 - (0.1/100))
                  self.ord_type = "SELL"
              print("Completed %s: %s %s %s Executed Price: %.2f Size: %.2f Commission: %.2f %s" %
                    (self.ord_type, order.ref,
                     self.data.num2date(order.executed.dt).date().isoformat(),
                     self.new_time,
                     order.executed.price,
                     order.executed.size,
                     order.executed.comm,
                     order.info['name'],))
      
          elif order.status in [order.Cancelled, order.Rejected, order.Margin]:
              print("Order Cancelled/Rejected/Margin")
      
          self.order = None
      
      def notify_trade(self, trade):
          if not trade.isclosed:
              return
          print('-' * 32, ' NOTIFY TRADE ', '-' * 32)
          # print("Operation Profit, gross %2f, Net %2f" % (trade.pnl, trade.pnlcomm))
      
      def stop(self):
          print('(Stop Loss Pct: %2f, S/P Multiplier: %2f) Ending Value %.2f (Num Trades: %d)' %
                (self.p.stoploss, self.p.takeprofit, self.broker.getvalue(), self.trade))
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors