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/

    Issuing counter orders for long and short strategy via notify order

    General Code/Help
    1
    1
    22
    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

      Hi, I wanted to know how can I issue a sell order for a long trade and buy order for a short trade both via notify order? Right now, when I try to do this, it does not behave as expected. My code is below and I am also attaching the logs.

      class test_strat(bt.Strategy):
          
          params = (('fma', 20), ('sma', 50), ('trail', 0.08),)
          
          
          def __init__(self):
              
              self.open = self.data.open
              self.high = self.data.high
              self.low = self.data.low
              self.close = self.data.close
              self.fma = bt.indicators.EMA(self.close, period = self.p.fma)
              self.sma = bt.indicators.EMA(self.close, period = self.p.sma)
              self.cross = bt.indicators.CrossOver(self.fma, self.sma)
      
              
              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.execprice = order.executed.price
                          self.totalcost = order.executed.value   
                          self.sellsize = order.executed.size
                          
                          self.log(f'BUY EXECUTED: {self.execprice}, SIZE: {self.sellsize}, COST: {self.totalcost}')
      
                          o2 = self.sell(size = self.sellsize, exectype=bt.Order.StopTrail, trailpercent = 0.05)
                          
                          
                          self.orders = [o2]
                          self.orefs = [o2.ref]
        
      
                          self.log(f'TRAILING PRICE: {self.execprice * 1.05}, ORDER ID: {self.orefs}, CASH: {cerebro.broker.getcash()}')
      
      
                      elif order.issell():
                          
                          
                          self.sellprice = order.executed.price
                          self.sellcost = order.executed.value
                          self.buysize = order.executed.size
                          
                          self.log(f'SELL EXECUTED: {self.sellprice}, SIZE: {self.buysize}, COST: {self.sellcost}')
                          
                          o4 = self.buy(size = self.buysize, exectype=bt.Order.StopTrail, trailpercent = 0.05)
                          
                          self.orders = [o4]
                          self.orefs = [o4.ref]
                          
                          self.log(f'TRAILING PRICE: {self.sellprice * 1.05}, ORDER ID: {self.orefs}, CASH: {cerebro.broker.getcash()}')
                          
      
                  elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                      self.log('Order Canceled/Margin/Rejected')
      
                  
                  if not order.alive() and order.ref in self.orefs:
                      self.orefs.remove(order.ref)
                      self.log(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):
              
              self.log(f'Close: {self.close[0]}')
              
              if self.orefs:
                  return
              
              if not self.position:
                  
                  if self.cross > 0:
                      
                      p1 = self.open[1]
                      
                      o1 = self.buy()
      #                 o2 = self.sell(exectype=bt.Order.StopTrail, price = p1, trailpercent = 0.05)
                      
      
                      self.orders = [o1]
                      self.orefs = [o1.ref]
                      self.log(f'BUY CREATED: {o1.created.price}, TRAILING STOP AT: {p1 * 0.95}, SIZE: {o1.created.size}, CASH: {cerebro.broker.getcash()}')
      #                 self.log(f'BUY CREATED: {o1.created.price}, SIZE: {o1.created.size}, ORDER ID: {self.orefs}, CASH: {cerebro.broker.getcash()}')
          
                  elif self.cross < 0:
                      
                      p2 = self.open[1]
                      
                      o3 = self.sell()
      #                 o4 = self.buy(exectype=bt.Order.StopTrail, price = p2, trailpercent= 0.05)
                      self.log(f'SELL CREATED: {o3.created.price}, TRAILING STOP AT: {p2 * 1.05}, SIZE: {o3.created.size}, CASH: {cerebro.broker.getcash()}')
      #                 self.log(f'SELL CREATED: {o3.created.price}, SIZE: {o3.created.size}, ORDER ID: {self.orefs} , CASH: {cerebro.broker.getcash()}')
                  
                      self.orders = [o3]
                      self.orefs = [o3.ref]
      #                 self.log(f'SELL CREATED: {o3.created.price}, SIZE: {o3.created.size}, ORDER ID: {self.orefs}')
      
      
                      
                      
                      
      cerebro = bt.Cerebro()
      cerebro.broker.set_cash(200000)
      
      
      print(f'Starting Portfolio Value: {cerebro.broker.getvalue()}')
      
      
      data = bt.feeds.PandasData(dataname=hdfcbank, datetime=None, open=-1, high=-1, low=-1, close=-1, volume=-1)
      cerebro.adddata(data, name = 'hdfcbank')
      
      
      cerebro.addstrategy(test_strat)
      cerebro.addsizer(MySizer)
      cerebro.addanalyzer(trades_list, _name='tradelist')
      cerebro.addanalyzer(CashMarket, _name='cash')
      
      
      strat = cerebro.run(tradehistory = True)
      tradeslist = strat[0].analyzers.tradelist.get_analysis()
      cash = strat[0].analyzers.cash.get_analysis()
      trades = pd.DataFrame(tradeslist)
      
      
      
      print(f'Final Portfolio Value: {cerebro.broker.getvalue()}')
      

      LOGS:
      Notice that my first trade is a short trade that is bought back on 2008-02-04 and instead of that being the end of the trade, the buy trade is also issuing a trailing price.

      My expectation is that my short trade should close after being bought back. Or Long trade should do the same. Instead here my covering order is also issuing trailing stops.

      Date: 2008-01-11, Close: 176.46
      Date: 2008-01-14, Close: 178.32
      Date: 2008-01-15, Close: 178.9
      Date: 2008-01-16, Close: 167.38
      Date: 2008-01-17, Close: 164.36
      Date: 2008-01-18, Close: 157.1
      Date: 2008-01-21, Close: 150.71
      Date: 2008-01-22, Close: 142.64
      Date: 2008-01-23, Close: 153.43
      Date: 2008-01-24, Close: 151.04
      Date: 2008-01-24, SELL CREATED: 151.04, TRAILING STOP AT: 162.12, SIZE: -259, CASH: 200000.0
      Date: 2008-01-25, SELL EXECUTED: 154.4, SIZE: -259, COST: -39989.6
      Date: 2008-01-25, TRAILING PRICE: 162.12, ORDER ID: [5986], CASH: 239989.6
      Date: 2008-01-25, Close: 160.85
      Date: 2008-01-28, Close: 159.02
      Date: 2008-01-29, Close: 153.74
      Date: 2008-01-30, Close: 153.3
      Date: 2008-01-31, Close: 156.96
      Date: 2008-02-01, Close: 157.1
      Date: 2008-02-04, BUY EXECUTED: 162.38, SIZE: 259, COST: -39989.6
      Date: 2008-02-04, TRAILING PRICE: 170.499, ORDER ID: [5987], CASH: 197933.18
      Date: 2008-02-04, OPERATION PROFIT: GROSS -2066.8199999999974, NET -2066.8199999999974, Trade PnL: 0.05168393782383413
      Date: 2008-02-04, Updated Account Balance: 197933.18
      Date: 2008-02-04, Close: 154.74
      Date: 2008-02-05, Close: 151.23
      Date: 2008-02-06, SELL EXECUTED: 147.00300000000001, SIZE: -259, COST: -38073.777
      Date: 2008-02-06, TRAILING PRICE: 154.35315000000003, ORDER ID: [5988], CASH: 236006.957
      Date: 2008-02-06, Close: 150.01
      Date: 2008-02-07, Close: 149.18
      Date: 2008-02-08, Close: 144.2
      Date: 2008-02-11, Close: 141.08
      Date: 2008-02-12, Close: 140.77
      Date: 2008-02-13, BUY EXECUTED: 147.8085, SIZE: 259, COST: -38073.777
      Date: 2008-02-13, TRAILING PRICE: 155.198925, ORDER ID: [5989], CASH: 197724.5555
      Date: 2008-02-13, OPERATION PROFIT: GROSS -208.6244999999987, NET -208.6244999999987, Trade PnL: 0.005479480010611994
      Date: 2008-02-13, Updated Account Balance: 197724.5555
      Date: 2008-02-13, Close: 146.85
      Date: 2008-02-14, Close: 153.65
      Date: 2008-02-15, Close: 156.23
      Date: 2008-02-18, Close: 155.69
      Date: 2008-02-19, Close: 157.19
      Date: 2008-02-20, Close: 153.72
      Date: 2008-02-21, Close: 154.09
      Date: 2008-02-22, SELL EXECUTED: 147.04, SIZE: -259, COST: -38083.36
      Date: 2008-02-22, TRAILING PRICE: 154.392, ORDER ID: [5990], CASH: 235807.9155
      Date: 2008-02-22, Close: 147.43
      Date: 2008-02-25, Close: 142.18
      Date: 2008-02-26, Close: 145.49
      Date: 2008-02-27, Close: 145.23
      Date: 2008-02-28, Close: 147.26
      Date: 2008-02-29, Close: 145.68
      Date: 2008-03-03, Close: 138.99
      Date: 2008-03-04, Close: 135.18
      Date: 2008-03-05, Close: 133.28
      Date: 2008-03-07, Close: 128.23
      Date: 2008-03-10, Close: 131.15
      Date: 2008-03-11, BUY EXECUTED: 134.64149999999998, SIZE: 259, COST: -38083.36
      Date: 2008-03-11, TRAILING PRICE: 141.373575, ORDER ID: [5991], CASH: 200935.767
      Date: 2008-03-11, OPERATION PROFIT: GROSS 3211.211500000003, NET 3211.211500000003, Trade PnL: -0.08432059303590868
      Date: 2008-03-11, Updated Account Balance: 200935.767
      Date: 2008-03-11, Close: 133.32
      Date: 2008-03-12, Close: 137.06
      Date: 2008-03-13, SELL EXECUTED: 130.207, SIZE: -259, COST: -33723.613
      Date: 2008-03-13, TRAILING PRICE: 136.71735, ORDER ID: [5992], CASH: 234659.38
      Date: 2008-03-13, Close: 129.92
      Date: 2008-03-14, Close: 131.55
      Date: 2008-03-17, Close: 122.6
      Date: 2008-03-18, Close: 123.1
      Date: 2008-03-19, BUY EXECUTED: 128.73, SIZE: 259, COST: -33723.613
      Date: 2008-03-19, TRAILING PRICE: 135.16649999999998, ORDER ID: [5993], CASH: 201318.31
      Date: 2008-03-19, OPERATION PROFIT: GROSS 382.54300000000103, NET 382.54300000000103, Trade PnL: -0.011343476157195881
      Date: 2008-03-19, Updated Account Balance: 201318.31
      Date: 2008-03-19, Close: 127.26
      Date: 2008-03-24, Close: 134.19
      Date: 2008-03-25, Close: 141.4
      Date: 2008-03-26, Close: 143.92
      Date: 2008-03-27, Close: 143.32
      Date: 2008-03-28, SELL EXECUTED: 136.724, SIZE: -259, COST: -35411.515999999996
      Date: 2008-03-28, TRAILING PRICE: 143.5602, ORDER ID: [5994], CASH: 236729.826
      Date: 2008-03-28, Close: 140.7
      Date: 2008-03-31, Close: 133.13
      Date: 2008-04-01, Close: 130.96
      Date: 2008-04-02, BUY EXECUTED: 138.0, SIZE: 259, COST: -35411.515999999996
      Date: 2008-04-02, TRAILING PRICE: 144.9, ORDER ID: [5995], CASH: 200987.826
      Date: 2008-04-02, OPERATION PROFIT: GROSS -330.4840000000027, NET -330.4840000000027, Trade PnL: 0.009332670196893088
      Date: 2008-04-02, Updated Account Balance: 200987.826
      Date: 2008-04-02, Close: 132.8
      Date: 2008-04-03, Close: 133.12
      Date: 2008-04-04, Close: 129.39
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors