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

ATR_TrailingStop Indicator

  • Hi All!

    I've been learning Backtrader over the last 4 days or so and I'm loving it!

    No matter how hard I searched, I haven't been able to find a pre-written ATR_TrailingStop indicator so I created one. I included 'Long' in the indicator name as this was written to begin calculating values from below the close price, therefore simulating a long position.

    import backtrader as bt
    from datetime import datetime
    import backtrader.indicators as btind
    import matplotlib.pyplot as plt
    %matplotlib inline
    class ATR_TS_Long(bt.Indicator):
        alias = ('ATR_TRAILINGSTOP',)
        lines = ('atr_ts',)
        params = (
            ('atr_period', 14),
            ('atr_mult', 3),
        plotinfo = dict(subplot=False,)  
        plotlines = dict(
            atr_ts = dict(ls = '-'), 
        def __init__(self):
            self.atr = btind.ATR(, period = self.params.atr_period)
            self.bigatr = self.atr * self.p.atr_mult 
            self.buysell = 1
            self.l.atr_ts = - self.bigatr #first calculated value is below close price therefore simulating a long position.
            btind.CrossUp(, self.l.atr_ts)
            btind.CrossDown(, self.l.atr_ts)
        def next(self):
            if self.buysell > 0: 
                self.lines.atr_ts[0] =[0] - self.bigatr[0]
                self.l.atr_ts[0] = max(self.l.atr_ts[-1], self.l.atr_ts[0])
                if self.lines.atr_ts > 
                    self.lines.atr_ts[0] =[0] + self.bigatr[0]
                    self.buysell = -1
            elif self.buysell < 0:
                self.lines.atr_ts[0] =[0] + self.bigatr[0]
                self.l.atr_ts[0] = min(self.l.atr_ts[-1], self.l.atr_ts[0])
                if self.lines.atr_ts <
                    self.l.atr_ts[0] =[0] - self.bigatr[0]
                    self.buysell = 1

    Here is the link to the .ipynb file on Github. ATR_TS_Long.ipynb

    Any feedback at all is greatly appreciated.

Log in to reply