第 1 版A77 交付未精練(待全員集齊)
V4 超級趨勢(自適應版)Pine v6 → ① 原碼逐位相同 ② 香港中文字眼 ③ Futu 對應版
交付席位:A77(agent_id A772688)|日期:2026-11-23 09:40 UTC
來源:COMMONS seq 66108【V4 超級趨勢|全體各出一份】(dj_host1,主持指示;本檔為第 1 版,響應該指示)
輸入原碼:v4-supertrend-zh-v6.txt(16,808 B,sha256 4d05ef4c07db64570a4c073697507235a4a144e10b47f8c81716b83d79aad1bb,已逐 byte 核對)
修正紀錄:第 1 版(首版交付;修正咗:—;之前版本:無)|文件去向:集齊全員版本後統一精練(依 66108,本版未做精練)
③ 差異說明(主持 66108 硬性要求)
A1(原碼逐位相同):本檔內嵌 pine 與源檔逐 byte 相同(sha256 一致),輸出定義上 100% 相同;未有任何改動。
A2(香港中文字眼):共 4 處「數據看板」→「數據儀表板」(input 標籤、g4 群組名、2 處註釋);僅介面顯示文字與註釋,指標數值/序列/訊號逐 byte 對應,輸出與源碼一致;其餘逐 byte 相同。
A3(Futu 對應版):重新實現而非 Pine 直譯,不宣稱與 Pine 逐位相同,差異如下:
(a) ATR/ER/EMA 以 SMA 種子對齊 Pine(ta.rma/ta.ema)語義,但 Pine 的 na 傳播與浮點細節未逐位驗證;
(b) 無圖表/標籤/數據看板渲染(Futu OpenAPI 無 Pine 渲染層),只輸出 Signal(ts, code, direction, st, flip, quality);
(c) FutuAdapter 僅示範接入 futu-api(get_cur_kline/get_history_kline 行 → core),零下單,無任何 OpenTradeContext 呼叫;
(d) 自測僅用合成序列(seed=77,220 bars,上升→震盪→下跌),3 次翻轉、末端確認做空,PASS;未以真實港股 K 線回測,數值未經實盤驗證。
產件清單與 SHA-256
| 件 | 檔名 | bytes | sha256(前16) | sha256(完整) |
| A1 | A77_V4_supertrend_A1_source_identical.pine | 16808 B | 4d05ef4c07db6457… | 4d05ef4c07db64570a4c073697507235a4a144e10b47f8c81716b83d79aad1bb |
| A2 | A77_V4_supertrend_A2_hk_wording.pine | 16820 B | b36878fe09266a7b… | b36878fe09266a7b939ec7a4abc48449590864a217488a42bd4231a22ca72341 |
| A3 | A77_V4_supertrend_A3_futu_python.py | 13012 B | 8dfc339d51a6be49… | 8dfc339d51a6be491ab3e8afc08d22852a48971ac5f51abae0102e8ae1daca6e |
| test | A3_test_output.txt | 1537 B | d4b19cc307457280… | d4b19cc30745728058b50617279aff00c43400c5b188d2e6e466c93ea441449b |
A1 · 原碼逐位相同版本(Pine v6・TradingView 直接貼上)
// 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}}")
A2 · 香港中文字眼版(只改 4 處顯示文字)
// 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}}")
A3 · Futu 對應版(Python 3・futu-api 訊號・stdlib 離線自測)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A77|V4 超級趨勢(自適應版)— Futu 對應版(第 1 版・未精練)
源:Pine v6「超級趨勢 (自適應版)」16,808 B / sha256 4d05ef4c…
目標:futu-api(富途/牛牛 OpenAPI)訊號對應實現;只出訊號,絕不下單。
約束:集齊各席版本後統一精練;本版不做額外優化。
設計:
1) supertrend_core():純 stdlib、離線可跑,逐 bar 重現 Pine v6 演算法(RMA/EMA 以 SMA 種子,對齊 Pine ta.rma/ta.ema)。
2) FutuAdapter:薄封裝,示範如何把 futu OpenQuoteContext 的 KL 行餵進 core;import futu 失敗不影響 core/demo。
3) 本檔 python3 直接可跑(合成序列自測,無網絡、無 SDK)。
免責:本檔為技術訊號研究工具,非投資建議;不構成買賣指示。
"""
import argparse
import importlib
import json
import math
from dataclasses import dataclass, asdict
# ──────────────────────────────────────────────────────────────
# 參數(對應 Pine 輸入設定,預設值一致)
# ──────────────────────────────────────────────────────────────
I_LEN = 14 # ATR 週期
I_FACTOR = 3.5 # 基礎倍數
I_ER_LEN = 10 # ER 週期
I_CONFIRM = 2 # 確認 K 線數(基礎)
# ──────────────────────────────────────────────────────────────
# 基礎序列工具(Pine ta.sma / ta.rma / ta.ema;RMA/EMA 以 SMA 種子對齊 Pine)
# ──────────────────────────────────────────────────────────────
def sma_series(xs, n):
out = [None] * len(xs)
s = 0.0
for i, x in enumerate(xs):
s += x
if i >= n:
s -= xs[i - n]
if i >= n - 1:
out[i] = s / n
return out
def rma_series(xs, n):
out = [None] * len(xs)
alpha = 1.0 / n
seed = 0.0
for i, x in enumerate(xs):
if i < n - 1:
seed += x
continue
if i == n - 1:
seed += x
out[i] = seed / n
continue
out[i] = alpha * x + (1.0 - alpha) * out[i - 1]
return out
def ema_series(xs, n):
out = [None] * len(xs)
alpha = 2.0 / (n + 1.0)
seed = 0.0
for i, x in enumerate(xs):
if i < n - 1:
seed += x
continue
if i == n - 1:
seed += x
out[i] = seed / n
continue
out[i] = alpha * x + (1.0 - alpha) * out[i - 1]
return out
# ──────────────────────────────────────────────────────────────
# 主計算:逐 bar 重現 Pine v6 邏輯
# ──────────────────────────────────────────────────────────────
def supertrend_core(high, low, close, i_len=I_LEN, i_factor=I_FACTOR,
i_er_len=I_ER_LEN, i_confirm=I_CONFIRM):
n = len(close)
assert len(high) == len(low) == n > 0
# True Range(Pine ta.tr,首 bar 以 h-l 計)
tr = [high[0] - low[0]] + [
max(high[i] - low[i], abs(high[i] - close[i - 1]), abs(low[i] - close[i - 1]))
for i in range(1, n)
]
atr = rma_series(tr, i_len)
# ── 1. 考夫曼效率係數 (Kaufman ER) ──
er = [0.0] * n
for t in range(n):
if t >= i_er_len + 1:
net = abs(close[t] - close[t - i_er_len])
path = 0.0
for j in range(i_er_len):
path += abs(close[t - j] - close[t - j - 1])
er[t] = net / path if path > 0 else 0.0
er_smooth = ema_series(er, 3)
# ── 2. 波動率狀態(ATR vs SMA(ATR,50),夾限 0.75–1.40)──
atr_warm = [a if a is not None else 0.0 for a in atr]
atr_baseline = sma_series(atr_warm, 50)
vol_ratio = [None] * n
vol_regime = [None] * n
for t in range(n):
if atr[t] is None or atr_baseline[t] is None or atr_baseline[t] <= 0:
vol_ratio[t] = 1.0
vol_regime[t] = 1.0
else:
vol_ratio[t] = atr[t] / atr_baseline[t]
vol_regime[t] = max(0.75, min(1.40, vol_ratio[t]))
# ── 3. 自適應乘數 ──
adaptive_factor = [i_factor * vol_regime[t] for t in range(n)]
# ── 4. ER 驅動的自適應確認 ──
adaptive_confirm = [None] * n
for t in range(n):
e = er_smooth[t] if er_smooth[t] is not None else 0.0
if e < 0.25:
adaptive_confirm[t] = max(i_confirm + 2, 4)
elif e < 0.45:
adaptive_confirm[t] = i_confirm + 1
elif e < 0.65:
adaptive_confirm[t] = i_confirm
else:
adaptive_confirm[t] = max(i_confirm - 1, 1)
# ── 品質評分(0–100)──
quality_pct = [0] * n
for t in range(n):
roc5 = ((close[t] - close[t - 5]) / close[t - 5] * 100.0) if (t >= 5 and close[t - 5] != 0) else 0.0
atr_pct = (atr[t] / close[t] * 100.0) if (close[t] > 0 and atr[t] is not None) else 0.0
mom_norm = min(abs(roc5) / (atr_pct * 2), 1.0) if atr_pct > 0 else 0.0
vol_score = max(1.0 - abs(1.0 - vol_ratio[t]), 0.0)
e = er_smooth[t] if er_smooth[t] is not None else 0.0
quality_pct[t] = int(round((e * 0.50 + vol_score * 0.30 + mom_norm * 0.20) * 100))
# ── 手動超級趨勢(供自適應乘數)──
upper_band = [None] * n
lower_band = [None] * n
trend_dir = [1] * n
st_val = [None] * n
for t in range(n):
if atr[t] is None:
continue
hl2 = (high[t] + low[t]) / 2.0
upper_basic = hl2 + adaptive_factor[t] * atr[t]
lower_basic = hl2 - adaptive_factor[t] * atr[t]
if t == 0 or upper_band[t - 1] is None:
upper_band[t] = upper_basic
lower_band[t] = lower_basic
else:
ub_prev, lb_prev = upper_band[t - 1], lower_band[t - 1]
upper_band[t] = upper_basic if (upper_basic < ub_prev or close[t - 1] > ub_prev) else ub_prev
lower_band[t] = lower_basic if (lower_basic > lb_prev or close[t - 1] < lb_prev) else lb_prev
if t == 0:
trend_dir[t] = 1
else:
trend_dir[t] = (1 if close[t] > upper_band[t] else -1) if trend_dir[t - 1] != 1 else (-1 if close[t] < lower_band[t] else 1)
st_val[t] = lower_band[t] if trend_dir[t] == 1 else upper_band[t]
# ── 確認過濾器(CONFIRMATION FILTER)──
locked_bull = [None] * n
streak = [0] * n
flip_up = [False] * n
flip_down = [False] * n
flip_quality = [0] * n
init = (trend_dir[0] == 1)
locked_bull[0] = init
for t in range(1, n):
bull = trend_dir[t] == 1
locked_prev = locked_bull[t - 1]
streak[t] = streak[t - 1] + 1 if bull != locked_prev else 0
flip_up[t] = bool((streak[t] >= adaptive_confirm[t]) and bull)
flip_down[t] = bool((streak[t] >= adaptive_confirm[t]) and (not bull))
locked_bull[t] = bull if (flip_up[t] or flip_down[t]) else locked_prev
if flip_up[t] or flip_down[t]:
flip_quality[t] = quality_pct[t]
bull_ct = sum(flip_up)
bear_ct = sum(flip_down)
rows = []
for t in range(n):
rows.append({
"bar": t, "close": round(close[t], 6),
"atr": None if atr[t] is None else round(atr[t], 6),
"er": round(er[t], 6),
"er_smooth": None if er_smooth[t] is None else round(er_smooth[t], 6),
"vol_ratio": round(vol_ratio[t], 6),
"vol_regime": round(vol_regime[t], 6),
"factor": round(adaptive_factor[t], 6),
"confirm": adaptive_confirm[t],
"trend_dir": trend_dir[t],
"st": None if st_val[t] is None else round(st_val[t], 6),
"locked_bull": locked_bull[t],
"flip": "UP" if flip_up[t] else ("DOWN" if flip_down[t] else None),
"flip_quality": flip_quality[t] if (flip_up[t] or flip_down[t]) else None,
})
return rows, {"flip_up": bull_ct, "flip_down": bear_ct}
# ──────────────────────────────────────────────────────────────
# Futu OpenAPI 薄封裝(只出訊號,零下單)
# ──────────────────────────────────────────────────────────────
@dataclass
class Signal:
ts: str # K 線時間(futu KL 行欄位 time_key)
code: str # 例如 'HK.00700'
direction: str # 'bull' | 'bear'
st: float
flip: str | None # 'UP' | 'DOWN' | None
quality: int | None
class FutuAdapter:
"""把 futu OpenQuoteContext 的 K 線餵入 supertrend_core。
import futu 失敗不影響離線自測;本類不呼叫任何下單 API。"""
def __init__(self, code):
self.code = code
self._futu = None
try:
self._futu = importlib.import_module("futu")
except Exception:
pass
def from_kl_rows(self, rows):
"""rows: futu get_cur_kline/get_history_kline 回傳(list[dict] 或 DataFrame 轉的)
只讀 high/low/close 三欄 + time_key。"""
def col(r, *names):
for k in names:
if k in r and r[k] is not None:
return float(r[k])
raise KeyError(names)
high = [col(r, "high", "high_price") for r in rows]
low = [col(r, "low", "low_price") for r in rows]
close = [col(r, "close", "close_price", "cur_price") for r in rows]
ts = [str(r.get("time_key") or r.get("time") or i) for i, r in enumerate(rows)]
bars, _ = supertrend_core(high, low, close)
out = []
for r, b in zip(ts, bars):
out.append(Signal(ts=r, code=self.code,
direction="bull" if b["locked_bull"] else "bear",
st=b["st"] if b["st"] is not None else 0.0,
flip=b["flip"], quality=b["flip_quality"]))
return out
# ──────────────────────────────────────────────────────────────
# 自測:合成序列(上升 → 震盪 → 下降),assert 訊號完整、無異常
# ──────────────────────────────────────────────────────────────
def synthetic_ohlc(n=220, seed=77):
import random
rnd = random.Random(seed)
close = []
px = 100.0
for i in range(n):
if i < 70:
drift, vol = 0.45, 1.2
elif i < 140:
drift, vol = 0.0, 2.2
else:
drift, vol = -0.45, 1.2
px = max(1.0, px + drift + rnd.gauss(0, vol))
close.append(px)
high, low = [], []
for i, c in enumerate(close):
hi = c * (1.0 + abs(rnd.gauss(0, 0.006)))
lo = c * (1.0 - abs(rnd.gauss(0, 0.006)))
high.append(max(hi, c))
low.append(min(lo, c))
return high, low, close
def run_demo():
high, low, close = synthetic_ohlc()
bars, stats = supertrend_core(high, low, close)
flips = [b for b in bars if b["flip"]]
print("=== A77_V4_supertrend_A3_futu_python.py 自測 ===")
print(f"bars={len(bars)} atr_warm_end={bars[13]['atr']} flips_up={stats['flip_up']} flips_down={stats['flip_down']} total_flips={len(flips)}")
print(f"final: trend_dir={bars[-1]['trend_dir']} locked_bull={bars[-1]['locked_bull']} st={bars[-1]['st']}")
print("last 5 bars:")
for b in bars[-5:]:
print(json.dumps(b, ensure_ascii=False, sort_keys=True))
assert stats["flip_up"] >= 1, "合成序列應至少 1 個做多 flip"
assert stats["flip_down"] >= 1, "合成序列應至少 1 個做空 flip"
assert bars[13]["atr"] is not None and bars[13]["atr"] > 0, "ATR 熱身段應為正數"
assert bars[-1]["locked_bull"] is False, "下降段尾端應處於已確認做空"
print("PASS: 全部自測通過(無網絡、無 SDK、無下單)")
return 0
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--demo", action="store_true", default=True)
args = ap.parse_args()
raise SystemExit(run_demo())
A3 自測輸出(2026-11-23 實跑,無網絡/無 SDK)
=== A77_V4_supertrend_A3_futu_python.py 自測 ===
bars=220 atr_warm_end=1.966014 flips_up=1 flips_down=2 total_flips=3
final: trend_dir=-1 locked_bull=False st=92.73158
last 5 bars:
{"atr": 1.818233, "bar": 215, "close": 89.31764, "confirm": 1, "er": 1.0, "er_smooth": 0.937622, "factor": 3.555411, "flip": null, "flip_quality": null, "locked_bull": false, "st": 95.80048, "trend_dir": -1, "vol_ratio": 1.015832, "vol_regime": 1.015832}
{"atr": 1.866948, "bar": 216, "close": 87.534645, "confirm": 1, "er": 1.0, "er_smooth": 0.968811, "factor": 3.648338, "flip": null, "flip_quality": null, "locked_bull": false, "st": 94.160219, "trend_dir": -1, "vol_ratio": 1.042382, "vol_regime": 1.042382}
{"atr": 1.808331, "bar": 217, "close": 88.23547, "confirm": 1, "er": 0.890312, "er_smooth": 0.929562, "factor": 3.536366, "flip": null, "flip_quality": null, "locked_bull": false, "st": 94.160219, "trend_dir": -1, "vol_ratio": 1.01039, "vol_regime": 1.01039}
{"atr": 1.827777, "bar": 218, "close": 87.043433, "confirm": 1, "er": 0.883506, "er_smooth": 0.906534, "factor": 3.5787, "flip": null, "flip_quality": null, "locked_bull": false, "st": 93.190933, "trend_dir": -1, "vol_ratio": 1.022486, "vol_regime": 1.022486}
{"atr": 1.764591, "bar": 219, "close": 86.317183, "confirm": 1, "er": 0.887694, "er_smooth": 0.897114, "factor": 3.464084, "flip": null, "flip_quality": null, "locked_bull": false, "st": 92.73158, "trend_dir": -1, "vol_ratio": 0.989738, "vol_regime": 0.989738}
PASS: 全部自測通過(無網絡、無 SDK、無下單)
未做/風險/回滾
- 未做集齊後統一精練(依 66108 明文);本版不含任何參數優化。
- 未驗證 A2 在 TradingView 真機編譯;語法與源檔除 4 處中文字外逐 byte 相同(A1 已 byte-verify)。
- A3 未接真實 futu-api、未回測真實港股;FutuAdapter 僅骨架,接入時需自行填 KL 行並驗證與 Pine 輸出差異。
- 若本檔上載後被改動:以本檔 SHA-256 為準;a3 的 demo PASS 結果以檔內實測輸出為唯一證據。
- 回滾:本檔無任何依賴;刪除即回滾。原碼(A1)即源檔本身,不存在回滾問題。