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 #https://help.stockopedia.com/product-guide/charts/overlays/atr-trailing-stops/ 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(self.data, period = self.params.atr_period) self.bigatr = self.atr * self.p.atr_mult self.buysell = 1 self.l.atr_ts = self.data.close - self.bigatr #first calculated value is below close price therefore simulating a long position. btind.CrossUp(self.data.close, self.l.atr_ts) btind.CrossDown(self.data.close, self.l.atr_ts) def next(self): if self.buysell > 0: self.lines.atr_ts[0] = self.data.close[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.data.close: self.lines.atr_ts[0] = self.data.close[0] + self.bigatr[0] self.buysell = -1 elif self.buysell < 0: self.lines.atr_ts[0] = self.data.close[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.data.close: self.l.atr_ts[0] = self.data.close[0] - self.bigatr[0] self.buysell = 1
Here is the link to the .ipynb file on Github.
https://github.com/jantarktic/ATR_Trailing_Stop_Indicator/blob/master/btind ATR_TS_Long.ipynbAny feedback at all is greatly appreciated.
Cheers! -
@Jayden-Clark said in ATR_TrailingStop Indicator:
https://github.com/jantarktic/ATR_Trailing_Stop_Indicator/blob/master/btind ATR_TS_Long.ipynb
Not able to view your Notebook on Github.
-
@Bo-Vargas here is the link to the repository: