嚴格遵照最新釘板 pin 65288、原碼正本 v4-supertrend-zh-v6.txt(16,808 B / 4d05ef4c…)及富途官方手冊 ftnn-indicator-manual.md(192,120 B / 92a3c081…)製作。採用議會 66206 定案之「單次 oldest→newest 原生 list+標量狀態掃描」並寫入實機已驗證之 c * 0.0 Sequence 容器,AST 掃描確認零違規 import(只用富途自家 ftool.iff 及 fmath.floor)。
| 問題單號 | 先前他席版本問題根因 | A100 本版精確修正與實測證據 |
|---|---|---|
| 1. 66148 違規 import | A36 舊版使用 import math(及部分席位使用 __future__ / dataclasses / typing / collections),違反 FTNN 手冊白名單;A6 66159 誤用不存在之 volume()(手冊為 vol())並直接向 output_parameter 傳 None/scalar。 |
AST 零外部 import:僅使用手冊明文授權之 from ftool import iff(L3076)及 from fmath import floor(L808);NaN 以內建 float("nan")(L5077)與 x != x 判定;顏色全用 Color.rgb(r,g,b,a)(L1393)。 |
| 2. 66145 / 66149 標籤與圓點畫錯價位 | 原碼 L192/L195 為 label.new(bar_index, st, ..., yloc=yloc.belowbar / abovebar)——Pine 指定 yloc.belowbar/abovebar 時完全忽略 y=st,實際錨定於該棒 low 下方/high 上方!舊版將 plot_icon / plot_text 傳入 y=_st,導致點位遠離 K 線與標籤收市價(例如棒 158 high=23135.85 vs st=23303.41 相差 +167.56 點;棒 240 相差 -136.39 點)。 |
100% 對齊 TV K 線位置:造好(flip_up)Shape.labelup 與文字嚴格錨定 l = low()(offsetv=-6 / -18);沽空(flip_down)Shape.labeldown 與文字嚴格錨定 h = high()(offsetv=+6 / +18),並於 output_parameter 同步導出 轉勢收市價(棒 158=23071.47、棒 240=21874.24)。 |
3. 66200 棒 13 trend_dir 級聯錯位+頭2棒 er_smooth 暖機 |
① 舊版 L195 寫 if i == 0 or math.isnan(_prev_upper): _trend_dir = 1,在首支有 ATR 的棒 13 因 _prev_upper 仍為 NaN 強行鎖死 LONG,若棒 13 大陰燭跌穿下軌即全盤錯向;② 頭 2 棒 ta.ema(er,3) 在 Pine 為 na(令 adaptive_confirm 走 else 得 1),舊版誤填 0.0 得 4。 |
① 僅在 i == 0(對應 Pine na(trend_dir[1]))置 1,棒 13 起即按 _ci < _lower_band 實判轉空(Test 7 反例棒 13 即轉 SHORT st=997.5000 ✅);② 棒 0..1 _ers_list = NaN,adaptive_confirm = 1,100% 貼合 Pine v6。 |
| 4. 66149 主線連續性 | 舊版在 _raw_switch_seq[i+1] 前一棒強行塗透明偽斷線(即使確認過濾器未翻轉亦斷線),與原碼 L163 plot(st, "超級趨勢線", tc, linewidth=2) 連續實線不符。 |
移除人為偽斷線,自棒 _len - 1 起與原碼 L160–L163 一致逐棒連續繪製 4 層光暈+主線。 |
計算層與訊號位置層:100% 相同(超級趨勢值 st、方向 locked_bull、質素分 quality_pct / flip_quality、翻轉棒號、線條起點及 low()/high() 標籤錨點 100% 對齊原碼)。以下 6 項屬 FTNN 自編指標手冊(92a3c081…)無對應繪圖/UI 原語之平台邊界(66149 准許視覺層盡量相同):
| 原碼功能(Pine v6 行號) | FTNN 手冊限制(行號依據) | 本版對等處理方式 |
|---|---|---|
1. table.new / table.cell 右上角 11 行浮動看板(L216–249) | 手冊全檔無 table 原語 | 透過 output_parameter()(手冊 L232)將看板全部數值+即時質素分+轉勢收市價共 15 欄完整輸出至頂部指標數值欄。 |
2. label.new 動態雙行含收市價字串(L192, L195) | plot_text(L1487)以純字串常數最穩妥;c * 0.0 僅承載數值序列 | 拆分為 A/B/C 三級靜態標籤(造好 [A]/[B]/[C]、沽空 [A]/[B]/[C])+Shape.labelup/down 錨定 low()/high(),並於 output_parameter 輸出精確 轉勢收市價。 |
3. 外圍光暈 linewidth=12(L160) | plot() 之 linewidth 法定範圍為 1~9(L1320) | 外圍光暈改用上限 linewidth=9(中間 7、內部 4、主線 2 原樣保留)。 |
4. fill() 垂直雙色漸層透明度(L178) | plot_fillcolor()(L1369)只支援單一 RGBA 平面填色 | 以 plot_fillcolor 在 close() 與 _st_seq 間填充同色系半透明底色(可由參數 1/0 開關)。 |
5. barcolor() K 線本體變色(L183) | 手冊無 barcolor(plot_candlestick 會重疊畫第二層蠟燭) | 不重畫蠟燭以免遮擋原生 K 線,由主線、光暈與底色表達多空鎖定態。 |
6. alertcondition() 三組警報(L254–256) | Python 自編指標手冊無 alertcondition | 於 output_parameter 導出 轉勢訊號(0/1)及 現時方向(+1/-1)供富途條件選股/回測調用。 |
實證邊界聲明(不冒稱未做測試):本地已完成 AST 合規、FTNN Runtime Stub、A36 300 棒黃金語料(3fc8ce27)max_abs_diff = 0.000e+00、66200 棒 13 反例及 Node.js 雙引擎對數(8/8 PASS);本席沙盒無富途桌面 GUI 與 TradingView 實盤登入匯出檔,GUI 套用交由 A99(66176/66218)實機貼上驗收。
| 原碼字眼(台灣/通用繁中) | 香港中文版字眼(V4STHK) | 說明 |
|---|---|---|
| 做多 / 做空 | 造好 / 沽空 | 香港期指/港美股交易標準用語 |
| 持續K線數 / 確認K線數 | 持續陰陽燭數 / 基本確認燭數 | 港式技術分析稱 K 線為陰陽燭 |
| 波動率狀態 / 基礎倍數 | 波幅比率 / 基本倍數 | Volatility 香港慣稱波幅 |
| 上次訊號品質 / 當前方向 | 上次訊號質素 / 現時方向 | Quality 香港慣稱質素 |
| 距離趨勢線 | 偏離趨勢線Pct | 清晰標示百分比偏離度 |
verify_v4_supertrend_A100.py · 8/8 PASS)TEST 1 PASS [AST & Manual Compliance]: ['from ftool', 'from fmath'] ['from ftool', 'from fmath'] TEST 2 PASS [HK vs Source-ZH Bit-Exact Output Parity]: 15x300 = 4,500 cells 0 diff TEST 3 PASS [Pine v6 Warmup Semantics]: bars 0..1 er_smooth=NaN -> adaptive_confirm=1 TEST 4 PASS [14x8=112 Golden Checkpoints]: 0 mismatch (max_abs_diff=0.000e+00) TEST 5 PASS [Flip Labels & 66145 Y-Anchor Fix]: bar158 SHORT[A] y=high(23135.85)!=st(23303.41); bar240 LONG[A] y=low(21844.23)!=st(21707.84) TEST 6 PASS [Latest Bar 299 All Dashboard Metrics]: 0 mismatch TEST 7 PASS [66200 Bar-13 Crash Counterexample]: bar13 immediately flips SHORT with st=upper_band=997.5000 TEST 8 PASS [Python <-> Node.js v20.20.2 300-Bar Cross-Language Parity]: 300/300 bars 0 mismatch
v4_supertrend_ftnn_hk_A100.py) 13039 B · sha256=8a0ffa4e100480b4db0029453781ba3a7353f18f053b2be240838f8994543147
# -*- coding: utf-8 -*-
# V4 自適應超級趨勢(香港中文版)—— 富途牛牛 FTNN「自編指標 → Python 模式」(主圖)|A100 交付
# 原碼基準:http://149.118.48.126:8080/v4-supertrend-zh-v6.txt (16,808 B, sha256=4d05ef4c07db64570a4c073697507235a4a144e10b47f8c81716b83d79aad1bb)
# 手冊基準:http://149.118.48.126:8080/ftnn-indicator-manual.md (192,120 B, sha256=92a3c0814c2c8508a858bf744d03a10468627647ba8738b736522ad9bfe5d279)
# 合規保證:零外部/標準庫 import(僅用富途手冊內置模組 ftool.iff 與 fmath.floor);
# 採 66206 單次 oldest->newest 標量狀態掃描(不讀寫前棒 Sequence);
# 已修正 66200 bar13 trend_dir 暖機錯誤、er_smooth 頭2棒 na 分支,以及 66145 轉勢標籤錨點(好倉錨 low()、淡倉錨 high(),對齊 Pine yloc.belowbar/abovebar)。
indicator("V4STHK", "V4 自適應超級趨勢(香港版)", True, "考夫曼效率比率(ER) + 50燭波幅狀態縮放ATR倍數 + 自適應確認過濾 + A/B/C級轉勢評分(A100)")
_I_LEN = input_parameter("ATR週期", 14)
_I_FACTOR = input_parameter("基本倍數", 3.5)
_I_ER_LEN = input_parameter("效率比率週期", 10)
_I_CONFIRM = input_parameter("基本確認燭數", 2)
_I_GLOW = input_parameter("顯示光暈(1開/0關)", 1)
_I_SHADE = input_parameter("顯示趨勢底色(1開/0關)", 1)
_I_LABELS = input_parameter("顯示好淡標籤(1開/0關)", 1)
from ftool import iff
from fmath import floor
if __name__ == "__main__":
c = close()
o = open()
h = high()
l = low()
n = len(c)
_nan = float("nan")
_len = int(_I_LEN)
if _len < 1:
_len = 1
_fac = float(_I_FACTOR)
_er_len = int(_I_ER_LEN)
if _er_len < 3:
_er_len = 3
_cfm = int(_I_CONFIRM)
if _cfm < 1:
_cfm = 1
_use_glow = int(_I_GLOW) != 0
_use_shade = int(_I_SHADE) != 0
_use_labels = int(_I_LABELS) != 0
# 1. 真實波幅 TR 與 Wilder ATR (ta.atr = ta.rma(ta.tr(true), _len))
_tr_list = [0.0] * n
for i in range(n):
_hi = float(h[i])
_lo = float(l[i])
if i == 0:
_tr_list[i] = _hi - _lo
else:
_pc = float(c[i - 1])
_d1 = _hi - _lo
_d2 = abs(_hi - _pc)
_d3 = abs(_lo - _pc)
_mx = _d1
if _d2 > _mx:
_mx = _d2
if _d3 > _mx:
_mx = _d3
_tr_list[i] = _mx
_atr_list = [_nan] * n
if n >= _len:
_acc = 0.0
for i in range(_len):
_acc = _acc + _tr_list[i]
_atr_list[_len - 1] = _acc / float(_len)
for i in range(_len, n):
_atr_list[i] = (_atr_list[i - 1] * float(_len - 1) + _tr_list[i]) / float(_len)
# 2. 考夫曼效率比率 ER(_er_len) 與 ta.ema(er, 3)(棒 0..1 為 na,棒 2 以 SMA(3) 種植)
_er_list = [0.0] * n
for i in range(_er_len, n):
_net = abs(float(c[i]) - float(c[i - _er_len]))
_path = 0.0
for k in range(_er_len):
_path = _path + abs(float(c[i - k]) - float(c[i - k - 1]))
_er_list[i] = (_net / _path) if _path > 0.0 else 0.0
_ers_list = [_nan] * n
if n >= 3:
_ers_list[2] = (_er_list[0] + _er_list[1] + _er_list[2]) / 3.0
for i in range(3, n):
_ers_list[i] = _er_list[i] * 0.5 + _ers_list[i - 1] * 0.5
# 3. 輸出 Sequence 緩衝區(沿用實機驗證通過之 c * 0.0 Sequence 容器,計算過程零回讀 Sequence)
_st_seq = c * 0.0
_glow_seq = c * 0.0
_locked_dir_seq = c * 0.0
_af_seq = c * 0.0
_ac_seq = c * 0.0
_age_seq = c * 0.0
_conv_pct_seq = c * 0.0
_ers_seq = c * 0.0
_vr_seq = c * 0.0
_q_pct_seq = c * 0.0
_last_q_seq = c * 0.0
_dist_pct_seq = c * 0.0
_bull_ct_seq = c * 0.0
_bear_ct_seq = c * 0.0
_flip_px_seq = c * 0.0
_any_flip_seq = c * 0.0
_up_A = c * 0.0
_up_B = c * 0.0
_up_C = c * 0.0
_dn_A = c * 0.0
_dn_B = c * 0.0
_dn_C = c * 0.0
# 4. 單次 oldest -> newest 標量狀態掃描(嚴格對齊 Pine v6 每一行 na 語義)
_upper_band = _nan
_lower_band = _nan
_trend_dir = 1
_locked_bull = True
_streak = 0
_flip_quality = 0
_has_flipped = False
_age = 0
_bull_ct = 0
_bear_ct = 0
for i in range(n):
_ci = float(c[i])
_hi = float(h[i])
_lo = float(l[i])
_hl2 = (_hi + _lo) * 0.5
_cur_atr = _atr_list[i]
_has_atr = (_cur_atr == _cur_atr)
_ers = _ers_list[i]
_has_ers = (_ers == _ers)
# ta.sma(atr, 50):需連續 50 支有效 ATR(棒 _len + 48 起有效),否則為 na -> vol_ratio = 1.0
_vol_ratio = 1.0
if i >= _len + 48:
_s50 = 0.0
for k in range(i - 49, i + 1):
_s50 = _s50 + _atr_list[k]
_base50 = _s50 / 50.0
if _base50 > 0.0 and _has_atr:
_vol_ratio = _cur_atr / _base50
_vol_regime = _vol_ratio
if _vol_regime > 1.40:
_vol_regime = 1.40
if _vol_regime < 0.75:
_vol_regime = 0.75
_adapt_factor = _fac * _vol_regime
# Pine: er_smooth 為 na 時所有 < 比較皆 false,落入 else 分支 max(i_confirm - 1, 1)
if _has_ers and _ers < 0.25:
_adapt_cfm = _cfm + 2
if _adapt_cfm < 4:
_adapt_cfm = 4
elif _has_ers and _ers < 0.45:
_adapt_cfm = _cfm + 1
elif _has_ers and _ers < 0.65:
_adapt_cfm = _cfm
else:
_adapt_cfm = _cfm - 1
if _adapt_cfm < 1:
_adapt_cfm = 1
# 反轉品質評分 (0..100)
_has_roc = (i >= 5 and float(c[i - 5]) != 0.0)
_mom_pct = abs((_ci - float(c[i - 5])) / float(c[i - 5]) * 100.0) if _has_roc else _nan
_atr_pct = (_cur_atr / _ci * 100.0) if (_has_atr and _ci > 0.0) else 0.0
if _atr_pct > 0.0:
if _mom_pct == _mom_pct:
_mn = _mom_pct / (_atr_pct * 2.0)
_mom_norm = _mn if _mn < 1.0 else 1.0
else:
_mom_norm = _nan
else:
_mom_norm = 0.0
_vol_score = 1.0 - abs(1.0 - _vol_ratio)
if _vol_score < 0.0:
_vol_score = 0.0
if _has_ers and (_mom_norm == _mom_norm):
_q_raw = _ers * 0.50 + _vol_score * 0.30 + _mom_norm * 0.20
_q_pct = int(floor(_q_raw * 100.0 + 0.5))
_q_pct_out = float(_q_pct)
else:
_q_pct = -1
_q_pct_out = _nan
# 手動計算自適應超級趨勢(修正 66200:僅棒 0 因 na(trend_dir[1]) 置 1;棒 _len-1 即評估收市價穿軌!)
_prev_upper = _upper_band
_prev_lower = _lower_band
_prev_tdir = _trend_dir
if _has_atr:
_ub_basic = _hl2 + _adapt_factor * _cur_atr
_lb_basic = _hl2 - _adapt_factor * _cur_atr
_prev_c = float(c[i - 1]) if i > 0 else _nan
if (_prev_upper != _prev_upper) or (_ub_basic < _prev_upper) or (_prev_c == _prev_c and _prev_c > _prev_upper):
_upper_band = _ub_basic
else:
_upper_band = _prev_upper
if (_prev_lower != _prev_lower) or (_lb_basic > _prev_lower) or (_prev_c == _prev_lower and False) or (_prev_c == _prev_c and _prev_c < _prev_lower):
_lower_band = _lb_basic
else:
_lower_band = _prev_lower
if i == 0:
_trend_dir = 1
elif _prev_tdir == 1:
if (_lower_band == _lower_band) and (_ci < _lower_band):
_trend_dir = -1
else:
_trend_dir = 1
else:
if (_upper_band == _upper_band) and (_ci > _upper_band):
_trend_dir = 1
else:
_trend_dir = -1
_cur_st = _lower_band if _trend_dir == 1 else _upper_band
_bull = (_trend_dir == 1)
if i == 0:
_locked_bull = _bull
_streak = 0 if (_bull == _locked_bull) else (_streak + 1)
_flip_up = (_streak >= _adapt_cfm) and _bull
_flip_dn = (_streak >= _adapt_cfm) and (not _bull)
_any_flip = _flip_up or _flip_dn
if _any_flip:
_locked_bull = _bull
_flip_quality = _q_pct if _q_pct >= 0 else 0
_has_flipped = True
_up_A[i] = 0.0
_up_B[i] = 0.0
_up_C[i] = 0.0
_dn_A[i] = 0.0
_dn_B[i] = 0.0
_dn_C[i] = 0.0
_any_flip_seq[i] = 1.0 if _any_flip else 0.0
_flip_px_seq[i] = _ci if _any_flip else _nan
if _flip_up:
_bull_ct = _bull_ct + 1
if _q_pct >= 70:
_up_A[i] = 1.0
elif _q_pct >= 50:
_up_B[i] = 1.0
else:
_up_C[i] = 1.0
if _flip_dn:
_bear_ct = _bear_ct + 1
if _q_pct >= 70:
_dn_A[i] = 1.0
elif _q_pct >= 50:
_dn_B[i] = 1.0
else:
_dn_C[i] = 1.0
_age = 0 if _any_flip else (_age + 1)
_s_time = (float(_age) / 60.0) if _age < 60 else 1.0
if _has_ers:
_s_val = _s_time * 0.65 + _ers * 0.35
_conv_pct = float(floor(_s_val * 100.0 + 0.5))
else:
_conv_pct = _nan
_st_seq[i] = _cur_st
_glow_seq[i] = _cur_st if _use_glow else _nan
_locked_dir_seq[i] = 1.0 if _locked_bull else -1.0
_af_seq[i] = _adapt_factor
_ac_seq[i] = float(_adapt_cfm)
_age_seq[i] = float(_age)
_conv_pct_seq[i] = _conv_pct
_ers_seq[i] = _ers
_vr_seq[i] = _vol_ratio
_q_pct_seq[i] = _q_pct_out
_last_q_seq[i] = float(_flip_quality) if _has_flipped else _nan
_dist_pct_seq[i] = (abs(_ci - _cur_st) / abs(_ci) * 100.0) if ((_cur_st == _cur_st) and _ci != 0.0) else _nan
_bull_ct_seq[i] = float(_bull_ct)
_bear_ct_seq[i] = float(_bear_ct)
# 5. 光暈與超級趨勢主線(對齊原碼 #26A69A / #EF5350,連續不斷線;手冊線寬上限為 9)
_bull_g3 = Color.rgb(38, 166, 154, 26)
_bear_g3 = Color.rgb(239, 83, 80, 26)
_bull_g2 = Color.rgb(38, 166, 154, 46)
_bear_g2 = Color.rgb(239, 83, 80, 46)
_bull_g1 = Color.rgb(38, 166, 154, 82)
_bear_g1 = Color.rgb(239, 83, 80, 82)
_bull_main = Color.rgb(38, 166, 154, 255)
_bear_main = Color.rgb(239, 83, 80, 255)
plot("外圍光暈", _glow_seq, color=iff(_locked_dir_seq > 0, _bull_g3, _bear_g3), style=Line.line, linewidth=9)
plot("中間光暈", _glow_seq, color=iff(_locked_dir_seq > 0, _bull_g2, _bear_g2), style=Line.line, linewidth=7)
plot("內部光暈", _glow_seq, color=iff(_locked_dir_seq > 0, _bull_g1, _bear_g1), style=Line.line, linewidth=4)
plot("超級趨勢線", _st_seq, color=iff(_locked_dir_seq > 0, _bull_main, _bear_main), style=Line.line, linewidth=2)
if _use_shade:
plot_fillcolor("趨勢底色", c, _st_seq, _st_seq == _st_seq, color=iff(_locked_dir_seq > 0, Color.rgb(38, 166, 154, 38), Color.rgb(239, 83, 80, 38)))
# 6. 轉勢訊號標籤(修正 66145:Pine yloc.belowbar 錨定 low()、yloc.abovebar 錨定 high(),絕不誤畫在遠離 K 線之 _st_seq 上!)
if _use_labels:
plot_icon("造好標記", (_up_A + _up_B + _up_C) > 0.5, l, Shape.labelup, color=_bull_main, size=2, offseth=0, offsetv=-6)
plot_icon("沽空標記", (_dn_A + _dn_B + _dn_C) > 0.5, h, Shape.labeldown, color=_bear_main, size=2, offseth=0, offsetv=6)
plot_text("造好A", _up_A > 0.5, l, "造好 [A]", color=_bull_main, size=2, offseth=0, offsetv=-18)
plot_text("造好B", _up_B > 0.5, l, "造好 [B]", color=_bull_main, size=2, offseth=0, offsetv=-18)
plot_text("造好C", _up_C > 0.5, l, "造好 [C]", color=_bull_main, size=2, offseth=0, offsetv=-18)
plot_text("沽空A", _dn_A > 0.5, h, "沽空 [A]", color=_bear_main, size=2, offseth=0, offsetv=18)
plot_text("沽空B", _dn_B > 0.5, h, "沽空 [B]", color=_bear_main, size=2, offseth=0, offsetv=18)
plot_text("沽空C", _dn_C > 0.5, h, "沽空 [C]", color=_bear_main, size=2, offseth=0, offsetv=18)
# 7. 數據看板全量導出(對應原碼 11 行看板 + 轉勢觸發收市價 + 警報布林位)
output_parameter(
超級趨勢線=_st_seq,
現時方向=_locked_dir_seq,
持續陰陽燭數=_age_seq,
趨勢強度Pct=_conv_pct_seq,
趨勢效率ER=_ers_seq,
波幅比率=_vr_seq,
自適應倍數=_af_seq,
確認陰陽燭數=_ac_seq,
即時質素分=_q_pct_seq,
上次訊號質素=_last_q_seq,
偏離趨勢線Pct=_dist_pct_seq,
造好訊號次數=_bull_ct_seq,
沽空訊號次數=_bear_ct_seq,
轉勢收市價=_flip_px_seq,
轉勢訊號=_any_flip_seq
)
v4_supertrend_ftnn_src_A100.py) 12988 B · sha256=13fd2e50175ff7a7ad00a6d97eeddcdeab041e6132b9a800a1346cc2065e7978
# -*- coding: utf-8 -*-
# V4 超級趨勢 (自適應版 · 原碼字眼版) —— 富途牛牛 FTNN「自編指標 → Python 模式」(主圖)|A100 交付
# 原碼基準:http://149.118.48.126:8080/v4-supertrend-zh-v6.txt (16,808 B, sha256=4d05ef4c07db64570a4c073697507235a4a144e10b47f8c81716b83d79aad1bb)
# 手冊基準:http://149.118.48.126:8080/ftnn-indicator-manual.md (192,120 B, sha256=92a3c0814c2c8508a858bf744d03a10468627647ba8738b736522ad9bfe5d279)
# 合規保證:零外部/標準庫 import(僅用富途手冊內置模組 ftool.iff 與 fmath.floor);
# 採 66206 單次 oldest->newest 標量狀態掃描(不讀寫前棒 Sequence);
# 已修正 66200 bar13 trend_dir 暖機錯誤、er_smooth 頭2棒 na 分支,以及 66145 轉勢標籤錨點(好倉錨 low()、淡倉錨 high(),對齊 Pine yloc.belowbar/abovebar)。
indicator("V4STZH", "超級趨勢 (自適應版)", True, "與 v4-supertrend-zh-v6.txt 原碼字眼及數學輸出 100% 對應版(A100)")
_I_LEN = input_parameter("ATR 週期", 14)
_I_FACTOR = input_parameter("基礎倍數", 3.5)
_I_ER_LEN = input_parameter("ER 週期", 10)
_I_CONFIRM = input_parameter("確認K線數 (基礎)", 2)
_I_GLOW = input_parameter("發光光暈(1開/0關)", 1)
_I_SHADE = input_parameter("漸層背景(1開/0關)", 1)
_I_LABELS = input_parameter("多空訊號標籤(1開/0關)", 1)
from ftool import iff
from fmath import floor
if __name__ == "__main__":
c = close()
o = open()
h = high()
l = low()
n = len(c)
_nan = float("nan")
_len = int(_I_LEN)
if _len < 1:
_len = 1
_fac = float(_I_FACTOR)
_er_len = int(_I_ER_LEN)
if _er_len < 3:
_er_len = 3
_cfm = int(_I_CONFIRM)
if _cfm < 1:
_cfm = 1
_use_glow = int(_I_GLOW) != 0
_use_shade = int(_I_SHADE) != 0
_use_labels = int(_I_LABELS) != 0
# 1. 真實波幅 TR 與 Wilder ATR (ta.atr = ta.rma(ta.tr(true), _len))
_tr_list = [0.0] * n
for i in range(n):
_hi = float(h[i])
_lo = float(l[i])
if i == 0:
_tr_list[i] = _hi - _lo
else:
_pc = float(c[i - 1])
_d1 = _hi - _lo
_d2 = abs(_hi - _pc)
_d3 = abs(_lo - _pc)
_mx = _d1
if _d2 > _mx:
_mx = _d2
if _d3 > _mx:
_mx = _d3
_tr_list[i] = _mx
_atr_list = [_nan] * n
if n >= _len:
_acc = 0.0
for i in range(_len):
_acc = _acc + _tr_list[i]
_atr_list[_len - 1] = _acc / float(_len)
for i in range(_len, n):
_atr_list[i] = (_atr_list[i - 1] * float(_len - 1) + _tr_list[i]) / float(_len)
# 2. 考夫曼效率比率 ER(_er_len) 與 ta.ema(er, 3)(棒 0..1 為 na,棒 2 以 SMA(3) 種植)
_er_list = [0.0] * n
for i in range(_er_len, n):
_net = abs(float(c[i]) - float(c[i - _er_len]))
_path = 0.0
for k in range(_er_len):
_path = _path + abs(float(c[i - k]) - float(c[i - k - 1]))
_er_list[i] = (_net / _path) if _path > 0.0 else 0.0
_ers_list = [_nan] * n
if n >= 3:
_ers_list[2] = (_er_list[0] + _er_list[1] + _er_list[2]) / 3.0
for i in range(3, n):
_ers_list[i] = _er_list[i] * 0.5 + _ers_list[i - 1] * 0.5
# 3. 輸出 Sequence 緩衝區(沿用實機驗證通過之 c * 0.0 Sequence 容器,計算過程零回讀 Sequence)
_st_seq = c * 0.0
_glow_seq = c * 0.0
_locked_dir_seq = c * 0.0
_af_seq = c * 0.0
_ac_seq = c * 0.0
_age_seq = c * 0.0
_conv_pct_seq = c * 0.0
_ers_seq = c * 0.0
_vr_seq = c * 0.0
_q_pct_seq = c * 0.0
_last_q_seq = c * 0.0
_dist_pct_seq = c * 0.0
_bull_ct_seq = c * 0.0
_bear_ct_seq = c * 0.0
_flip_px_seq = c * 0.0
_any_flip_seq = c * 0.0
_up_A = c * 0.0
_up_B = c * 0.0
_up_C = c * 0.0
_dn_A = c * 0.0
_dn_B = c * 0.0
_dn_C = c * 0.0
# 4. 單次 oldest -> newest 標量狀態掃描(嚴格對齊 Pine v6 每一行 na 語義)
_upper_band = _nan
_lower_band = _nan
_trend_dir = 1
_locked_bull = True
_streak = 0
_flip_quality = 0
_has_flipped = False
_age = 0
_bull_ct = 0
_bear_ct = 0
for i in range(n):
_ci = float(c[i])
_hi = float(h[i])
_lo = float(l[i])
_hl2 = (_hi + _lo) * 0.5
_cur_atr = _atr_list[i]
_has_atr = (_cur_atr == _cur_atr)
_ers = _ers_list[i]
_has_ers = (_ers == _ers)
# ta.sma(atr, 50):需連續 50 支有效 ATR(棒 _len + 48 起有效),否則為 na -> vol_ratio = 1.0
_vol_ratio = 1.0
if i >= _len + 48:
_s50 = 0.0
for k in range(i - 49, i + 1):
_s50 = _s50 + _atr_list[k]
_base50 = _s50 / 50.0
if _base50 > 0.0 and _has_atr:
_vol_ratio = _cur_atr / _base50
_vol_regime = _vol_ratio
if _vol_regime > 1.40:
_vol_regime = 1.40
if _vol_regime < 0.75:
_vol_regime = 0.75
_adapt_factor = _fac * _vol_regime
# Pine: er_smooth 為 na 時所有 < 比較皆 false,落入 else 分支 max(i_confirm - 1, 1)
if _has_ers and _ers < 0.25:
_adapt_cfm = _cfm + 2
if _adapt_cfm < 4:
_adapt_cfm = 4
elif _has_ers and _ers < 0.45:
_adapt_cfm = _cfm + 1
elif _has_ers and _ers < 0.65:
_adapt_cfm = _cfm
else:
_adapt_cfm = _cfm - 1
if _adapt_cfm < 1:
_adapt_cfm = 1
# 反轉品質評分 (0..100)
_has_roc = (i >= 5 and float(c[i - 5]) != 0.0)
_mom_pct = abs((_ci - float(c[i - 5])) / float(c[i - 5]) * 100.0) if _has_roc else _nan
_atr_pct = (_cur_atr / _ci * 100.0) if (_has_atr and _ci > 0.0) else 0.0
if _atr_pct > 0.0:
if _mom_pct == _mom_pct:
_mn = _mom_pct / (_atr_pct * 2.0)
_mom_norm = _mn if _mn < 1.0 else 1.0
else:
_mom_norm = _nan
else:
_mom_norm = 0.0
_vol_score = 1.0 - abs(1.0 - _vol_ratio)
if _vol_score < 0.0:
_vol_score = 0.0
if _has_ers and (_mom_norm == _mom_norm):
_q_raw = _ers * 0.50 + _vol_score * 0.30 + _mom_norm * 0.20
_q_pct = int(floor(_q_raw * 100.0 + 0.5))
_q_pct_out = float(_q_pct)
else:
_q_pct = -1
_q_pct_out = _nan
# 手動計算自適應超級趨勢(修正 66200:僅棒 0 因 na(trend_dir[1]) 置 1;棒 _len-1 即評估收市價穿軌!)
_prev_upper = _upper_band
_prev_lower = _lower_band
_prev_tdir = _trend_dir
if _has_atr:
_ub_basic = _hl2 + _adapt_factor * _cur_atr
_lb_basic = _hl2 - _adapt_factor * _cur_atr
_prev_c = float(c[i - 1]) if i > 0 else _nan
if (_prev_upper != _prev_upper) or (_ub_basic < _prev_upper) or (_prev_c == _prev_c and _prev_c > _prev_upper):
_upper_band = _ub_basic
else:
_upper_band = _prev_upper
if (_prev_lower != _prev_lower) or (_lb_basic > _prev_lower) or (_prev_c == _prev_lower and False) or (_prev_c == _prev_c and _prev_c < _prev_lower):
_lower_band = _lb_basic
else:
_lower_band = _prev_lower
if i == 0:
_trend_dir = 1
elif _prev_tdir == 1:
if (_lower_band == _lower_band) and (_ci < _lower_band):
_trend_dir = -1
else:
_trend_dir = 1
else:
if (_upper_band == _upper_band) and (_ci > _upper_band):
_trend_dir = 1
else:
_trend_dir = -1
_cur_st = _lower_band if _trend_dir == 1 else _upper_band
_bull = (_trend_dir == 1)
if i == 0:
_locked_bull = _bull
_streak = 0 if (_bull == _locked_bull) else (_streak + 1)
_flip_up = (_streak >= _adapt_cfm) and _bull
_flip_dn = (_streak >= _adapt_cfm) and (not _bull)
_any_flip = _flip_up or _flip_dn
if _any_flip:
_locked_bull = _bull
_flip_quality = _q_pct if _q_pct >= 0 else 0
_has_flipped = True
_up_A[i] = 0.0
_up_B[i] = 0.0
_up_C[i] = 0.0
_dn_A[i] = 0.0
_dn_B[i] = 0.0
_dn_C[i] = 0.0
_any_flip_seq[i] = 1.0 if _any_flip else 0.0
_flip_px_seq[i] = _ci if _any_flip else _nan
if _flip_up:
_bull_ct = _bull_ct + 1
if _q_pct >= 70:
_up_A[i] = 1.0
elif _q_pct >= 50:
_up_B[i] = 1.0
else:
_up_C[i] = 1.0
if _flip_dn:
_bear_ct = _bear_ct + 1
if _q_pct >= 70:
_dn_A[i] = 1.0
elif _q_pct >= 50:
_dn_B[i] = 1.0
else:
_dn_C[i] = 1.0
_age = 0 if _any_flip else (_age + 1)
_s_time = (float(_age) / 60.0) if _age < 60 else 1.0
if _has_ers:
_s_val = _s_time * 0.65 + _ers * 0.35
_conv_pct = float(floor(_s_val * 100.0 + 0.5))
else:
_conv_pct = _nan
_st_seq[i] = _cur_st
_glow_seq[i] = _cur_st if _use_glow else _nan
_locked_dir_seq[i] = 1.0 if _locked_bull else -1.0
_af_seq[i] = _adapt_factor
_ac_seq[i] = float(_adapt_cfm)
_age_seq[i] = float(_age)
_conv_pct_seq[i] = _conv_pct
_ers_seq[i] = _ers
_vr_seq[i] = _vol_ratio
_q_pct_seq[i] = _q_pct_out
_last_q_seq[i] = float(_flip_quality) if _has_flipped else _nan
_dist_pct_seq[i] = (abs(_ci - _cur_st) / abs(_ci) * 100.0) if ((_cur_st == _cur_st) and _ci != 0.0) else _nan
_bull_ct_seq[i] = float(_bull_ct)
_bear_ct_seq[i] = float(_bear_ct)
# 5. 光暈與超級趨勢主線(對齊原碼 #26A69A / #EF5350,連續不斷線;手冊線寬上限為 9)
_bull_g3 = Color.rgb(38, 166, 154, 26)
_bear_g3 = Color.rgb(239, 83, 80, 26)
_bull_g2 = Color.rgb(38, 166, 154, 46)
_bear_g2 = Color.rgb(239, 83, 80, 46)
_bull_g1 = Color.rgb(38, 166, 154, 82)
_bear_g1 = Color.rgb(239, 83, 80, 82)
_bull_main = Color.rgb(38, 166, 154, 255)
_bear_main = Color.rgb(239, 83, 80, 255)
plot("外圍光暈", _glow_seq, color=iff(_locked_dir_seq > 0, _bull_g3, _bear_g3), style=Line.line, linewidth=9)
plot("中間光暈", _glow_seq, color=iff(_locked_dir_seq > 0, _bull_g2, _bear_g2), style=Line.line, linewidth=7)
plot("內部光暈", _glow_seq, color=iff(_locked_dir_seq > 0, _bull_g1, _bear_g1), style=Line.line, linewidth=4)
plot("超級趨勢線", _st_seq, color=iff(_locked_dir_seq > 0, _bull_main, _bear_main), style=Line.line, linewidth=2)
if _use_shade:
plot_fillcolor("漸層背景", c, _st_seq, _st_seq == _st_seq, color=iff(_locked_dir_seq > 0, Color.rgb(38, 166, 154, 38), Color.rgb(239, 83, 80, 38)))
# 6. 轉勢訊號標籤(修正 66145:Pine yloc.belowbar 錨定 low()、yloc.abovebar 錨定 high(),絕不誤畫在遠離 K 線之 _st_seq 上!)
if _use_labels:
plot_icon("做多標記", (_up_A + _up_B + _up_C) > 0.5, l, Shape.labelup, color=_bull_main, size=2, offseth=0, offsetv=-6)
plot_icon("做空標記", (_dn_A + _dn_B + _dn_C) > 0.5, h, Shape.labeldown, color=_bear_main, size=2, offseth=0, offsetv=6)
plot_text("做多A", _up_A > 0.5, l, "做多 [A]", color=_bull_main, size=2, offseth=0, offsetv=-18)
plot_text("做多B", _up_B > 0.5, l, "做多 [B]", color=_bull_main, size=2, offseth=0, offsetv=-18)
plot_text("做多C", _up_C > 0.5, l, "做多 [C]", color=_bull_main, size=2, offseth=0, offsetv=-18)
plot_text("做空A", _dn_A > 0.5, h, "做空 [A]", color=_bear_main, size=2, offseth=0, offsetv=18)
plot_text("做空B", _dn_B > 0.5, h, "做空 [B]", color=_bear_main, size=2, offseth=0, offsetv=18)
plot_text("做空C", _dn_C > 0.5, h, "做空 [C]", color=_bear_main, size=2, offseth=0, offsetv=18)
# 7. 數據看板全量導出(對應原碼 11 行看板 + 轉勢觸發收市價 + 警報布林位)
output_parameter(
超級趨勢線=_st_seq,
當前方向=_locked_dir_seq,
持續K線數=_age_seq,
趨勢強度=_conv_pct_seq,
趨勢效率=_ers_seq,
波動率狀態=_vr_seq,
自適應倍數=_af_seq,
自適應確認K線數=_ac_seq,
當棒訊號品質=_q_pct_seq,
上次訊號品質=_last_q_seq,
距離趨勢線=_dist_pct_seq,
做多訊號次數=_bull_ct_seq,
做空訊號次數=_bear_ct_seq,
翻轉收盤價=_flip_px_seq,
任何多空翻轉=_any_flip_seq
)
server.js / Node.js 零依賴 V4 計算引擎(v4_supertrend_engine_A100.js) 6339 B · sha256=af28b1c8bb9af001300997d4cdb10efa1e2b8aa78b41f6982681a339baa12285
"use strict";
/**
* V4 SuperTrend (Adaptive) — Pure JS Engine for server.js / Node.js (Zero Dependencies)
* Exact Pine Script v6 port of v4-supertrend-zh-v6.txt (sha256=4d05ef4c...)
* Seat A100 (A1001477)
*/
function pineRound(x) {
if (!Number.isFinite(x)) return NaN;
return Math.floor(x + 0.5);
}
function computeV4SuperTrend(bars, opts = {}) {
const iLen = Math.max(1, Math.trunc(opts.i_len ?? 14));
const iFactor = Number(opts.i_factor ?? 3.5);
const iErLen = Math.max(3, Math.trunc(opts.i_er_len ?? 10));
const iConfirm = Math.max(1, Math.trunc(opts.i_confirm ?? 2));
const lang = opts.lang === "hk" ? "hk" : "src";
const n = bars.length;
const tr = new Float64Array(n);
const atr = new Float64Array(n).fill(NaN);
for (let i = 0; i < n; i++) {
const h = Number(bars[i][2]), l = Number(bars[i][3]);
if (i === 0) {
tr[i] = h - l;
} else {
const pc = Number(bars[i - 1][4]);
tr[i] = Math.max(h - l, Math.abs(h - pc), Math.abs(l - pc));
}
}
if (n >= iLen) {
let acc = 0;
for (let i = 0; i < iLen; i++) acc += tr[i];
atr[iLen - 1] = acc / iLen;
for (let i = iLen; i < n; i++) {
atr[i] = (atr[i - 1] * (iLen - 1) + tr[i]) / iLen;
}
}
const er = new Float64Array(n);
for (let i = iErLen; i < n; i++) {
const net = Math.abs(Number(bars[i][4]) - Number(bars[i - iErLen][4]));
let path = 0;
for (let k = 0; k < iErLen; k++) {
path += Math.abs(Number(bars[i - k][4]) - Number(bars[i - k - 1][4]));
}
er[i] = path > 0 ? net / path : 0.0;
}
const erSmooth = new Float64Array(n).fill(NaN);
if (n >= 3) {
erSmooth[2] = (er[0] + er[1] + er[2]) / 3.0;
for (let i = 3; i < n; i++) {
erSmooth[i] = er[i] * 0.5 + erSmooth[i - 1] * 0.5;
}
}
let upperBand = NaN, lowerBand = NaN, trendDir = 1;
let lockedBull = true, streak = 0, flipQuality = 0, hasFlipped = false;
let age = 0, bullCt = 0, bearCt = 0;
const series = [];
const labels = [];
for (let i = 0; i < n; i++) {
const h = Number(bars[i][2]), l = Number(bars[i][3]), c = Number(bars[i][4]);
const hl2 = (h + l) * 0.5;
const curAtr = atr[i];
const hasAtr = Number.isFinite(curAtr);
const ers = erSmooth[i];
const hasErs = Number.isFinite(ers);
let volRatio = 1.0;
if (i >= iLen + 48 && hasAtr) {
let s50 = 0;
for (let k = i - 49; k <= i; k++) s50 += atr[k];
const base50 = s50 / 50.0;
if (base50 > 0) volRatio = curAtr / base50;
}
const volRegime = Math.max(Math.min(volRatio, 1.40), 0.75);
const adaptiveFactor = iFactor * volRegime;
let adaptiveConfirm;
if (hasErs && ers < 0.25) adaptiveConfirm = Math.max(iConfirm + 2, 4);
else if (hasErs && ers < 0.45) adaptiveConfirm = iConfirm + 1;
else if (hasErs && ers < 0.65) adaptiveConfirm = iConfirm;
else adaptiveConfirm = Math.max(iConfirm - 1, 1);
const hasRoc = i >= 5 && Number(bars[i - 5][4]) !== 0;
const momPct = hasRoc ? Math.abs((c - Number(bars[i - 5][4])) / Number(bars[i - 5][4]) * 100.0) : NaN;
const atrPct = (hasAtr && c > 0) ? (curAtr / c * 100.0) : 0.0;
let momNorm = 0.0;
if (atrPct > 0) {
momNorm = Number.isFinite(momPct) ? Math.min(momPct / (atrPct * 2.0), 1.0) : NaN;
}
const volScore = Math.max(1.0 - Math.abs(1.0 - volRatio), 0.0);
const qRaw = (hasErs && Number.isFinite(momNorm)) ? (ers * 0.50 + volScore * 0.30 + momNorm * 0.20) : NaN;
const qualityPct = Number.isFinite(qRaw) ? pineRound(qRaw * 100.0) : NaN;
const qualityGrade = (Number.isFinite(qualityPct) && qualityPct >= 70) ? "A" : ((Number.isFinite(qualityPct) && qualityPct >= 50) ? "B" : "C");
const prevUpper = upperBand, prevLower = lowerBand, prevTdir = trendDir;
if (hasAtr) {
const ubBasic = hl2 + adaptiveFactor * curAtr;
const lbBasic = hl2 - adaptiveFactor * curAtr;
const prevC = i > 0 ? Number(bars[i - 1][4]) : NaN;
upperBand = (!Number.isFinite(prevUpper) || ubBasic < prevUpper || (Number.isFinite(prevC) && prevC > prevUpper)) ? ubBasic : prevUpper;
lowerBand = (!Number.isFinite(prevLower) || lbBasic > prevLower || (Number.isFinite(prevC) && prevC < prevLower)) ? lbBasic : prevLower;
}
if (i === 0) {
trendDir = 1;
} else if (prevTdir === 1) {
trendDir = (Number.isFinite(lowerBand) && c < lowerBand) ? -1 : 1;
} else {
trendDir = (Number.isFinite(upperBand) && c > upperBand) ? 1 : -1;
}
const st = trendDir === 1 ? lowerBand : upperBand;
const bull = trendDir === 1;
if (i === 0) lockedBull = bull;
streak = (bull === lockedBull) ? 0 : (streak + 1);
const flipUp = streak >= adaptiveConfirm && bull;
const flipDown = streak >= adaptiveConfirm && !bull;
const anyFlip = flipUp || flipDown;
if (anyFlip) {
lockedBull = bull;
flipQuality = Number.isFinite(qualityPct) ? qualityPct : 0;
hasFlipped = true;
}
if (flipUp) {
bullCt += 1;
labels.push({
barIndex: i, time: bars[i][0], direction: "LONG",
yPineArg: st, yRenderAnchor: l, yloc: "belowbar",
close: c, quality: qualityPct, grade: qualityGrade,
text: (lang === "hk" ? "造好 [" : "做多 [") + qualityGrade + "]\n" + c.toFixed(2)
});
}
if (flipDown) {
bearCt += 1;
labels.push({
barIndex: i, time: bars[i][0], direction: "SHORT",
yPineArg: st, yRenderAnchor: h, yloc: "abovebar",
close: c, quality: qualityPct, grade: qualityGrade,
text: (lang === "hk" ? "沽空 [" : "做空 [") + qualityGrade + "]\n" + c.toFixed(2)
});
}
age = anyFlip ? 0 : (age + 1);
const sTime = Math.min(age / 60.0, 1.0);
const s = hasErs ? (sTime * 0.65 + ers * 0.35) : NaN;
const distPct = (Number.isFinite(st) && c !== 0) ? (Math.abs(c - st) / Math.abs(c) * 100.0) : NaN;
series.push({
index: i, st, trendDir, lockedBull, erSmooth: ers, volRatio,
adaptiveFactor, adaptiveConfirm, qualityPct, qualityGrade,
flipQuality: hasFlipped ? flipQuality : 0, hasFlipped,
age, s, convictionPct: Number.isFinite(s) ? pineRound(s * 100.0) : NaN,
distPct, bullCt, bearCt, flipUp, flipDown, anyFlip
});
}
return { series, labels, latest: series[n - 1] || null };
}
module.exports = { computeV4SuperTrend };
verify_v4_supertrend_A100.py)# -*- coding: utf-8 -*-
"""Automated Verification Suite for A100 V4 SuperTrend (FTNN Python HK + Source + Node.js)"""
import ast, json, math, subprocess, sys, types
ALLOWED_IMPORT_MODULES = {"fdatetime", "fmath", "fta", "ftool"}
def check_ast_compliance(py_path):
src = open(py_path, "r", encoding="utf-8").read()
tree = ast.parse(src, filename=py_path)
imports = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imports.append(alias.name)
assert alias.name in ALLOWED_IMPORT_MODULES, f"Forbidden import {alias.name} in {py_path}"
elif isinstance(node, ast.ImportFrom):
mod = node.module or ""
imports.append(f"from {mod}")
assert mod in ALLOWED_IMPORT_MODULES, f"Forbidden from-import {mod} in {py_path}"
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "plot":
for kw in node.keywords:
if kw.arg == "linewidth" and isinstance(kw.value, ast.Constant):
lw = kw.value.value
assert 1 <= lw <= 9, f"Invalid linewidth={lw} in {py_path}"
return imports
class MockSeq(list):
@property
def size(self):
return len(self)
@property
def values(self):
return list(self)
def __mul__(self, o):
return MockSeq([float(x) * float(o) for x in self])
def __add__(self, o):
if isinstance(o, MockSeq):
return MockSeq([float(a) + float(b) for a, b in zip(self, o)])
return MockSeq([float(x) + float(o) for x in self])
def __gt__(self, o):
return MockSeq([bool(x == x and x > o) for x in self])
def __eq__(self, o):
if isinstance(o, MockSeq):
return MockSeq([bool(a == a and b == b and a == b) for a, b in zip(self, o)])
return super().__eq__(o)
def run_ftnn_script(py_path, bars):
ftool_mod = types.ModuleType("ftool")
def _iff(cond, t_val, f_val):
out = []
for i, c in enumerate(cond):
tv = t_val[i] if isinstance(t_val, list) else t_val
fv = f_val[i] if isinstance(f_val, list) else f_val
out.append(tv if bool(c) else fv)
return MockSeq(out)
ftool_mod.iff = _iff
fmath_mod = types.ModuleType("fmath")
fmath_mod.floor = math.floor
sys.modules["ftool"] = ftool_mod
sys.modules["fmath"] = fmath_mod
class Color:
@staticmethod
def rgb(r, g, b, a=255):
return ("rgba", r, g, b, a)
@staticmethod
def hex(h):
return ("hex", h)
class Line:
line = "line"
class Shape:
labelup = "labelup"
labeldown = "labeldown"
circle = "circle"
cap = {"plots": {}, "fill": {}, "icons": {}, "texts": {}, "outputs": {}}
env = {
"__name__": "__main__",
"indicator": lambda *a, **k: None,
"input_parameter": lambda name, default: default,
"open": lambda: MockSeq([float(b[1]) for b in bars]),
"high": lambda: MockSeq([float(b[2]) for b in bars]),
"low": lambda: MockSeq([float(b[3]) for b in bars]),
"close": lambda: MockSeq([float(b[4]) for b in bars]),
"vol": lambda: MockSeq([float(b[5]) for b in bars]),
"Color": Color,
"Line": Line,
"Shape": Shape,
"plot": lambda name, seq, **kw: cap["plots"].__setitem__(name, {"seq": list(seq), **kw}),
"plot_fillcolor": lambda name, v1, v2, cond=True, **kw: cap["fill"].__setitem__(name, {"v1": list(v1), "v2": list(v2), "cond": list(cond) if isinstance(cond, list) else cond, **kw}),
"plot_icon": lambda name, cond, y, shape, **kw: cap["icons"].__setitem__(name, {"cond": list(cond), "y": list(y), "shape": shape, **kw}),
"plot_text": lambda name, cond, y, text, **kw: cap["texts"].__setitem__(name, {"cond": list(cond), "y": list(y), "text": text, **kw}),
"output_parameter": lambda **kw: cap["outputs"].update({k: list(v) for k, v in kw.items()}),
}
code = compile(open(py_path, "r", encoding="utf-8").read(), py_path, "exec")
exec(code, env)
return cap
def main():
imp_hk = check_ast_compliance("v4_supertrend_ftnn_hk_A100.py")
imp_src = check_ast_compliance("v4_supertrend_ftnn_src_A100.py")
print("TEST 1 PASS [AST & Manual Compliance]:", imp_hk, imp_src)
golden = json.load(open("v4_golden_300bars.json", "r", encoding="utf-8"))
bars = golden["input_bars_ts_o_h_l_c_v"]
cap_hk = run_ftnn_script("v4_supertrend_ftnn_hk_A100.py", bars)
cap_src = run_ftnn_script("v4_supertrend_ftnn_src_A100.py", bars)
# Verify HK vs SRC numeric outputs are 100% bit-for-bit identical across all 15 exported sequences
hk_vals = list(cap_hk["outputs"].values())
src_vals = list(cap_src["outputs"].values())
assert len(hk_vals) == len(src_vals) == 15
for s_a, s_b in zip(hk_vals, src_vals):
for a, b in zip(s_a, s_b):
if math.isnan(a) and math.isnan(b):
continue
assert a == b, f"HK vs SRC mismatch: {a} != {b}"
print("TEST 2 PASS [HK vs Source-ZH Bit-Exact Output Parity]: 15x300 = 4,500 cells 0 diff")
out = cap_hk["outputs"]
# Check warmup bars 0..1 er_smooth is NaN and adaptiveConfirm is 1 (Pine v6 exact semantics)
assert math.isnan(out["趨勢效率ER"][0]) and math.isnan(out["趨勢效率ER"][1])
assert out["確認陰陽燭數"][0] == 1.0 and out["確認陰陽燭數"][1] == 1.0
print("TEST 3 PASS [Pine v6 Warmup Semantics]: bars 0..1 er_smooth=NaN -> adaptive_confirm=1")
# Verify all 14 golden checkpoints
max_diff = 0.0
for cp in golden["expected_checkpoints"]:
idx = cp["index"]
checks = [
("st", out["超級趨勢線"][idx], cp["st"]),
("erSmooth", out["趨勢效率ER"][idx], cp["erSmooth"]),
("volRatio", out["波幅比率"][idx], cp["volRatio"]),
("adaptiveFactor", out["自適應倍數"][idx], cp["adaptiveFactor"]),
("adaptiveConfirm", out["確認陰陽燭數"][idx], float(cp["adaptiveConfirm"])),
("lockedBull", out["現時方向"][idx] > 0, cp["lockedBull"]),
("qualityPct", out["即時質素分"][idx], float(cp["qualityPct"])),
("convPct", out["趨勢強度Pct"][idx], float(math.floor(cp["s"] * 100.0 + 0.5))),
]
for name, got, exp in checks:
if isinstance(exp, bool):
assert got is exp, f"CP {idx} {name}: got={got} exp={exp}"
else:
d = abs(float(got) - float(exp))
if d > max_diff:
max_diff = d
assert d <= 1e-9, f"CP {idx} {name}: got={got} exp={exp} diff={d}"
print(f"TEST 4 PASS [14x8=112 Golden Checkpoints]: 0 mismatch (max_abs_diff={max_diff:.3e})")
# Verify flip labels AND 66145 Y-anchor fix (anchored on high[158] and low[240], NOT st!)
dn_A = cap_hk["texts"]["沽空A"]
up_A = cap_hk["texts"]["造好A"]
dn_bars = [i for i, v in enumerate(dn_A["cond"]) if v]
up_bars = [i for i, v in enumerate(up_A["cond"]) if v]
assert dn_bars == [158], f"Expected SHORT_A at [158], got {dn_bars}"
assert up_bars == [240], f"Expected LONG_A at [240], got {up_bars}"
assert dn_A["y"][158] == float(bars[158][2]), "SHORT label must anchor on high[158] (yloc.abovebar)"
assert up_A["y"][240] == float(bars[240][3]), "LONG label must anchor on low[240] (yloc.belowbar)"
assert out["轉勢收市價"][158] == 23071.47 and out["轉勢收市價"][240] == 21874.24
print(f"TEST 5 PASS [Flip Labels & 66145 Y-Anchor Fix]: bar158 SHORT[A] y=high({dn_A['y'][158]})!=st({out['超級趨勢線'][158]:.2f}); bar240 LONG[A] y=low({up_A['y'][240]})!=st({out['超級趨勢線'][240]:.2f})")
# Verify expected_latest
lat = golden["expected_latest"]
assert abs(out["超級趨勢線"][299] - lat["st"]) < 1e-9
assert int(out["持續陰陽燭數"][299]) == lat["age"] == 59
assert int(out["趨勢強度Pct"][299]) == lat["convictionPct"] == 99
assert abs(out["自適應倍數"][299] - lat["adaptiveFactor"]) < 1e-9
assert int(out["上次訊號質素"][299]) == lat["flipQuality"] == 82
assert abs(out["偏離趨勢線Pct"][299] - lat["distancePct"]) < 1e-9
assert int(out["造好訊號次數"][299]) == 1 and int(out["沽空訊號次數"][299]) == 1
print("TEST 6 PASS [Latest Bar 299 All Dashboard Metrics]: 0 mismatch")
# TEST 7: A23 66200 Bar-13 Crash Counterexample (close[13] < lower_band[13] on first valid ATR bar!)
ce_bars = []
for i in range(30):
if i < 13:
ce_bars.append([1700000000000 + i * 60000, 1000.0, 1002.0, 998.0, 1000.0, 100.0])
elif i == 13:
# Big bearish crash at bar 13: hl2=985, tr[0..12]=4, tr[13]=30 -> atr[13]=(52+30)/14=5.857
# vol_ratio=1.0 -> af=3.5 -> lb_basic = 985 - 20.5 = 964.5; let's crash close to 950 (< 964.5)!
ce_bars.append([1700000000000 + i * 60000, 1000.0, 1000.0, 945.0, 950.0, 500.0])
else:
ce_bars.append([1700000000000 + i * 60000, 950.0, 952.0, 946.0, 948.0, 100.0])
cap_ce = run_ftnn_script("v4_supertrend_ftnn_hk_A100.py", ce_bars)
st_ce_13 = cap_ce["outputs"]["超級趨勢線"][13]
# hl2[13] = 972.5, tr[0..12]=4 (sum=52), tr[13]=1000-945=55 -> atr[13]=107/14=7.642857...
# upper_band[13] = 972.5 + 3.5 * 7.642857 = 999.25 (SHORT!), whereas lower_band[13] = 945.75 (wait: close=950 > 945.75, make close=940!)
ce_bars[13] = [1700000000000 + 13 * 60000, 1000.0, 1000.0, 938.0, 940.0, 500.0]
cap_ce = run_ftnn_script("v4_supertrend_ftnn_hk_A100.py", ce_bars)
st_ce_13 = cap_ce["outputs"]["超級趨勢線"][13]
exp_atr_13 = (13 * 4.0 + 62.0) / 14.0
exp_ub_13 = ((1000.0 + 938.0) * 0.5) + 3.5 * exp_atr_13
assert abs(st_ce_13 - exp_ub_13) < 1e-9, f"Bar 13 must flip SHORT (st=upper_band={exp_ub_13}), got {st_ce_13}"
print(f"TEST 7 PASS [66200 Bar-13 Crash Counterexample]: bar13 immediately flips SHORT with st=upper_band={st_ce_13:.4f}")
# TEST 8: Cross-language parity with Node.js v4_supertrend_engine_A100.js across all 300 golden bars + bar-13 counterexample
node_check = subprocess.check_output([
"node", "-e",
"""
const fs = require("fs");
const { computeV4SuperTrend } = require("./v4_supertrend_engine_A100.js");
const golden = JSON.parse(fs.readFileSync("./v4_golden_300bars.json", "utf8"));
const res = computeV4SuperTrend(golden.input_bars_ts_o_h_l_c_v, { lang: "hk" });
console.log(JSON.stringify({ st: res.series.map(r => r.st), labels: res.labels }));
"""
], text=True)
nj = json.loads(node_check)
for i in range(300):
pa = out["超級趨勢線"][i]
ja = nj["st"][i]
if ja is None:
assert math.isnan(pa)
else:
assert abs(pa - ja) < 1e-11, f"Py vs JS mismatch at bar {i}: {pa} vs {ja}"
assert [l["barIndex"] for l in nj["labels"]] == [158, 240]
print("TEST 8 PASS [Python <-> Node.js v20.20.2 300-Bar Cross-Language Parity]: 300/300 bars 0 mismatch")
if __name__ == "__main__":
main()