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/

    Using Donchian Channel to execute buy order

    General Code/Help
    2
    3
    269
    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.
    • Edward Owen
      Edward Owen last edited by

      hi,

      I am new to backtrader and even python. I know I shouldn't be rushing but I just wanna get this to work. I have only watched a few tutorials on backtrading but not much.

      So I am planning to use the provided
      https://www.backtrader.com/recipes/indicators/donchian/donchian/
      and use it to execute a buy order on DC 5 day.

      Here is the code
      import backtrader as bt
      import datetime

      cerebro = bt.Cerebro()
      cerebro.broker.set_cash(1000000)
      data = bt.feeds.YahooFinanceCSVData(
      dataname="oracle.csv",
      fromdate=datetime.datetime(2000,1,1),
      todate=datetime.datetime(2000,12,31),
      reverse=False)

      cerebro.adddata(data) #Insert Data.

      class DonchianChannels(bt.Strategy):
      #DONCHIAN CHANNELS PLOTTING
      alias = ('DCH', 'DonchianChannel',)
      lines = ( 'dch', 'dcl',) # dc middle, dc high, dc low
      params = dict(
      period=5,
      lookback=-1, #look at Params Note.
      )
      plotinfo = dict(subplot=False) # plot along with data
      plotlines = dict(
      dch=dict(_samecolor=True), # use same color as prev line (dcm)
      dcl=dict(_samecolor=True), # use same color as prev line (dch)
      )

      def __init__(self):
          self.dataclose = self.datas[0].close
          self.order = None
          #DC
          hi, lo = self.data.high, self.data.low
          if self.p.lookback:  # move backwards as needed
              hi, lo = hi(self.p.lookback), lo(self.p.lookback)
          self.l.dch = bt.ind.Highest(hi, period=self.p.period)
          self.l.dcl = bt.ind.Lowest(lo, period=self.p.period)
          self.l.dcm = (self.l.dch + self.l.dcl) / 2.0  # avg of the above
          
      def next(self):
          # Simply log the closing price of the series from the reference
          self.log('Close, %.2f' % self.dataclose[0])
      
          if self.order:
              return
      
          if not self.position:
              if self.dataclose[-1] < self.l.dch:
                  # previous close less than the previous previous close
      
                  # BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  self.order = self.buy()
          else:
              if len(self) >= (self.bar_executed + 5):
                  self.log("SELL CREATED {}".format(self.dataclose[0]))
                  self.order = self.sell()
      

      cerebro.addstrategy(DonchianChannels)

      cerebro.addsizer(bt.sizers.FixedSize, stake=1000)
      print("Starting Portfolio :%.2f" % cerebro.broker.getvalue())
      cerebro.run()
      print("Final Portfolio Value:%.2f" % cerebro.broker.getvalue())
      cerebro.plot(style="candlestick",barup='green', bardown='red')

      1 Reply Last reply Reply Quote 0
      • A
        ab_trader last edited by

        Do you have an issue with the code provided? If yes, describe an issue and provide some outputs showing it.

        • If my answer helped, hit reputation up arrow at lower right corner of the post.
        • Python Debugging With Pdb
        • New to python and bt - check this out
        1 Reply Last reply Reply Quote 0
        • Edward Owen
          Edward Owen last edited by

          ah, i shouldve put the results, sorry. I already found the fix :D

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