mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-07-29 18:17:43 +00:00
77 lines
2.8 KiB
Plaintext
77 lines
2.8 KiB
Plaintext
// Licensed under the Apache License, Version 2.0
|
|
// © mihakralj
|
|
//@version=6
|
|
indicator("Schaff Trend Cycle (STC)", "STC", overlay=false)
|
|
|
|
ema(series float source,simple int period=0,simple float alpha=0)=>
|
|
if alpha<=0 and period<=0
|
|
runtime.error("Alpha or period must be provided")
|
|
float a=alpha>0?alpha:2.0/(math.max(period,1)+1)
|
|
var float raw_ema=na
|
|
var float ema=na
|
|
var float e=1.0
|
|
var bool warmup=true
|
|
if not na(source)
|
|
if na(raw_ema)
|
|
raw_ema:=0
|
|
ema:=source
|
|
else
|
|
raw_ema:=a*(source-raw_ema)+raw_ema
|
|
if warmup
|
|
e*=(1-a)
|
|
float c=1.0/(1.0-e)
|
|
ema:=c*raw_ema
|
|
if e<=1e-10
|
|
warmup:=false
|
|
else
|
|
ema:=raw_ema
|
|
ema
|
|
|
|
//@function Calculates the Schaff Trend Cycle (STC) indicator
|
|
//@param source Input price series
|
|
//@param cycleLength Main cycle length parameter for lookback periods
|
|
//@param fastLength Period for fast EMA calculation
|
|
//@param slowLength Period for slow EMA calculation
|
|
//@param smoothingType Type of smoothing (0:none, 1:ema, 2:sigmoid, 3:digital)
|
|
//@returns Smoothed STC value
|
|
stc(series float source, simple int cycleLength, simple int fastLength, simple int slowLength, simple int smoothingType = 1) =>
|
|
float fast_ema = ema(source, fastLength)
|
|
float slow_ema = ema(source, slowLength)
|
|
float macdLine = fast_ema - slow_ema
|
|
|
|
h1 = ta.highest(macdLine, cycleLength)
|
|
l1 = ta.lowest(macdLine, cycleLength)
|
|
float stoch1_raw = (h1 - l1) > 0 ? 100 * (macdLine - l1) / (h1 - l1) : 0
|
|
float stoch1 = ema(stoch1_raw, 3)
|
|
h2 = ta.highest(stoch1, cycleLength)
|
|
l2 = ta.lowest(stoch1, cycleLength)
|
|
float stoch2_raw = (h2 - l2) > 0 ? 100 * (stoch1 - l2) / (h2 - l2) : 0
|
|
|
|
// Second-stage IIR smoothing: PFF = PFF[1] + 0.5 * (Frac2 - PFF[1])
|
|
var float stoch2 = na
|
|
stoch2 := na(stoch2[1]) ? stoch2_raw : stoch2[1] + 0.5 * (stoch2_raw - stoch2[1])
|
|
|
|
float stcValue = stoch2
|
|
if smoothingType == 1
|
|
stcValue := ema(stoch2, 3)
|
|
else if smoothingType == 2
|
|
stcValue := 100 / (1 + math.exp(-0.1 * (stcValue - 50)))
|
|
else if smoothingType == 3
|
|
stcValue := stcValue > 75 ? 100 : stcValue < 25 ? 0 : stcValue[1]
|
|
stcValue
|
|
|
|
// ---------- Main loop ----------
|
|
|
|
// Inputs
|
|
i_source = input.source(close, title="Source")
|
|
i_cycleLength = input.int(10, title="Cycle Length", minval=2)
|
|
i_fastLength = input.int(23, title="Fast Length", minval=2)
|
|
i_slowLength = input.int(50, title="Slow Length", minval=2)
|
|
i_smoothingType = input.int(1, title="Smoothing", minval=0, maxval=3, tooltip="0: none, 1:ema, 2:sigmoid, 3:digital")
|
|
|
|
// Calculation
|
|
stcValue = stc(i_source, i_cycleLength, i_fastLength, i_slowLength, i_smoothingType)
|
|
|
|
// Plot
|
|
plot(stcValue, "STC", color=color.yellow, linewidth=2)
|