// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TheRealDrip2Rip
// Translated to Traditional Chinese
//@version=6
indicator("超級趨勢 (自適應版)", overlay=true, max_labels_count=500)

// ═══════════════════════════════════════════════════════════════
//   輸入設定 (INPUTS)
// ═══════════════════════════════════════════════════════════════
g1 = "計算核心"
i_len     = input.int  (14,  "ATR 週期",         minval=1,           group=g1)
i_factor  = input.float(3.5, "基礎倍數",        step=0.1, minval=1, group=g1, tooltip="基礎乘數。會根據即時的波動率狀態自動進行縮放。")
i_er_len  = input.int  (10,  "ER 週期",          minval=3, maxval=20, group=g1, tooltip="考夫曼效率係數(Kaufman ER)回溯期。用於衡量價格是處於單邊趨勢還是震盪洗盤。")
i_confirm = input.int  (2,   "確認K線數 (基礎)", minval=1, maxval=5, group=g1, tooltip="基礎確認K線數。當 ER 低（震盪洗盤）時會自動增加以過濾雜訊，當 ER 高（明顯趨勢）時會自動減少。")

g2 = "視覺設定"
i_glow    = input.bool(true,  "發光光暈",      group=g2)
i_shade   = input.bool(true,  "漸層背景",      group=g2)
i_candles = input.bool(true,  "K線著色",       group=g2)
i_labels  = input.bool(true,  "多空訊號標籤",  group=g2)
i_table   = input.bool(true,  "數據看板",      group=g2)

g3 = "顏色設定"
i_bull = input.color(#26a69a, "做多 (Bull)", group=g3)
i_bear = input.color(#ef5350, "做空 (Bear)", group=g3)

g4 = "數據看板"
i_pos = input.string("右上", "顯示位置", options=["右上","左上","右下","左下"], group=g4)

// ═══════════════════════════════════════════════════════════════
//   自適應層 (ADAPTIVE LAYER)
// ═══════════════════════════════════════════════════════════════
atr = ta.atr(i_len)

// ── 1. 考夫曼效率係數 (KAUFMAN EFFICIENCY RATIO) ──────────────────
// 淨價格位移 除以 總行走距離。
// 完美的單邊趨勢得分為 1.0。
// 上衝下洗但原地踏步的市場得分接近 0.0。
net_move   = math.abs(close - close[i_er_len])
var float total_path = 0.0
total_path := 0.0
for i = 0 to i_er_len - 1
    total_path += math.abs(close[i] - close[i + 1])
er        = total_path > 0 ? net_move / total_path : 0.0
er_smooth = ta.ema(er, 3)

// ── 2. 波動率狀態 (VOLATILITY REGIME) ────────────────────────
// 當前 ATR 與其 50 根 K 線平均基準的比例。
// > 1.2 : 波動劇烈，乘數放大
// < 0.8 : 波動壓縮，乘數縮小
// 將比例限制在 0.75 - 1.40 之間，用於縮放下方的乘數。
atr_baseline = ta.sma(atr, 50)
vol_ratio    = atr_baseline > 0 ? atr / atr_baseline : 1.0
vol_regime   = math.max(math.min(vol_ratio, 1.40), 0.75)

// ── 3. 自適應乘數 (ADAPTIVE FACTOR) ──────────────────────────
// 超級趨勢的乘數由波動率狀態來決定縮放。
// 當波動率升高時，軌道變寬；當波動率受到壓縮時，軌道收緊。
adaptive_factor = i_factor * vol_regime

// ── 4. ER驅動的自適應確認機制 (ER-DRIVEN ADAPTIVE CONFIRMATION) ──
// 低 ER (震盪)：在確認反轉之前需要更多根K線。
// 高 ER (趨勢)：需要較少根K線。
adaptive_confirm = er_smooth < 0.25 ? math.max(i_confirm + 2, 4) :
                   er_smooth < 0.45 ? i_confirm + 1               :
                   er_smooth < 0.65 ? i_confirm                   :
                                      math.max(i_confirm - 1, 1)

// ── 5. 反轉訊號品質評分 (0–100) ──────────────────────────────
// 在每次多空翻轉時計算。包含三個加權組件：
//   50% — 效率 (ER): 市場真的在走趨勢嗎？
//   30% — 波動率正常度: 波動率是否處於健康範圍？ (在 vol_ratio=1.0 時達峰值，極端時下降)
//   20% — 5根K線動能: 翻轉時價格是否真的在移動？
//
// 分數越高表示翻轉發生在越乾淨的市場條件下。
// 等級：A = 70分及以上，B = 50到69分，C = 50分以下。
price_mom_pct = math.abs(ta.roc(close, 5))
atr_pct       = close > 0 ? atr / close * 100 : 0.0
mom_norm      = atr_pct > 0 ? math.min(price_mom_pct / (atr_pct * 2), 1.0) : 0.0
vol_score     = math.max(1.0 - math.abs(1.0 - vol_ratio), 0.0)
quality_raw   = er_smooth * 0.50 + vol_score * 0.30 + mom_norm * 0.20
quality_pct   = math.round(quality_raw * 100)
quality_grade = quality_pct >= 70 ? "A" :quality_pct >= 50 ? "B" : "C"

// ═══════════════════════════════════════════════════════════════
//   手動計算超級趨勢 (配合自適應乘數)
//   因為 ta.supertrend() 只接受簡單的浮點數，所以我們手動
//   實現相同的演算法，以接收我們的動態時間序列乘數。
// ═══════════════════════════════════════════════════════════════
upper_basic = hl2 + adaptive_factor * atr
lower_basic = hl2 - adaptive_factor * atr

var float upper_band = na
var float lower_band = na

upper_band := na(upper_band[1]) ? upper_basic : (upper_basic < upper_band[1] or close[1] > upper_band[1] ? upper_basic : upper_band[1])
lower_band := na(lower_band[1]) ? lower_basic : (lower_basic > lower_band[1] or close[1] < lower_band[1] ? lower_basic : lower_band[1])

var int trend_dir = 1
trend_dir := na(trend_dir[1]) ? 1 : trend_dir[1] ==  1 ? (close < lower_band ? -1 :  1) :(close > upper_band  ?  1 : -1)

st   = trend_dir ==  1 ? lower_band : upper_band
bull = trend_dir ==  1

// ═══════════════════════════════════════════════════════════════
//   確認過濾器 (CONFIRMATION FILTER)
// ═══════════════════════════════════════════════════════════════
var bool locked_bull = bull
var int  streak      = 0

streak    := bull == locked_bull ? 0 : streak + 1
flip_up    = streak >= adaptive_confirm and bull
flip_down  = streak >= adaptive_confirm and not bull
any_flip   = flip_up or flip_down

if any_flip
    locked_bull := bull

tc = locked_bull ? i_bull : i_bear

// 在多空翻轉瞬間捕捉品質分數，供數據看板使用
var int  flip_quality = 0
var bool has_flipped  = false

if any_flip
    flip_quality := quality_pct
    has_flipped  := true

flip_grade = flip_quality >= 70 ? "A" : flip_quality >= 50 ? "B" : "C"

// ═══════════════════════════════════════════════════════════════
//   趨勢強度/確信度 (CONVICTION)
//   融合了時間（K線數）和效率（ER），因此一個 30 根 K 線的乾淨趨勢
//   得分會高過一個 60 根 K 線的震盪洗盤。兩個維度都很重要。
// ═══════════════════════════════════════════════════════════════
var int age = 0
age := any_flip ? 0 : age + 1

s_time = math.min(age / 60.0, 1.0)
s      = s_time * 0.65 + er_smooth * 0.35

var int bull_ct = 0
var int bear_ct = 0

if flip_up
    bull_ct += 1
if flip_down
    bear_ct += 1

// ═══════════════════════════════════════════════════════════════
//   光暈與線條 (GLOW + LINE)
// ═══════════════════════════════════════════════════════════════
// 堆疊三層線條，最寬也最淡的在最下面，讓線條帶有柔和的光暈效果。
plot(i_glow ? st : na, "外圍光暈", color.new(tc, 90), linewidth=12, editable=false)
plot(i_glow ? st : na, "中間光暈",   color.new(tc, 82), linewidth=7,  editable=false)
plot(i_glow ? st : na, "內部光暈", color.new(tc, 68), linewidth=4,  editable=false)
plot(st, "超級趨勢線", tc, linewidth=2)

// ═══════════════════════════════════════════════════════════════
//   漸層著色背景 (GRADIENT SHADING)
//   連續的漸層：靠近超級趨勢線處顏色最深，到價格處漸隱為透明。
//   趨勢確信度越高，線條處的顏色越深。
// ═══════════════════════════════════════════════════════════════
boost     = int(s * 30)
c_line    = color.new(tc, math.max(60 - boost, 28))
c_price   = color.new(tc, 100)
st_on_top = st >= close
top_val   = math.max(st, close)
bot_val   = math.min(st, close)

p_close = plot(close, display=display.none, editable=false)
p_st    = plot(st,    display=display.none, editable=false)

fill(p_close, p_st, i_shade ? top_val : na, i_shade ? bot_val : na, st_on_top ? c_line : c_price, st_on_top ? c_price : c_line, title="漸層背景")

// ═══════════════════════════════════════════════════════════════
//   K線著色 (CANDLES)
// ═══════════════════════════════════════════════════════════════
barcolor(i_candles ? color.new(tc, 22) : na)

// ═══════════════════════════════════════════════════════════════
//   反轉訊號標籤 (FLIP LABELS)
//   顯示方向、品質等級以及當前價格。
// ═══════════════════════════════════════════════════════════════
if i_labels and flip_up
    label.new(bar_index, st, text      = "做多  [" + quality_grade + "]\n" + str.tostring(close, format.mintick), yloc      = yloc.belowbar, style     = label.style_label_up,color     = color.new(i_bull, 8), textcolor = color.white, size      = size.small)

if i_labels and flip_down
    label.new(bar_index, st, text      = "做空  [" + quality_grade + "]\n" + str.tostring(close, format.mintick),  yloc      = yloc.abovebar,style     = label.style_label_down, color     = color.new(i_bear, 8), textcolor = color.white,size      = size.small)

// ═══════════════════════════════════════════════════════════════
//   數據看板 (DASHBOARD)
// ═══════════════════════════════════════════════════════════════
if i_table and barstate.islast
    pos = i_pos == "右上" ? position.top_right    :
          i_pos == "左上" ? position.top_left     :
          i_pos == "右下" ? position.bottom_right :
          position.bottom_left
          
    int    filled = int(math.round(s * 10))
    string sbar   = ""
    for i = 0 to 9
        sbar += i < filled ? "█" : "░"
        
    dist = math.abs(close - st) / close * 100
    
    er_label  = er_smooth > 0.65 ? "趨勢明顯" : er_smooth > 0.40 ? "多空交戰"    : "震盪洗盤"
    er_color  = er_smooth > 0.65 ? tc         : er_smooth > 0.40 ? color.orange : color.gray
    
    vol_label = vol_ratio > 1.20 ? "波動劇烈"   : vol_ratio < 0.80 ? "波動壓縮" : "正常"
    vol_color = vol_ratio > 1.20 ? color.orange  : vol_ratio < 0.80 ? color.aqua    : color.silver
    
    q_color   = not has_flipped ? color.gray : flip_quality >= 70 ? tc : flip_quality >= 50 ? color.orange : color.gray
    q_text    = has_flipped ? str.tostring(flip_quality) + " / 100  [" + flip_grade + "]" : "尚未出現訊號"
    
    t = table.new(pos, 2, 11,bgcolor      = color.new(#080808, 5),border_color = color.new(tc, 52), border_width = 1,frame_color  = color.new(tc, 22),frame_width  = 2)
    
    table.cell(t, 0, 0, "自適應超級趨勢", text_color=color.white, text_size=size.small, bgcolor=color.new(tc, 42), text_halign=text.align_center)
    table.cell(t, 1, 0, "倍數:" + str.tostring(adaptive_factor, "#.##") + "  確認:" + str.tostring(adaptive_confirm),text_color=color.silver, text_size=size.small,bgcolor=color.new(tc, 42), text_halign=text.align_center)
    
    table.cell(t, 0, 1, "當前方向",   text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 1, locked_bull ? "做多" : "做空",text_color=tc, text_size=size.small, text_halign=text.align_center, bgcolor=color.new(tc, 85))
    
    table.cell(t, 0, 2, "持續K線數",  text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 2, str.tostring(age) + " 根",text_color=color.silver, text_size=size.small, text_halign=text.align_center)
    
    table.cell(t, 0, 3, "趨勢強度",  text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 3, sbar + "  " + str.tostring(math.round(s * 100)) + "%", text_color=s > 0.5 ? tc : color.gray,text_size=size.tiny, text_halign=text.align_center)
    
    table.cell(t, 0, 4, "趨勢效率",  text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 4, er_label + "  " + str.tostring(er_smooth, "#.##"),text_color=er_color, text_size=size.small, text_halign=text.align_center)
    
    table.cell(t, 0, 5, "波動率狀態",  text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 5, vol_label + "  " + str.tostring(vol_ratio, "#.##"),text_color=vol_color, text_size=size.small, text_halign=text.align_center)
    
    table.cell(t, 0, 6, "自適應倍數",text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 6, str.tostring(adaptive_factor, "#.##") + "  (基礎 " + str.tostring(i_factor, "#.#") + ")",text_color=color.silver, text_size=size.small, text_halign=text.align_center)
    
    table.cell(t, 0, 7, "上次訊號品質",   text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 7, q_text, text_color=q_color, text_size=size.small, text_halign=text.align_center)
    
    table.cell(t, 0, 8, "距離趨勢線",    text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 8, str.tostring(dist, "#.##") + "%", text_color=dist > 3.0 ? color.orange : color.silver, text_size=size.small, text_halign=text.align_center)
    
    table.cell(t, 0, 9, "做多訊號次數",  text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 9, str.tostring(bull_ct), text_color=i_bull, text_size=size.small, text_halign=text.align_center)
    
    table.cell(t, 0, 10, "做空訊號次數", text_color=color.gray, text_size=size.small)
    table.cell(t, 1, 10, str.tostring(bear_ct),text_color=i_bear, text_size=size.small, text_halign=text.align_center)

// ═══════════════════════════════════════════════════════════════
//   警報設定 (ALERTS)
// ═══════════════════════════════════════════════════════════════
alertcondition(flip_up,   "做多訊號",  "超級趨勢: 做多 — {{ticker}} {{interval}} @ {{close}}")
alertcondition(flip_down, "做空訊號", "超級趨勢: 做空 — {{ticker}} {{interval}} @ {{close}}")
alertcondition(any_flip,  "任何多空翻轉", "超級趨勢: 翻轉 — {{ticker}} {{interval}} @ {{close}}")