SuperTrend Indicator
Overview
SuperTrend is a trend-following indicator that combines ATR volatility with price action to generate reliable trend signals. This implementation will leverage our existing ATR implementation and add advanced trend detection capabilities.
Status
- Domain Model Design
- Core Implementation
- API Integration
- Testing
- Documentation
Components
1. Domain Model
interface SuperTrendData {
// Core Values
value: number; // Current SuperTrend value
direction: TrendDirection; // Current trend direction
stop_loss: number; // Current stop level
// Analysis
trend_strength: TrendStrength; // Current trend strength
reversal_state: ReversalState; // Reversal detection
distance_to_price: number; // Distance from current price
// Signals
signal: SignalType; // Trading signal
signal_strength: number; // Signal confidence (0-1)
}
enum TrendDirection {
UP = 'up',
DOWN = 'down',
}
enum ReversalState {
POTENTIAL_REVERSAL = 'potential_reversal',
CONFIRMED_REVERSAL = 'confirmed_reversal',
NO_REVERSAL = 'no_reversal',
}
2. Configuration
interface SuperTrendSettings {
atr_period: number; // ATR calculation period (default: 10)
atr_multiplier: number; // ATR multiplier (default: 3.0)
reversal_threshold: number; // % for reversal confirmation
trend_strength_periods: number; // Periods for strength calculation
}
3. API Endpoints
REST API
GET /v1/supertrend- Parameters:
symbol: Trading pairtimeframe: Candle timeframeatr_period: Optional ATR periodatr_multiplier: Optional multiplier
- Parameters:
WebSocket
- Channel:
supertrend- Updates: Value, direction, and signals
- Frequency: On candle close
Technical Implementation
1. Core Calculation
def compute_supertrend(
df: pd.DataFrame,
settings: SuperTrendSettings
) -> pd.DataFrame:
"""
Calculate SuperTrend indicator.
Args:
df: DataFrame with OHLCV data
settings: SuperTrend calculation settings
Returns:
DataFrame with SuperTrend calculations
"""
# Calculate ATR
df['atr'] = compute_atr(df, settings.atr_period)
# Calculate basic bands
df['basic_upper'] = (
(df['high'] + df['low']) / 2 +
(settings.atr_multiplier * df['atr'])
)
df['basic_lower'] = (
(df['high'] + df['low']) / 2 -
(settings.atr_multiplier * df['atr'])
)
# Initialize SuperTrend
df['supertrend'] = 0.0
df['direction'] = TrendDirection.UP
# Calculate SuperTrend values
for i in range(1, len(df)):
curr_close = df['close'].iloc[i]
prev_supertrend = df['supertrend'].iloc[i-1]
curr_upper = df['basic_upper'].iloc[i]
curr_lower = df['basic_lower'].iloc[i]
prev_direction = df['direction'].iloc[i-1]
if prev_direction == TrendDirection.UP:
df.loc[df.index[i], 'supertrend'] = max(
curr_lower,
prev_supertrend if curr_close > prev_supertrend else curr_upper
)
else:
df.loc[df.index[i], 'supertrend'] = min(
curr_upper,
prev_supertrend if curr_close < prev_supertrend else curr_lower
)
# Update direction
df.loc[df.index[i], 'direction'] = (
TrendDirection.UP
if curr_close > df['supertrend'].iloc[i]
else TrendDirection.DOWN
)
return df
2. Analysis Functions
def analyze_trend_strength(
df: pd.DataFrame,
row_idx: int,
periods: int
) -> TrendStrength:
"""Analyze trend strength based on price-SuperTrend relationship."""
# Implementation details
def detect_reversal(
df: pd.DataFrame,
row_idx: int,
threshold: float
) -> ReversalState:
"""Detect potential and confirmed reversals."""
# Implementation details
def generate_signal(
direction: TrendDirection,
strength: TrendStrength,
reversal: ReversalState
) -> Tuple[SignalType, float]:
"""Generate trading signal and strength."""
# Implementation details
3. Integration Points
- Integration with ATR volatility
- Stop-loss level generation
- Trend strength confirmation
- Signal combination with other indicators
Configuration
TIMEFRAME_SETTINGS: Dict[str, SuperTrendSettings] = {
"1m": SuperTrendSettings(
atr_period=10,
atr_multiplier=3.0,
reversal_threshold=0.02,
trend_strength_periods=10
),
"5m": SuperTrendSettings(...),
"15m": SuperTrendSettings(...),
"1h": SuperTrendSettings(...),
"4h": SuperTrendSettings(...),
"1d": SuperTrendSettings(...)
}
Development Guidelines
1. Performance Optimization
- Reuse ATR calculations
- Optimize trend detection
- Efficient reversal detection
- Smart signal generation
2. Testing Strategy
def test_supertrend_calculation():
"""Test basic SuperTrend calculation."""
def test_trend_direction():
"""Test trend direction changes."""
def test_reversal_detection():
"""Test reversal state detection."""
def test_signal_generation():
"""Test trading signal generation."""
def test_stop_loss():
"""Test stop-loss level calculation."""
3. Error Handling
- Handle missing data
- Validate parameters
- Handle calculation edge cases
- Manage trend transitions
Dependencies
- NumPy: Numerical operations
- Pandas: Data manipulation
- FastAPI: REST endpoints
- Existing ATR implementation
Future Enhancements
- Multi-timeframe SuperTrend
- Dynamic ATR multiplier
- Advanced reversal detection
- Machine learning optimization