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/

    Issue sell order after a condition is met when in a long position

    General Code/Help
    1
    3
    37
    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.
    • V
      Vypy1 last edited by

      How do I issue a sell order for long position after it meets a certain condition?

      My setup is to issue a buy order when price breaks out from a 20 period high and issue a stop 2 ATR below the price.

      Then Issue another sell order only when price breaks out of a 10 period low (this is the condition). I am trying to place this order in next if there is an existing position but it seems to not go through, request you to help with this.

      My code is below.

      class StratOne(bt.Strategy):
          
          params = (('fma', 20), ('sma', 50), ('trail', 0.08),)
          
          
          def __init__(self):
              
              self.open = self.data.open
              self.close = self.data.close
              self.high = self.data.high
              self.low = self.data.low
                  
              self.atr = bt.talib.ATR(self.high, self.low, self.close, timeperiod = 14)
              self.atrema = bt.talib.EMA(self.atr, timeperiod = 30)
              self.highest = bt.indicators.Highest(self.high, period = 20)
              self.lowest = bt.indicators.Lowest(self.low, period = 20)
              self.highest_10 = bt.indicators.Highest(self.high, period = 10)
              self.lowest_10 = bt.indicators.Lowest(self.low, period = 10)
                  
              self.orders = None
              self.orefs = []
      
      
                   
          def log(self, txt, dt=None):
              dt = self.datas[0].datetime.date()
              print(f'Date: {dt}, {txt}')
              
          
          def notify_order(self, order):
              
                  
              if order.status in [order.Submitted, order.Accepted]:
                  return
      
      
              if order.status in [order.Completed]:
                  
                  if order.isbuy():
                      
                      self.log(f'BUY EXECUTED: {order.executed.price}, Cost: {order.executed.value}')
      
                      self.execprice = order.executed.price
                      self.totalcost = order.executed.value
                      self.size = order.executed.size
                      
          
                      
      
                  elif order.issell():
                      self.sellprice = order.executed.price
                      self.sellcost = order.executed.value
                      self.log(f'SELL EXECUTED: {self.sellprice}, Cost: {self.sellcost}')
      
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected')
      
      
              order_name = ['main', 'stop', 'limit', 'close']
              
              if not order.alive() and order.ref in self.orefs:
                  self.orefs.remove(order.ref)
                  print(f'ORDERS ALIVE: {self.orefs}')
      
      
          
          def notify_trade(self, trade):
              if trade.isopen:
                  return  
              
              
              else:
                  self.log(f'OPERATION PROFIT: GROSS {trade.pnl}, NET {trade.pnlcomm}, Trade PnL: {trade.pnlcomm/self.totalcost}')
                  self.log(f'Updated Account Balance: {cerebro.broker.getcash()}')
          
          
                  
                  
          def next(self):
          
              pos = self.getposition().size
              self.log(f'Close: {self.close[0]}, Pos: {pos}, HIGH: {self.high[0]}, LOW: {self.low[0]}, HIGHEST: {self.highest_10[0]}, LOWEST: {self.lowest_10[0]}')
      
              if self.orefs:
                  return
              
              if not self.position:
      
                  if self.close[0] > self.highest[-1]:
                          
                      p1 = self.open[1]
                      p2 = p1 - (self.atrema * 2)
      
                      o1 = self.buy()
                      o2 = self.sell(exectype=bt.Order.Stop, price = p2)
      
                          
                      self.log(f'BUY CREATED: {o1.created.price}, STOP: {p2}, SIZE: {o1.created.size}')
          
                      self.orders = [o1, o2]
                      self.orefs = [o1.ref, o2.ref]
                      self.log(f'FIRST ORDERS: {self.orefs}')
      
             
                      
              else:
                          
                  if self.low[0] < self.lowest_10[-1]:
                      
                      sell_order = self.orders[1]
                      self.log(f'SELL ORDER: {sell_order}')
                      
                      p3 = self.lowest_10[-1] - 1
                          
                      o3 = self.sell(size = self.size)
                      self.orders = [o3]
                      self.orefs = [o3.ref]
                      self.log(f'TARGET SELL: {self.orefs}')
                          
                          
      
      
                      
      cerebro = bt.Cerebro()
      cerebro.broker.set_cash(200000)
      
      print(f'Starting Portfolio Value: {cerebro.broker.getvalue()}')
      
      data = pandas_data_ext(dataname=hdfcbank, datetime=None, open=-1, high=-1, low=-1, close=-1, volume=-1,
                              Peaks=-1, Trough=-1)
      cerebro.adddata(data, name = 'hdfcbank')
      
      
      cerebro.addstrategy(StratOne)
      cerebro.addsizer(bt.sizers.FixedSize, stake = 10)
      cerebro.addanalyzer(trades_list, _name = 'listrades')
      
      
      strat = cerebro.run(tradehistory = True)
      strats = strat[0].analyzers.listrades.get_analysis()
      listrades = pd.DataFrame(strats)
      
      
      print(f'Final Portfolio Value: {cerebro.broker.getvalue()}')
      
      V 1 Reply Last reply Reply Quote 0
      • V
        Vypy1 @Vypy1 last edited by

        @vypy1 An update here is that I am able to issue my sell order for a long position after a condition is met if I don't issue my stop order along with creating a buy order.

        Why would this be the case? Can someone please help here!

        V 1 Reply Last reply Reply Quote 0
        • V
          Vypy1 @Vypy1 last edited by

          @vypy1 Also, I think a probable explanation to this is that when I issue a stop order along with my buy order, since I have set the strategy in such a way that if there is a pending order (which is stop order in this case), the strategy will not issue another order.

          Hence I guess when the condition is being met the strategy does not issue another order.

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