For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

Using Donchian Channel to execute buy order

  • 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
    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()
    data = bt.feeds.YahooFinanceCSVData(

    cerebro.adddata(data) #Insert Data.

    class DonchianChannels(bt.Strategy):
    alias = ('DCH', 'DonchianChannel',)
    lines = ( 'dch', 'dcl',) # dc middle, dc high, dc low
    params = dict(
    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
        hi, lo =,
        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:
        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 =
            if len(self) >= (self.bar_executed + 5):
                self.log("SELL CREATED {}".format(self.dataclose[0]))
                self.order = self.sell()


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

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

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

Log in to reply