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/

    Still confused in Buy at Open and Sell at close

    General Code/Help
    1
    1
    145
    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.
    • Rushi Chaudhari
      Rushi Chaudhari last edited by

      Hi everyone,

      This post is similar to https://community.backtrader.com/topic/2648/buy-at-open-price-and-close-at-close-price-in-the-same-day, but I'm still confused. I have used cheat_on_open=True and also cerebro.broker.set_coc(True)

      class TestStrat(bt.Strategy):
          # list of parameters which are configurable for the strategy
          params = dict(
              pfast=15,  # period for the fast moving average
              pslow=30   # period for the slow moving average
          )
      
      
          def log(self, txt, dt=None):
              # return
              ''' Logging function for this strategy'''
              dt = dt or self.datas[0].datetime.datetime(0)
              print('%s, %s' % (dt, txt))
          
          def notify_order(self, order):
              if order.status in [order.Submitted, order.Accepted, order.Partial]:
                  # Buy/Sell order submitted/accepted to/by broker/partially filled - Nothing to do
                  return
      
      		# Check if an order has been completed
              if order.status in [order.Completed]:
                  if order.isbuy():
                      self.log('BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f, tradeID: %d' %(order.executed.price, order.executed.value, order.executed.comm, order.tradeid))
                  elif order.issell():
                      self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f, tradeID: %d' %(order.executed.price, order.executed.value, order.executed.comm, order.tradeid))
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected')
              
          def notify_trade(self, trade):
              if trade.justopened:
                  self.log('New trade just opened with id %d'%(trade.tradeid))
                  self.livetrades[trade.tradeid] = trade
              elif trade.isclosed:
                  self.log('A trade just closed with id %d'%(trade.tradeid))
                  self.livetrades.pop(trade.tradeid)
              else:
                  self.log('Trade id %d updated'%(trade.tradeid))
              
          def __init__(self):
              self.livetrades = {}
              self.counter = 0
              
              self.fastMA = bt.indicators.EMA(period=self.p.pfast)
              self.slowMA = bt.indicators.EMA(period=self.p.pslow)
              self.crossover = bt.indicators.CrossOver(self.fastMA, self.slowMA) 
              self.i=0
              self.longCrossed = False
              self.shortCrossed = False
              self.buysize=0
      
          def next(self):
              self.i += 1
              if self.position:
                  self.close(size=self.position.size)
                  print('selling' + str(self.data.close[0]))
      
          def next_open(self):
              self.i += 1
              if self.crossover > 0:  # if fast crosses slow to the upside
                  self.longCrossed = True
              if self.crossover < 0:
                  self.longCrossed = False
      
              if self.longCrossed and (self.data.open[0] > self.fastMA[-1]):
                  print('buying' + str(self.data.open[0]))
                  buysize =  int(self.broker.get_cash() / self.data.close[0])
                  self.buy(size=buysize, coc=False)
      
      
      
      
      
      cerebro = bt.Cerebro(writer=True, stdstats=True, cheat_on_open=True)
      cerebro.adddata(bt.feeds.PandasData(dataname=hourlydf))
      print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
      cerebro.addstrategy(TestStrat) 
      cerebro.addwriter(bt.WriterFile, csv=True)
      cerebro.addanalyzer(BarAnalysis, _name="bar_data")
      cerebro.broker.set_coc(True)
      strat = cerebro.run()
      cerebro.plot(style='candlestick', volume=False)
      print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      bar_data_res = strat[0].analyzers.bar_data.get_analysis()
      header = ["date", "open", "high", "low", "close", "position", "value", "cash", "slowMA", "fastMA"]
      
      df = pd.DataFrame(bar_data_res, columns= header)
      df.to_csv('strategy.csv', index=False)
      

      This is not executing the buy at open and sell at close during the same day. Can anyone help where am I going wrong?

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