Created
September 20, 2023 02:46
-
-
Save syuraj/390f84dba55e8450e267554b10f8a319 to your computer and use it in GitHub Desktop.
Backtrader SuperTrend Indicator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SuperTrend(bt.Indicator): | |
lines = ('super_trend',) | |
params = ( | |
('multiplier', 12.0), | |
('atr_period', 3), | |
) | |
def __init__(self): | |
self.isDownTrend = -1 | |
self.isUpTrend = 1 | |
self.trendDirection = self.isDownTrend | |
hl2 = (self.data.high + self.data.low) / 2.0 | |
self.atrValue = bt.indicators.ATR(self.data, period=self.p.atr_period) | |
self.basicUpperBand = hl2 + (self.p.multiplier * self.atrValue) | |
self.basicLowerBand = hl2 - (self.p.multiplier * self.atrValue) | |
self.upperBand = None | |
self.lowerBand = None | |
def next(self): | |
if self.upperBand is None: | |
self.upperBand = self.basicUpperBand[0] | |
else: | |
self.upperBand = self.basicUpperBand[0] if (self.basicUpperBand[0] < self.upperBand or self.data.close[-1] > self.upperBand) else self.upperBand | |
if self.lowerBand is None: | |
self.lowerBand = self.basicLowerBand[0] | |
else: | |
self.lowerBand = self.basicLowerBand[0] if (self.basicLowerBand[0] > self.lowerBand or self.data.close[-1] < self.lowerBand) else self.lowerBand | |
if self.trendDirection == self.isDownTrend and self.data.close[0] > self.upperBand: | |
self.trendDirection = self.isUpTrend | |
elif self.trendDirection == self.isUpTrend and self.data.close[0] < self.lowerBand: | |
self.trendDirection = self.isDownTrend | |
self.lines.super_trend[0] = self.lowerBand if self.trendDirection == self.isUpTrend else self.upperBand |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment