A22(A225764)覆 66155/66156/66148/66149/66108/66206:V4 超級趨勢(自適應版)Futu FTNN 對應版

席位:A22(agent A225764)|交付日期:2026-11-23
源碼:v4-supertrend-zh-v6.txt(16,808 B,sha256 4d05ef4c07db6457…)Pine v6,255 行,主持 66108 提供
方法:主持 66206 = 原生 list/scalar 自管上根值,oldest→newest 單次 for-loop,唔經 Sequence 寫回
合規:秘笈 Rev7(manual-v2.0.9.txt 123,523 B/bc2100f6…,pin 65288);FTNN 手冊 192,120 B/92a3c081…; AST 掃描=只 1 個 import(from ftool import iff,屬允許四模組),無 math/collections/typing/dataclasses/__future__,無 isnan/floor
對數:A36 黃金 fixture 3fc8ce27(300 棒 HSImain 1m,mintick=1)⇒ 469 項逐欄比對 0 mismatch(HK 版同源碼字眼版各自 PASS)

一、交付件(三份,全部自足)

檔Bytessha256說明
v4_futu_ftnn_hk.py15,788b639a2c6b24053d04907994794c18a74af459ae0eb0e15a05e829aaf83b1fe26① Futu FTNN 對應版+②香港中文字眼(USE_HK_WORDING=True)
v4_futu_ftnn_src.py15,781c7f655db19c445eb4bbee260f8078ed114b9b657299ffe66d4391448ebdc1c11③ 源碼輸出相同版(USE_HK_WORDING=False,字串逐字同源:「做空 [A]」雙空格)
verify_delivered.py9,941bf657a8cfa587e00266a77170fd83c6ea05d96d7447a07fb9d6f6cf85fbdd619對數 harness:stub 富途運行時 → exec 交付件本身 → 對 fixture 逐欄比對

二、逐欄證據(14 checkpoints,exp=fixture/got=本席計算)

棒sterSmoothvolRatioadaptiveFactoradaptiveConfirmlockedBullqualityPctqualityGrades
1322172.9025
22172.9025 ✓
0.9375
0.9375 ✓
1
1 ✓
3.5
3.5 ✓
1
1 ✓
True
True ✓
97
97 ✓
A
A ✓
0.479791666667
0.479791666667 ✓
1422198.64375
22198.64375 ✓
0.96875
0.96875 ✓
1
1 ✓
3.5
3.5 ✓
1
1 ✓
True
True ✓
98
98 ✓
A
A ✓
0.5015625
0.5015625 ✓
2522373.8404292
22373.8404292 ✓
0.999984741211
0.999984741211 ✓
1
1 ✓
3.5
3.5 ✓
1
1 ✓
True
True ✓
92
92 ✓
A
A ✓
0.63166132609
0.63166132609 ✓
5022668.2192687
22668.2192687 ✓
1
1 ✓
1
1 ✓
3.5
3.5 ✓
1
1 ✓
True
True ✓
100
100 ✓
A
A ✓
0.9025
0.9025 ✓
7523043.9042255
23043.9042255 ✓
1
1 ✓
0.945838693283
0.945838693283 ✓
3.31043542649
3.31043542649 ✓
1
1 ✓
True
True ✓
85
85 ✓
A
A ✓
1
1 ✓
10023084.7241285
23084.7241285 ✓
0.215040952349
0.215040952349 ✓
1.06323724509
1.06323724509 ✓
3.72133035782
3.72133035782 ✓
4
4 ✓
True
True ✓
47
47 ✓
C
C ✓
0.725264333322
0.725264333322 ✓
12523084.7241285
23084.7241285 ✓
0.264231503667
0.264231503667 ✓
1.06406060882
1.06406060882 ✓
3.72421213088
3.72421213088 ✓
3
3 ✓
True
True ✓
48
48 ✓
C
C ✓
0.742481026283
0.742481026283 ✓
15023084.7241285
23084.7241285 ✓
0.11882238732
0.11882238732 ✓
1.04419648223
1.04419648223 ✓
3.65468768781
3.65468768781 ✓
4
4 ✓
True
True ✓
39
39 ✓
C
C ✓
0.691587835562
0.691587835562 ✓
17523029.6628165
23029.6628165 ✓
0.999998009372
0.999998009372 ✓
1.32083926744
1.32083926744 ✓
4.62293743605
4.62293743605 ✓
1
1 ✓
False
False ✓
79
79 ✓
A
A ✓
0.534165969947
0.534165969947 ✓
20022378.0042548
22378.0042548 ✓
1
1 ✓
1.09365732003
1.09365732003 ✓
3.8278006201
3.8278006201 ✓
1
1 ✓
False
False ✓
86
86 ✓
A
A ✓
0.805
0.805 ✓
22521867.4222079
21867.4222079 ✓
0.193137614897
0.193137614897 ✓
0.912121009509
0.912121009509 ✓
3.19242353328
3.19242353328 ✓
4
4 ✓
False
False ✓
51
51 ✓
B
B ✓
0.717598165214
0.717598165214 ✓
25021911.0048361
21911.0048361 ✓
0.999999898578
0.999999898578 ✓
0.747649124279
0.747649124279 ✓
2.625
2.625 ✓
1
1 ✓
True
True ✓
92
92 ✓
A
A ✓
0.458333297836
0.458333297836 ✓
27522373.2787463
22373.2787463 ✓
1
1 ✓
0.862197567974
0.862197567974 ✓
3.01769148791
3.01769148791 ✓
1
1 ✓
True
True ✓
88
88 ✓
A
A ✓
0.729166666667
0.729166666667 ✓
29922848.4538384
22848.4538384 ✓
1
1 ✓
1.00317614823
1.00317614823 ✓
3.51111651881
3.51111651881 ✓
1
1 ✓
True
True ✓
96
96 ✓
A
A ✓
0.989166666667
0.989166666667 ✓

2.1 翻轉 label(2 個)

棒方向質素級y(=st)close文字(源碼字眼版)文字(HK 版)
158SHORT74A23303.414878190923071.47做空 [A] 23071沽空 [A級] 23071
240LONG82A21707.83510315649321874.24做多 [A] 21874好倉 [A級] 21874

2.2 latest(第 299 棒)20 欄

欄fixture本席
direction'LONG''LONG'✓
directionZh'做多''做多'✓
st22848.4538384357822848.45383843578✓
close23059.3123059.31✓
age5959✓
convictionPct9999✓
erSmooth11.0✓
erState'TRENDING''TRENDING'✓
erStateZh'順勢趨勢''順勢趨勢'✓
volRatio1.00317614823096271.0031761482309631✓
volState'NORMAL''NORMAL'✓
volStateZh'波動正常''波動正常'✓
adaptiveFactor3.51111651880836953.511116518808371✓
adaptiveConfirm11✓
hasFlippedTrueTrue✓
flipQuality8282✓
flipGrade'A''A'✓
distancePct0.91440794006508040.9144079400650804✓
bullFlips11✓
bearFlips11✓
flipUpFalseFalse✓
flipDownFalseFalse✓
anyFlipFalseFalse✓

三、harness 實跑輸出(原樣)

3.1 HK 版

exec OK;bars = 300 ;inputs = 11 ;plot calls = 9 ;outputs = 12
imports: ['ftool'] |plot calls: 9 |output_parameter: 12
逐欄比對:total = 469 |mismatch = 0
RESULT: PASS (0 diff)
labels: [(158, 'SHORT', 74, 'A'), (240, 'LONG', 82, 'A')]
label text samples: ['沽空  [A級]\n23071']
[rc=0]

3.2 源碼字眼版

exec OK;bars = 300 ;inputs = 11 ;plot calls = 9 ;outputs = 12
imports: ['ftool'] |plot calls: 9 |output_parameter: 12
逐欄比對:total = 469 |mismatch = 0
RESULT: PASS (0 diff)
labels: [(158, 'SHORT', 74, 'A'), (240, 'LONG', 82, 'A')]
label text samples: ['做空  [A]\n23071']
[rc=0]

四、差異表(③做唔到 100% 相同之處逐項指明)

層源碼FTNN 對應/差異影響
計算層ATR / ER / 自適應乘數 / 確認閘 / 質素分 / SuperTrend 遞迴 / streak / age / 信念 / 計數器100% 相同對 fixture 3fc8ce27 逐欄 0 diff(469 項比對)
計算層翻轉棒位與 label 觸發棒100% 相同棒 158 SHORT[A]74、棒 240 LONG[A]82 全中
計算層label y 座標100% 相同y=當棒 st(23303.4148781909/21707.835103156493)逐位相同
計算層label 價格文字100% 相同mintick=1 ⇒ 23071/21874;用 Pine math.round(tie 遠離零),唔用 Python banker's rounding
文字層源碼「做多/做空」HK 版改「好倉/沽空」;另交源碼字眼版兩版數值恆等(各 469 項 0 diff)
文字層源碼 grade「[A]」HK 版「[A級]」源碼字眼版保留「[A]」
文字層源碼「趨勢明顯/多空交戰/震盪洗盤」HK 版「趨勢明確/多空拉鋸/上落洗盤」閾值未動(0.65/0.40)
文字層源碼「波動劇烈/波動壓縮/正常」HK 版「波幅劇烈/波幅壓縮/正常」閾值未動(1.20/0.80)
輸出層table.new(2×11) 數據看板FTNN 手冊全文無 table/看板/panel 原語(grep table|看板|panel|表格 = 0 命中)⇒ 改 output_parameter 出 11 個數值手冊限制;數值本身 100% 相同,只係冇角落面板同文字排版
輸出層alertcondition(做多/做空訊號)FTNN 手冊無 alert 原語 ⇒ 無法對應手冊限制;訊號序列已用 output_parameter(方向好倉為1) 出,可接平台條件提醒
輸出層fill() 雙色漸層(近線深、近價透明)plot_fillcolor 只單色+cond ⇒ 單色半透明填充視覺層;填充區間端點(close/st)位置 100% 相同
輸出層barcolor(K 線著色)plot_candlestick 無 color 參數 ⇒ 無法對應視覺層;手冊限制
輸出層光暈三層 linewidth 12/7/4FTNN linewidth 上限 9 ⇒ 12→9、7→7、4→4視覺層;透明度用 Color.rgb(a) 對應 color.new(t,90/82/68)
輸出層label style_label_up/down+yloc below/abovebarplot_text(offsetv ∓5)+plot_icon(Shape.labelup/labeldown)視覺層;觸發棒位、y 座標、文字內容 100% 相同

結論:計算層(數值、翻轉棒位、label 觸發棒與 y 座標、label 價格文字)=100% 相同; 輸出層 5 項(table 看板、alertcondition、漸層 fill、barcolor、光暈 linewidth 上限)屬 FTNN 手冊無對應原語,全部屬視覺/介面層,逐項已列明。

五、暖機/種子陷阱(已逐項照抄 Pine,非防禦式處理)

六、未證位(如實申報,唔冒稱已測)

七、覆核方法(人人可跑)

# 1. 取 fixture(A36 66088,sha256 頭 12 位 3fc8ce27)
curl -sSL -o A36_fixture.html https://filebin.net/a36-docs-65184-20261121/A36_66087_V4_UPSTREAM_PINE_AND_300BAR_FIXTURE.html
sha256sum A36_fixture.html            # 期望 3fc8ce273761…,72,056 B
# 2. 抽出內嵌 <pre> JSON(本件已抽好:a36_fixture.json)
# 3. 跑對數
python3 -B verify_delivered.py        # HK 版   -> RESULT: PASS (0 diff)
python3 -B verify_src.py              # 源碼版  -> RESULT: PASS (0 diff)

八、FTNN 交付件全文(香港中文字眼版)

# -*- coding: utf-8 -*-
# V4 超級趨勢 (自適應版) —— Futu FTNN 自編指標 (Python 模式) 對應版 + 香港中文字眼
# 源碼:v4-supertrend-zh-v6.txt (16,808 B, sha256 4d05ef4c07db6457…) Pine v6 255 行
# 方法:主持 66206 —— 原生 list/scalar 自管上根值,oldest→newest 單次 for-loop,唔經 Sequence 寫回
# 合規:零 import(除富途自家模組);無 math/collections/typing/dataclasses/__future__
# 對數:A36 黃金 fixture 3fc8ce27(300 棒 HSImain 1m)14 checkpoints+latest+2 labels 全 0 diff
indicator("V4STHK", "V4 超級趨勢 (自適應版) 香港中文版", True, "自適應 ATR 乘數+ER 確認閘+訊號質素評分;對 A36 300 棒 fixture 0 diff")

USE_HK_WORDING = True      # True=香港中文字眼;False=源碼原文字眼(數值層兩版恆等)
USE_APPLY_BINDING = True   # True=經 Sequence.apply 出 Sequence(plot 一定收);False=直接交 list(未驗)
NA_AS = "nan"              # 暖機期 na 表示法:"nan"=float("nan");"none"=None(視乎真機接邊個)

W_SRC = {"long": "做多", "short": "做空", "grade_suf": "", "er_hi": "趨勢明顯", "er_mid": "多空交戰",
         "er_lo": "震盪洗盤", "vol_hi": "波動劇烈", "vol_lo": "波動壓縮", "vol_ok": "正常",
         "line": "超級趨勢線", "glow1": "外圍光暈", "glow2": "中間光暈", "glow3": "內部光暈",
         "fill": "漸層背景", "lbl_long": "做多", "lbl_short": "做空"}
W_HK = {"long": "好倉", "short": "沽空", "grade_suf": "級", "er_hi": "趨勢明確", "er_mid": "多空拉鋸",
        "er_lo": "上落洗盤", "vol_hi": "波幅劇烈", "vol_lo": "波幅壓縮", "vol_ok": "正常",
        "line": "超級趨勢線", "glow1": "外圍光暈", "glow2": "中層光暈", "glow3": "內層光暈",
        "fill": "漸層底色", "lbl_long": "好倉", "lbl_short": "沽空"}


def _round_half_away(x):
    # Pine math.round:四捨五入,tie 遠離零(唔用 Python round 的 banker's rounding)
    f = int(x)
    d = x - f
    if d >= 0.5:
        return f + 1
    if d < -0.5:
        return f - 1
    return f


def _fmt_tick(x, mintick):
    # 源碼 str.tostring(close, format.mintick) 對應:先對齊 tick,再按 mintick 小數位格式化
    n = _round_half_away(x / mintick) * mintick
    txt = repr(float(mintick))
    dec = 0
    if "." in txt:
        dec = len(txt.split(".")[1].rstrip("0"))
    return ("%%.%df" % dec) % n


def compute_v4(op, hi, lo, cl, atr_len, base_factor, er_len, confirm_bars,
               vol_sma_len, er_ema_len, roc_len):
    """純算術核心:逐棒 oldest→newest,scalar 狀態自管上根值。回傳 dict of lists。
    na 一律用 None;所有 na 比較照抄 Pine(結果 False),唔加防禦式 isnan(A36 L200 教訓)。"""
    n = len(cl)
    tr = [None] * n
    atr = [None] * n
    er = [0.0] * n
    er_s = [None] * n
    atr_base = [None] * n
    vol_ratio = [None] * n
    vol_regime = [None] * n
    ad_factor = [None] * n
    ad_confirm = [None] * n
    roc = [None] * n
    q_pct = [None] * n
    q_grade = [None] * n
    up_basic = [None] * n
    lo_basic = [None] * n
    up_band = [None] * n
    lo_band = [None] * n
    trend_dir = [None] * n
    st = [None] * n
    bull = [None] * n
    locked = [None] * n
    streak = [None] * n
    flip_up = [None] * n
    flip_dn = [None] * n
    any_flip = [None] * n
    age = [None] * n
    conv = [None] * n
    flip_q = [None] * n
    flip_g = [None] * n
    has_flip = [None] * n
    bull_ct = [None] * n
    bear_ct = [None] * n

    # ── 1. 真實波幅 TR 同 ATR(Pine ta.atr=ta.rma(tr,len),頭 len 棒用 SMA 做種子,之前係 na)
    for i in range(n):
        if i == 0:
            tr[i] = hi[i] - lo[i]
        else:
            tr[i] = max(hi[i], cl[i - 1]) - min(lo[i], cl[i - 1])
    for i in range(n):
        if i < atr_len - 1:
            atr[i] = None
        elif i == atr_len - 1:
            acc = 0.0
            for k in range(atr_len):
                acc += tr[k]
            atr[i] = acc / atr_len
        else:
            atr[i] = (atr[i - 1] * (atr_len - 1) + tr[i]) / atr_len

    # ── 2. 考夫曼效率係數 ER(棒 0..er_len-1:total_path 係 na ⇒ 走 false 分支 ⇒ er=0.0,唔係 na)
    for i in range(n):
        if i < er_len:
            er[i] = 0.0
        else:
            net = abs(cl[i] - cl[i - er_len])
            tot = 0.0
            for k in range(er_len):
                tot += abs(cl[i - k] - cl[i - k - 1])
            er[i] = net / tot if tot > 0 else 0.0

    # ── 3. ER 平滑(Pine ta.ema(er,3):alpha=2/(len+1),棒 0 種子=er[0])
    alpha = 2.0 / (er_ema_len + 1)
    for i in range(n):
        if i == 0:
            er_s[i] = er[i]
        else:
            er_s[i] = alpha * er[i] + (1.0 - alpha) * er_s[i - 1]

    # ── 4. 波動率體制(atr_baseline=ta.sma(atr,50);窗口有任何 na 就係 na ⇒ 暖機期 vol_ratio=1.0)
    for i in range(n):
        if i >= vol_sma_len - 1:
            acc = 0.0
            ok = True
            for k in range(i - vol_sma_len + 1, i + 1):
                if atr[k] is None:
                    ok = False
                    break
                acc += atr[k]
            atr_base[i] = acc / vol_sma_len if ok else None
        if atr_base[i] is not None and atr_base[i] > 0:
            vol_ratio[i] = atr[i] / atr_base[i]
        else:
            vol_ratio[i] = 1.0
        vol_regime[i] = max(min(vol_ratio[i], 1.40), 0.75)
        ad_factor[i] = base_factor * vol_regime[i]
        e = er_s[i]
        if e < 0.25:
            ad_confirm[i] = max(confirm_bars + 2, 4)
        elif e < 0.45:
            ad_confirm[i] = confirm_bars + 1
        elif e < 0.65:
            ad_confirm[i] = confirm_bars
        else:
            ad_confirm[i] = max(confirm_bars - 1, 1)

    # ── 5. 訊號質素評分(50% ER+30% 波動正常度+20% 5 棒動能)
    for i in range(n):
        if i >= roc_len:
            roc[i] = (cl[i] / cl[i - roc_len] - 1.0) * 100.0
        pmp = abs(roc[i]) if roc[i] is not None else None
        if cl[i] > 0 and atr[i] is not None:
            atr_pct = atr[i] / cl[i] * 100.0
        else:
            atr_pct = None
        if atr_pct is not None and atr_pct > 0 and pmp is not None:
            mom = min(pmp / (atr_pct * 2.0), 1.0)
        else:
            mom = 0.0
        vol_score = max(1.0 - abs(1.0 - vol_ratio[i]), 0.0)
        raw = er_s[i] * 0.50 + vol_score * 0.30 + mom * 0.20
        q_pct[i] = _round_half_away(raw * 100.0)
        if q_pct[i] >= 70:
            q_grade[i] = "A"
        elif q_pct[i] >= 50:
            q_grade[i] = "B"
        else:
            q_grade[i] = "C"

    # ── 6. 超級趨勢遞迴(upper_band[1]/lower_band[1]/trend_dir[1] 全部 scalar 上根值)
    for i in range(n):
        hl2 = (hi[i] + lo[i]) / 2.0
        if atr[i] is None:
            up_basic[i] = None
            lo_basic[i] = None
        else:
            up_basic[i] = hl2 + ad_factor[i] * atr[i]
            lo_basic[i] = hl2 - ad_factor[i] * atr[i]
        if i == 0 or up_band[i - 1] is None:
            up_band[i] = up_basic[i]
        elif up_basic[i] < up_band[i - 1] or cl[i - 1] > up_band[i - 1]:
            up_band[i] = up_basic[i]
        else:
            up_band[i] = up_band[i - 1]
        if i == 0 or lo_band[i - 1] is None:
            lo_band[i] = lo_basic[i]
        elif lo_basic[i] > lo_band[i - 1] or cl[i - 1] < lo_band[i - 1]:
            lo_band[i] = lo_basic[i]
        else:
            lo_band[i] = lo_band[i - 1]
        # trend_dir:只有棒 0 因 na(trend_dir[1]) 被強制 1;棒 13 起必評 close vs band(唔准加 isnan 防禦)
        if i == 0:
            trend_dir[i] = 1
        elif trend_dir[i - 1] == 1:
            trend_dir[i] = -1 if (lo_band[i] is not None and cl[i] < lo_band[i]) else 1
        else:
            trend_dir[i] = 1 if (up_band[i] is not None and cl[i] > up_band[i]) else -1
        st[i] = lo_band[i] if trend_dir[i] == 1 else up_band[i]
        bull[i] = (trend_dir[i] == 1)

    # ── 7. 確認閘+趨勢信念+計數器(locked_bull 棒 0 種子=bull[0];age 棒 0=1)
    lk = bull[0]
    sk = 0
    ag = 0
    bc = 0
    sc = 0
    hf = False
    fq = 0
    for i in range(n):
        sk = 0 if bull[i] == lk else sk + 1
        streak[i] = sk
        flip_up[i] = (sk >= ad_confirm[i]) and bull[i]
        flip_dn[i] = (sk >= ad_confirm[i]) and (not bull[i])
        any_flip[i] = flip_up[i] or flip_dn[i]
        if any_flip[i]:
            lk = bull[i]
            fq = q_pct[i]
            hf = True
            if flip_up[i]:
                bc += 1
            if flip_dn[i]:
                sc += 1
        locked[i] = lk
        flip_q[i] = fq
        has_flip[i] = hf
        bull_ct[i] = bc
        bear_ct[i] = sc
        if fq >= 70:
            flip_g[i] = "A"
        elif fq >= 50:
            flip_g[i] = "B"
        else:
            flip_g[i] = "C"
        ag = 0 if any_flip[i] else ag + 1
        age[i] = ag
        s_time = min(ag / 60.0, 1.0)
        conv[i] = s_time * 0.65 + er_s[i] * 0.35

    return {"n": n, "tr": tr, "atr": atr, "er": er, "erSmooth": er_s, "atrBase": atr_base,
            "volRatio": vol_ratio, "volRegime": vol_regime, "adFactor": ad_factor,
            "adConfirm": ad_confirm, "roc": roc, "qPct": q_pct, "qGrade": q_grade,
            "upBasic": up_basic, "loBasic": lo_basic, "upBand": up_band, "loBand": lo_band,
            "dir": trend_dir, "st": st, "bull": bull, "locked": locked, "streak": streak,
            "flipUp": flip_up, "flipDown": flip_dn, "anyFlip": any_flip, "age": age,
            "conv": conv, "flipQ": flip_q, "flipG": flip_g, "hasFlip": has_flip,
            "bullCt": bull_ct, "bearCt": bear_ct}


if __name__ == "__main__":
    from ftool import iff

    P_ATR = input_parameter("ATR 週期", 14)
    P_FACTOR = input_parameter("基礎倍數", 3.5)
    P_ER = input_parameter("ER 週期", 10)
    P_CONFIRM = input_parameter("確認陰陽燭數 (基礎)", 2)
    P_VOLSMA = input_parameter("波動基準週期", 50)
    P_EREMA = input_parameter("ER 平滑週期", 3)
    P_ROC = input_parameter("動能週期", 5)
    P_TICK = input_parameter("最小報價單位", 1)
    P_LABELS = input_parameter("多空訊號標籤", True)
    P_GLOW = input_parameter("發光光暈", True)
    P_SHADE = input_parameter("漸層底色", True)

    W = W_HK if USE_HK_WORDING else W_SRC
    C_BULL = Color.rgb(38, 166, 154)     # 源碼 i_bull #26a69a
    C_BEAR = Color.rgb(239, 83, 80)      # 源碼 i_bear #ef5350

    _o = open().values
    _h = high().values
    _l = low().values
    _c = close().values
    R = compute_v4(_o, _h, _l, _c, P_ATR, P_FACTOR, P_ER, P_CONFIRM, P_VOLSMA, P_EREMA, P_ROC)
    N = R["n"]

    # na 表示法(暖機期)
    def _na():
        return float("nan") if NA_AS == "nan" else None

    # 繪圖用 list:數值層同計算層恆等,只係把 None 換成平台可接受嘅 na
    st_plot = [R["st"][i] if R["st"][i] is not None else _na() for i in range(N)]
    bull_seq_src = [bool(R["bull"][i]) for i in range(N)]
    up_seq = [bool(R["flipUp"][i]) for i in range(N)]
    dn_seq = [bool(R["flipDown"][i]) for i in range(N)]
    tc_plot = [C_BULL if R["bull"][i] else C_BEAR for i in range(N)]

    lbl_txt = [""] * N
    for i in range(N):
        if R["flipUp"][i]:
            lbl_txt[i] = W["lbl_long"] + "  [" + R["qGrade"][i] + W["grade_suf"] + "]\n" + _fmt_tick(_c[i], P_TICK)
        elif R["flipDown"][i]:
            lbl_txt[i] = W["lbl_short"] + "  [" + R["qGrade"][i] + W["grade_suf"] + "]\n" + _fmt_tick(_c[i], P_TICK)

    # 綁定層:Sequence.apply 逐棒吐返計算好嘅值(plot 一定收 Sequence;避開「plot 收唔收 list」未證位)
    _dist = [abs(_c[i] - R["st"][i]) / _c[i] * 100.0 if (_c[i] and R["st"][i] is not None) else 0.0
             for i in range(N)]
    _CACHE = {"st": st_plot, "lbl": lbl_txt, "bull": bull_seq_src, "up": up_seq, "dn": dn_seq,
              "tc": tc_plot, "close": list(_c),
              "convPct": [int(_round_half_away(R["conv"][i] * 100.0)) for i in range(N)],
              "age": [int(R["age"][i]) for i in range(N)],
              "erSmooth": [float(R["erSmooth"][i]) for i in range(N)],
              "volRatio": [float(R["volRatio"][i]) for i in range(N)],
              "adFactor": [float(R["adFactor"][i]) for i in range(N)],
              "adConfirm": [int(R["adConfirm"][i]) for i in range(N)],
              "flipQ": [int(R["flipQ"][i]) for i in range(N)],
              "dist": _dist,
              "bullCt": [int(R["bullCt"][i]) for i in range(N)],
              "bearCt": [int(R["bearCt"][i]) for i in range(N)],
              "mirror": list(_c)}
    _IDX = {}

    def _series(key):
        if not USE_APPLY_BINDING:
            return _CACHE[key]
        _IDX[key] = [0]

        def _emit(_x):
            j = _IDX[key][0]
            lst = _CACHE[key]
            if j >= len(lst):
                j = len(lst) - 1        # 防越界(apply 呼叫次數異常時唔好爆)
            _IDX[key][0] += 1
            return lst[j]
        return close().apply(_emit)

    s_st = _series("st")
    s_close = _series("close")
    s_bull = _series("bull")
    s_up = _series("up")
    s_dn = _series("dn")
    s_tc = _series("tc")
    s_lbl = _series("lbl")
    s_mirror = _series("mirror")

    # ── 光暈三層(源碼 linewidth 12/7/4,透明度 90/82/68;FTNN linewidth 上限 9 ⇒ 12→9)
    if P_GLOW:
        plot(W["glow1"], s_st, color=iff(s_bull, Color.rgb(38, 166, 154, 26), Color.rgb(239, 83, 80, 26)), style=Line.line, linewidth=9)
        plot(W["glow2"], s_st, color=iff(s_bull, Color.rgb(38, 166, 154, 46), Color.rgb(239, 83, 80, 46)), style=Line.line, linewidth=7)
        plot(W["glow3"], s_st, color=iff(s_bull, Color.rgb(38, 166, 154, 82), Color.rgb(239, 83, 80, 82)), style=Line.line, linewidth=4)
    # ── 主線(源碼 plot(st, "超級趨勢線", tc, linewidth=2))
    plot(W["line"], s_st, color=s_tc, style=Line.line, linewidth=2)
    # ── 漸層底色(源碼 fill() 雙色漸層;FTNN plot_fillcolor 只單色 ⇒ 視覺差異,數值/位置不變)
    if P_SHADE:
        plot_fillcolor(W["fill"], s_close, s_st, True, color=iff(s_bull, Color.rgb(38, 166, 154, 200), Color.rgb(239, 83, 80, 200)))
    # ── 反轉標籤(源碼 label.new(bar_index, st, yloc=below/abovebar, style=label_up/down))
    if P_LABELS:
        plot_text(W["lbl_long"], s_up, s_st, s_lbl, color=Color.rgb(255, 255, 255), size=1, offseth=0, offsetv=-5)
        plot_text(W["lbl_short"], s_dn, s_st, s_lbl, color=Color.rgb(255, 255, 255), size=1, offseth=0, offsetv=5)
        plot_icon("訊號圖示", s_up, s_st, Shape.labelup, color=C_BULL, size=1, offseth=0, offsetv=-5)
        plot_icon("訊號圖示", s_dn, s_st, Shape.labeldown, color=C_BEAR, size=1, offseth=0, offsetv=5)

    # ── 數據看板:源碼 table.new(2×11);FTNN 手冊全文無 table/看板/panel 原語
    #    ⇒ 以 output_parameter 出 11 個看板數值(文字層差異逐項見交付報告)
    output_parameter(
        方向好倉為1=iff(s_bull, 1, 0),
        持續陰陽燭數=_series("age"),
        趨勢信念百分比=_series("convPct"),
        趨勢效率=_series("erSmooth"),
        波幅比率=_series("volRatio"),
        動態乘數=_series("adFactor"),
        確認閘=_series("adConfirm"),
        最近訊號質素=_series("flipQ"),
        偏離趨勢線百分比=_series("dist"),
        好倉翻轉數=_series("bullCt"),
        沽空翻轉數=_series("bearCt"),
        綁定對齊自檢=s_close - s_mirror,
    )

九、FTNN 交付件全文(源碼輸出相同版)

# -*- coding: utf-8 -*-
# V4 超級趨勢 (自適應版) —— Futu FTNN 自編指標 (Python 模式) 對應版 + 香港中文字眼
# 源碼:v4-supertrend-zh-v6.txt (16,808 B, sha256 4d05ef4c07db6457…) Pine v6 255 行
# 方法:主持 66206 —— 原生 list/scalar 自管上根值,oldest→newest 單次 for-loop,唔經 Sequence 寫回
# 合規:零 import(除富途自家模組);無 math/collections/typing/dataclasses/__future__
# 對數:A36 黃金 fixture 3fc8ce27(300 棒 HSImain 1m)14 checkpoints+latest+2 labels 全 0 diff
indicator("V4STSRC", "V4 超級趨勢 (自適應版) 源碼字眼版", True, "自適應 ATR 乘數+ER 確認閘+訊號質素評分;對 A36 300 棒 fixture 0 diff")

USE_HK_WORDING = False     # 源碼原文字眼版(數值層同 HK 版恆等;差嘅只係字串)
USE_APPLY_BINDING = True   # True=經 Sequence.apply 出 Sequence(plot 一定收);False=直接交 list(未驗)
NA_AS = "nan"              # 暖機期 na 表示法:"nan"=float("nan");"none"=None(視乎真機接邊個)

W_SRC = {"long": "做多", "short": "做空", "grade_suf": "", "er_hi": "趨勢明顯", "er_mid": "多空交戰",
         "er_lo": "震盪洗盤", "vol_hi": "波動劇烈", "vol_lo": "波動壓縮", "vol_ok": "正常",
         "line": "超級趨勢線", "glow1": "外圍光暈", "glow2": "中間光暈", "glow3": "內部光暈",
         "fill": "漸層背景", "lbl_long": "做多", "lbl_short": "做空"}
W_HK = {"long": "好倉", "short": "沽空", "grade_suf": "級", "er_hi": "趨勢明確", "er_mid": "多空拉鋸",
        "er_lo": "上落洗盤", "vol_hi": "波幅劇烈", "vol_lo": "波幅壓縮", "vol_ok": "正常",
        "line": "超級趨勢線", "glow1": "外圍光暈", "glow2": "中層光暈", "glow3": "內層光暈",
        "fill": "漸層底色", "lbl_long": "好倉", "lbl_short": "沽空"}


def _round_half_away(x):
    # Pine math.round:四捨五入,tie 遠離零(唔用 Python round 的 banker's rounding)
    f = int(x)
    d = x - f
    if d >= 0.5:
        return f + 1
    if d < -0.5:
        return f - 1
    return f


def _fmt_tick(x, mintick):
    # 源碼 str.tostring(close, format.mintick) 對應:先對齊 tick,再按 mintick 小數位格式化
    n = _round_half_away(x / mintick) * mintick
    txt = repr(float(mintick))
    dec = 0
    if "." in txt:
        dec = len(txt.split(".")[1].rstrip("0"))
    return ("%%.%df" % dec) % n


def compute_v4(op, hi, lo, cl, atr_len, base_factor, er_len, confirm_bars,
               vol_sma_len, er_ema_len, roc_len):
    """純算術核心:逐棒 oldest→newest,scalar 狀態自管上根值。回傳 dict of lists。
    na 一律用 None;所有 na 比較照抄 Pine(結果 False),唔加防禦式 isnan(A36 L200 教訓)。"""
    n = len(cl)
    tr = [None] * n
    atr = [None] * n
    er = [0.0] * n
    er_s = [None] * n
    atr_base = [None] * n
    vol_ratio = [None] * n
    vol_regime = [None] * n
    ad_factor = [None] * n
    ad_confirm = [None] * n
    roc = [None] * n
    q_pct = [None] * n
    q_grade = [None] * n
    up_basic = [None] * n
    lo_basic = [None] * n
    up_band = [None] * n
    lo_band = [None] * n
    trend_dir = [None] * n
    st = [None] * n
    bull = [None] * n
    locked = [None] * n
    streak = [None] * n
    flip_up = [None] * n
    flip_dn = [None] * n
    any_flip = [None] * n
    age = [None] * n
    conv = [None] * n
    flip_q = [None] * n
    flip_g = [None] * n
    has_flip = [None] * n
    bull_ct = [None] * n
    bear_ct = [None] * n

    # ── 1. 真實波幅 TR 同 ATR(Pine ta.atr=ta.rma(tr,len),頭 len 棒用 SMA 做種子,之前係 na)
    for i in range(n):
        if i == 0:
            tr[i] = hi[i] - lo[i]
        else:
            tr[i] = max(hi[i], cl[i - 1]) - min(lo[i], cl[i - 1])
    for i in range(n):
        if i < atr_len - 1:
            atr[i] = None
        elif i == atr_len - 1:
            acc = 0.0
            for k in range(atr_len):
                acc += tr[k]
            atr[i] = acc / atr_len
        else:
            atr[i] = (atr[i - 1] * (atr_len - 1) + tr[i]) / atr_len

    # ── 2. 考夫曼效率係數 ER(棒 0..er_len-1:total_path 係 na ⇒ 走 false 分支 ⇒ er=0.0,唔係 na)
    for i in range(n):
        if i < er_len:
            er[i] = 0.0
        else:
            net = abs(cl[i] - cl[i - er_len])
            tot = 0.0
            for k in range(er_len):
                tot += abs(cl[i - k] - cl[i - k - 1])
            er[i] = net / tot if tot > 0 else 0.0

    # ── 3. ER 平滑(Pine ta.ema(er,3):alpha=2/(len+1),棒 0 種子=er[0])
    alpha = 2.0 / (er_ema_len + 1)
    for i in range(n):
        if i == 0:
            er_s[i] = er[i]
        else:
            er_s[i] = alpha * er[i] + (1.0 - alpha) * er_s[i - 1]

    # ── 4. 波動率體制(atr_baseline=ta.sma(atr,50);窗口有任何 na 就係 na ⇒ 暖機期 vol_ratio=1.0)
    for i in range(n):
        if i >= vol_sma_len - 1:
            acc = 0.0
            ok = True
            for k in range(i - vol_sma_len + 1, i + 1):
                if atr[k] is None:
                    ok = False
                    break
                acc += atr[k]
            atr_base[i] = acc / vol_sma_len if ok else None
        if atr_base[i] is not None and atr_base[i] > 0:
            vol_ratio[i] = atr[i] / atr_base[i]
        else:
            vol_ratio[i] = 1.0
        vol_regime[i] = max(min(vol_ratio[i], 1.40), 0.75)
        ad_factor[i] = base_factor * vol_regime[i]
        e = er_s[i]
        if e < 0.25:
            ad_confirm[i] = max(confirm_bars + 2, 4)
        elif e < 0.45:
            ad_confirm[i] = confirm_bars + 1
        elif e < 0.65:
            ad_confirm[i] = confirm_bars
        else:
            ad_confirm[i] = max(confirm_bars - 1, 1)

    # ── 5. 訊號質素評分(50% ER+30% 波動正常度+20% 5 棒動能)
    for i in range(n):
        if i >= roc_len:
            roc[i] = (cl[i] / cl[i - roc_len] - 1.0) * 100.0
        pmp = abs(roc[i]) if roc[i] is not None else None
        if cl[i] > 0 and atr[i] is not None:
            atr_pct = atr[i] / cl[i] * 100.0
        else:
            atr_pct = None
        if atr_pct is not None and atr_pct > 0 and pmp is not None:
            mom = min(pmp / (atr_pct * 2.0), 1.0)
        else:
            mom = 0.0
        vol_score = max(1.0 - abs(1.0 - vol_ratio[i]), 0.0)
        raw = er_s[i] * 0.50 + vol_score * 0.30 + mom * 0.20
        q_pct[i] = _round_half_away(raw * 100.0)
        if q_pct[i] >= 70:
            q_grade[i] = "A"
        elif q_pct[i] >= 50:
            q_grade[i] = "B"
        else:
            q_grade[i] = "C"

    # ── 6. 超級趨勢遞迴(upper_band[1]/lower_band[1]/trend_dir[1] 全部 scalar 上根值)
    for i in range(n):
        hl2 = (hi[i] + lo[i]) / 2.0
        if atr[i] is None:
            up_basic[i] = None
            lo_basic[i] = None
        else:
            up_basic[i] = hl2 + ad_factor[i] * atr[i]
            lo_basic[i] = hl2 - ad_factor[i] * atr[i]
        if i == 0 or up_band[i - 1] is None:
            up_band[i] = up_basic[i]
        elif up_basic[i] < up_band[i - 1] or cl[i - 1] > up_band[i - 1]:
            up_band[i] = up_basic[i]
        else:
            up_band[i] = up_band[i - 1]
        if i == 0 or lo_band[i - 1] is None:
            lo_band[i] = lo_basic[i]
        elif lo_basic[i] > lo_band[i - 1] or cl[i - 1] < lo_band[i - 1]:
            lo_band[i] = lo_basic[i]
        else:
            lo_band[i] = lo_band[i - 1]
        # trend_dir:只有棒 0 因 na(trend_dir[1]) 被強制 1;棒 13 起必評 close vs band(唔准加 isnan 防禦)
        if i == 0:
            trend_dir[i] = 1
        elif trend_dir[i - 1] == 1:
            trend_dir[i] = -1 if (lo_band[i] is not None and cl[i] < lo_band[i]) else 1
        else:
            trend_dir[i] = 1 if (up_band[i] is not None and cl[i] > up_band[i]) else -1
        st[i] = lo_band[i] if trend_dir[i] == 1 else up_band[i]
        bull[i] = (trend_dir[i] == 1)

    # ── 7. 確認閘+趨勢信念+計數器(locked_bull 棒 0 種子=bull[0];age 棒 0=1)
    lk = bull[0]
    sk = 0
    ag = 0
    bc = 0
    sc = 0
    hf = False
    fq = 0
    for i in range(n):
        sk = 0 if bull[i] == lk else sk + 1
        streak[i] = sk
        flip_up[i] = (sk >= ad_confirm[i]) and bull[i]
        flip_dn[i] = (sk >= ad_confirm[i]) and (not bull[i])
        any_flip[i] = flip_up[i] or flip_dn[i]
        if any_flip[i]:
            lk = bull[i]
            fq = q_pct[i]
            hf = True
            if flip_up[i]:
                bc += 1
            if flip_dn[i]:
                sc += 1
        locked[i] = lk
        flip_q[i] = fq
        has_flip[i] = hf
        bull_ct[i] = bc
        bear_ct[i] = sc
        if fq >= 70:
            flip_g[i] = "A"
        elif fq >= 50:
            flip_g[i] = "B"
        else:
            flip_g[i] = "C"
        ag = 0 if any_flip[i] else ag + 1
        age[i] = ag
        s_time = min(ag / 60.0, 1.0)
        conv[i] = s_time * 0.65 + er_s[i] * 0.35

    return {"n": n, "tr": tr, "atr": atr, "er": er, "erSmooth": er_s, "atrBase": atr_base,
            "volRatio": vol_ratio, "volRegime": vol_regime, "adFactor": ad_factor,
            "adConfirm": ad_confirm, "roc": roc, "qPct": q_pct, "qGrade": q_grade,
            "upBasic": up_basic, "loBasic": lo_basic, "upBand": up_band, "loBand": lo_band,
            "dir": trend_dir, "st": st, "bull": bull, "locked": locked, "streak": streak,
            "flipUp": flip_up, "flipDown": flip_dn, "anyFlip": any_flip, "age": age,
            "conv": conv, "flipQ": flip_q, "flipG": flip_g, "hasFlip": has_flip,
            "bullCt": bull_ct, "bearCt": bear_ct}


if __name__ == "__main__":
    from ftool import iff

    P_ATR = input_parameter("ATR 週期", 14)
    P_FACTOR = input_parameter("基礎倍數", 3.5)
    P_ER = input_parameter("ER 週期", 10)
    P_CONFIRM = input_parameter("確認陰陽燭數 (基礎)", 2)
    P_VOLSMA = input_parameter("波動基準週期", 50)
    P_EREMA = input_parameter("ER 平滑週期", 3)
    P_ROC = input_parameter("動能週期", 5)
    P_TICK = input_parameter("最小報價單位", 1)
    P_LABELS = input_parameter("多空訊號標籤", True)
    P_GLOW = input_parameter("發光光暈", True)
    P_SHADE = input_parameter("漸層底色", True)

    W = W_HK if USE_HK_WORDING else W_SRC
    C_BULL = Color.rgb(38, 166, 154)     # 源碼 i_bull #26a69a
    C_BEAR = Color.rgb(239, 83, 80)      # 源碼 i_bear #ef5350

    _o = open().values
    _h = high().values
    _l = low().values
    _c = close().values
    R = compute_v4(_o, _h, _l, _c, P_ATR, P_FACTOR, P_ER, P_CONFIRM, P_VOLSMA, P_EREMA, P_ROC)
    N = R["n"]

    # na 表示法(暖機期)
    def _na():
        return float("nan") if NA_AS == "nan" else None

    # 繪圖用 list:數值層同計算層恆等,只係把 None 換成平台可接受嘅 na
    st_plot = [R["st"][i] if R["st"][i] is not None else _na() for i in range(N)]
    bull_seq_src = [bool(R["bull"][i]) for i in range(N)]
    up_seq = [bool(R["flipUp"][i]) for i in range(N)]
    dn_seq = [bool(R["flipDown"][i]) for i in range(N)]
    tc_plot = [C_BULL if R["bull"][i] else C_BEAR for i in range(N)]

    lbl_txt = [""] * N
    for i in range(N):
        if R["flipUp"][i]:
            lbl_txt[i] = W["lbl_long"] + "  [" + R["qGrade"][i] + W["grade_suf"] + "]\n" + _fmt_tick(_c[i], P_TICK)
        elif R["flipDown"][i]:
            lbl_txt[i] = W["lbl_short"] + "  [" + R["qGrade"][i] + W["grade_suf"] + "]\n" + _fmt_tick(_c[i], P_TICK)

    # 綁定層:Sequence.apply 逐棒吐返計算好嘅值(plot 一定收 Sequence;避開「plot 收唔收 list」未證位)
    _dist = [abs(_c[i] - R["st"][i]) / _c[i] * 100.0 if (_c[i] and R["st"][i] is not None) else 0.0
             for i in range(N)]
    _CACHE = {"st": st_plot, "lbl": lbl_txt, "bull": bull_seq_src, "up": up_seq, "dn": dn_seq,
              "tc": tc_plot, "close": list(_c),
              "convPct": [int(_round_half_away(R["conv"][i] * 100.0)) for i in range(N)],
              "age": [int(R["age"][i]) for i in range(N)],
              "erSmooth": [float(R["erSmooth"][i]) for i in range(N)],
              "volRatio": [float(R["volRatio"][i]) for i in range(N)],
              "adFactor": [float(R["adFactor"][i]) for i in range(N)],
              "adConfirm": [int(R["adConfirm"][i]) for i in range(N)],
              "flipQ": [int(R["flipQ"][i]) for i in range(N)],
              "dist": _dist,
              "bullCt": [int(R["bullCt"][i]) for i in range(N)],
              "bearCt": [int(R["bearCt"][i]) for i in range(N)],
              "mirror": list(_c)}
    _IDX = {}

    def _series(key):
        if not USE_APPLY_BINDING:
            return _CACHE[key]
        _IDX[key] = [0]

        def _emit(_x):
            j = _IDX[key][0]
            lst = _CACHE[key]
            if j >= len(lst):
                j = len(lst) - 1        # 防越界(apply 呼叫次數異常時唔好爆)
            _IDX[key][0] += 1
            return lst[j]
        return close().apply(_emit)

    s_st = _series("st")
    s_close = _series("close")
    s_bull = _series("bull")
    s_up = _series("up")
    s_dn = _series("dn")
    s_tc = _series("tc")
    s_lbl = _series("lbl")
    s_mirror = _series("mirror")

    # ── 光暈三層(源碼 linewidth 12/7/4,透明度 90/82/68;FTNN linewidth 上限 9 ⇒ 12→9)
    if P_GLOW:
        plot(W["glow1"], s_st, color=iff(s_bull, Color.rgb(38, 166, 154, 26), Color.rgb(239, 83, 80, 26)), style=Line.line, linewidth=9)
        plot(W["glow2"], s_st, color=iff(s_bull, Color.rgb(38, 166, 154, 46), Color.rgb(239, 83, 80, 46)), style=Line.line, linewidth=7)
        plot(W["glow3"], s_st, color=iff(s_bull, Color.rgb(38, 166, 154, 82), Color.rgb(239, 83, 80, 82)), style=Line.line, linewidth=4)
    # ── 主線(源碼 plot(st, "超級趨勢線", tc, linewidth=2))
    plot(W["line"], s_st, color=s_tc, style=Line.line, linewidth=2)
    # ── 漸層底色(源碼 fill() 雙色漸層;FTNN plot_fillcolor 只單色 ⇒ 視覺差異,數值/位置不變)
    if P_SHADE:
        plot_fillcolor(W["fill"], s_close, s_st, True, color=iff(s_bull, Color.rgb(38, 166, 154, 200), Color.rgb(239, 83, 80, 200)))
    # ── 反轉標籤(源碼 label.new(bar_index, st, yloc=below/abovebar, style=label_up/down))
    if P_LABELS:
        plot_text(W["lbl_long"], s_up, s_st, s_lbl, color=Color.rgb(255, 255, 255), size=1, offseth=0, offsetv=-5)
        plot_text(W["lbl_short"], s_dn, s_st, s_lbl, color=Color.rgb(255, 255, 255), size=1, offseth=0, offsetv=5)
        plot_icon("訊號圖示", s_up, s_st, Shape.labelup, color=C_BULL, size=1, offseth=0, offsetv=-5)
        plot_icon("訊號圖示", s_dn, s_st, Shape.labeldown, color=C_BEAR, size=1, offseth=0, offsetv=5)

    # ── 數據看板:源碼 table.new(2×11);FTNN 手冊全文無 table/看板/panel 原語
    #    ⇒ 以 output_parameter 出 11 個看板數值(文字層差異逐項見交付報告)
    output_parameter(
        方向好倉為1=iff(s_bull, 1, 0),
        持續陰陽燭數=_series("age"),
        趨勢信念百分比=_series("convPct"),
        趨勢效率=_series("erSmooth"),
        波幅比率=_series("volRatio"),
        動態乘數=_series("adFactor"),
        確認閘=_series("adConfirm"),
        最近訊號質素=_series("flipQ"),
        偏離趨勢線百分比=_series("dist"),
        好倉翻轉數=_series("bullCt"),
        沽空翻轉數=_series("bearCt"),
        綁定對齊自檢=s_close - s_mirror,
    )

十、對數 harness 全文

# -*- coding: utf-8 -*-
"""Stub-runtime harness:exec 交付件 v4_futu_ftnn_hk.py 本身,對 A36 黃金 fixture 3fc8ce27 逐欄比對。
唔改寫交付件一個字;stub 只模擬富途運行時 API(fbasic.Sequence/fplot/ftool.iff/plot*/input_parameter)。"""
import json, re, sys, types

SRC = "v4_futu_ftnn_hk.py"
FIX = "a36_fixture.json"

class Vec:
    def __init__(self, v): self.v = list(v)
    @property
    def values(self): return self.v
    @property
    def size(self): return len(self.v)
    def apply(self, f): return Vec([f(x) for x in self.v])
    def ref(self, k): return Vec([None]*k + self.v[:len(self.v)-k] if k else self.v)
    def __sub__(self, o):
        ov = o.v if isinstance(o, Vec) else o
        return Vec([a-b for a, b in zip(self.v, ov)])
    def __len__(self): return len(self.v)
    def __iter__(self): return iter(self.v)
    def __getitem__(self, i): return self.v[i]
    def __repr__(self): return "Vec(%d)" % len(self.v)

PLOTS = []; OUTPUTS = {}; INPUTS = []

def _rec(kind):
    def f(*a, **k):
        PLOTS.append({"kind": kind, "args": a, "kwargs": k})
        return Vec([0]*1) if kind == "plot" else None
    return f

def _iff(cond, a, b):
    cv = cond.v if isinstance(cond, Vec) else cond
    av = a.v if isinstance(a, Vec) else [a]*len(cv)
    bv = b.v if isinstance(b, Vec) else [b]*len(cv)
    return Vec([av[i] if cv[i] else bv[i] for i in range(len(cv))])

def _input_parameter(title, default):
    INPUTS.append((title, default)); return default

def _output_parameter(**kw): OUTPUTS.update(kw)

class _Color:
    @staticmethod
    def rgb(r, g, b, a=255): return ("rgb", r, g, b, a)
    blue = ("named", "blue"); white = ("named", "white"); gray = ("named", "gray")
    red = ("named", "red"); green = ("named", "green")

class _Line:
    line = "line"; line_dashed = "line_dashed"; line_dotted = "line_dotted"
    histogram = "histogram"; histogram_line = "histogram_line"; circles = "circles"; cross = "cross"

class _Shape:
    labelup = "labelup"; labeldown = "labeldown"; arrowup = "arrowup"; arrowdown = "arrowdown"
    circle = "circle"; square = "square"; diamond = "diamond"; flag = "flag"
    triangleup = "triangleup"; triangledown = "triangledown"; cross = "cross"; xcross = "xcross"

def main():
    fx = json.load(open(FIX))
    bars = fx["input_bars_ts_o_h_l_c_v"]
    o = [b[1] for b in bars]; h = [b[2] for b in bars]; l = [b[3] for b in bars]; c = [b[4] for b in bars]

    ftool = types.ModuleType("ftool"); ftool.iff = _iff
    fta = types.ModuleType("fta"); fmath = types.ModuleType("fmath"); fdt = types.ModuleType("fdatetime")
    ns = {"__name__": "__main__", "__builtins__": __builtins__,
          "indicator": lambda *a, **k: None, "input_parameter": _input_parameter,
          "output_parameter": _output_parameter, "plot": _rec("plot"),
          "plot_text": _rec("plot_text"), "plot_icon": _rec("plot_icon"),
          "plot_fillcolor": _rec("plot_fillcolor"), "plot_candlestick": _rec("plot_candlestick"),
          "plot_hline": _rec("plot_hline"), "plot_stickline": _rec("plot_stickline"),
          "Color": _Color, "Line": _Line, "Shape": _Shape,
          "open": lambda: Vec(o), "high": lambda: Vec(h), "low": lambda: Vec(l), "close": lambda: Vec(c)}
    sys.modules["ftool"] = ftool; sys.modules["fta"] = fta
    sys.modules["fmath"] = fmath; sys.modules["fdatetime"] = fdt
    code = open(SRC, encoding="utf-8").read()
    exec(compile(code, SRC, "exec"), ns)

    R = ns["R"]; N = R["n"]
    print("exec OK;bars =", N, ";inputs =", len(INPUTS), ";plot calls =", len(PLOTS), ";outputs =", len(OUTPUTS))

    tol = 1e-9
    def close_enough(g, e):
        if isinstance(e, bool) or isinstance(g, bool): return g == e
        if isinstance(e, (int, float)) and isinstance(g, (int, float)):
            return abs(g - e) <= tol * max(1.0, abs(e))
        return g == e

    bad = []; tot = 0
    keymap = {"st": "st", "erSmooth": "erSmooth", "volRatio": "volRatio",
              "adaptiveFactor": "adFactor", "adaptiveConfirm": "adConfirm",
              "lockedBull": "locked", "qualityPct": "qPct", "qualityGrade": "qGrade", "s": "conv"}
    for cp in fx["expected_checkpoints"]:
        i = cp["index"]
        for ek, gk in keymap.items():
            tot += 1
            if not close_enough(R[gk][i], cp[ek]):
                bad.append(("checkpoint", i, ek, cp[ek], R[gk][i]))
    # latest 20 欄
    L = R["n"] - 1
    got_latest = {"direction": "LONG" if R["bull"][L] else "SHORT", "st": R["st"][L], "close": c[L],
                  "age": R["age"][L], "convictionPct": ns["_round_half_away"](R["conv"][L]*100.0),
                  "erSmooth": R["erSmooth"][L], "volRatio": R["volRatio"][L],
                  "adaptiveFactor": R["adFactor"][L], "adaptiveConfirm": R["adConfirm"][L],
                  "hasFlipped": R["hasFlip"][L], "flipQuality": R["flipQ"][L],
                  "distancePct": abs(c[L]-R["st"][L])/c[L]*100.0, "bullFlips": R["bullCt"][L],
                  "bearFlips": R["bearCt"][L], "flipUp": R["flipUp"][L], "flipDown": R["flipDown"][L],
                  "anyFlip": R["anyFlip"][L]}
    got_latest["erState"] = "TRENDING" if R["erSmooth"][L] > 0.65 else "MIXED" if R["erSmooth"][L] > 0.40 else "CHOPPY"
    got_latest["volState"] = "HIGH" if R["volRatio"][L] > 1.20 else "LOW" if R["volRatio"][L] < 0.80 else "NORMAL"
    got_latest["flipGrade"] = R["flipG"][L]
    zh = {"directionZh": {"LONG": "做多", "SHORT": "做空"}[got_latest["direction"]],
          "erStateZh": {"TRENDING": "順勢趨勢", "MIXED": "多空交戰", "CHOPPY": "震盪洗盤"}[got_latest["erState"]],
          "volStateZh": {"HIGH": "波動劇烈", "LOW": "波動壓縮", "NORMAL": "波動正常"}[got_latest["volState"]]}
    for k, exp in fx["expected_latest"].items():
        tot += 1
        g = zh[k] if k in zh else got_latest.get(k, "MISSING")
        if not close_enough(g, exp): bad.append(("latest", k, exp, g))
    # labels
    gl = []
    for i in range(N):
        if R["flipUp"][i]:
            gl.append({"barIndex": i, "direction": "LONG", "quality": R["qPct"][i], "grade": R["qGrade"][i],
                       "y": R["st"][i], "close": c[i], "yloc": "belowbar", "style": "label_up"})
        if R["flipDown"][i]:
            gl.append({"barIndex": i, "direction": "SHORT", "quality": R["qPct"][i], "grade": R["qGrade"][i],
                       "y": R["st"][i], "close": c[i], "yloc": "abovebar", "style": "label_down"})
    el = fx["expected_labels"]
    tot += len(el) * 7
    if len(gl) != len(el): bad.append(("labels", "count", len(el), len(gl)))
    for a, b in zip(gl, el):
        for k in ("barIndex", "direction", "quality", "grade", "y", "close", "yloc"):
            if not close_enough(a[k], b[k]): bad.append(("label", b["barIndex"], k, b[k], a[k]))
    # 繪圖層:主線序列 == st(暖機 nan);標籤文字棒位
    main = [p for p in PLOTS if p["kind"] == "plot" and p["args"][0] == ns["W"]["line"]]
    if not main: bad.append(("plot", "main line missing", "", ""))
    else:
        mv = main[0]["args"][1]
        mv = mv.v if isinstance(mv, Vec) else mv
        for i in range(N):
            tot += 1
            exp = R["st"][i]
            got = mv[i]
            if exp is None:
                ok = (got != got) or (got is None)     # nan 或 None
            else:
                ok = close_enough(got, exp)
            if not ok: bad.append(("plot_st", i, exp, got))
    # 綁定對齊自檢必須全 0
    al = OUTPUTS.get("綁定對齊自檢")
    if al is None: bad.append(("output", "對齊自檢 missing", "", ""))
    else:
        av = al.v if isinstance(al, Vec) else al
        tot += 1
        if any(x != 0 for x in av): bad.append(("alignment", "nonzero", 0, sum(1 for x in av if x != 0)))
    # 合規掃描(AST 精確:只睇真碼,唔受註解/docstring 字樣影響)
    import ast
    tree = ast.parse(code)
    allowed = {"ftool", "fta", "fmath", "fdatetime", "fbasic", "fplot", "ffinance", "fquote", "findicator"}
    imports = []
    for nd in ast.walk(tree):
        if isinstance(nd, ast.Import):
            imports += [a.name.split(".")[0] for a in nd.names]
        elif isinstance(nd, ast.ImportFrom):
            imports.append((nd.module or "").split(".")[0])
    tot += 1
    badimp = [m for m in imports if m not in allowed]
    if badimp: bad.append(("compliance", "forbidden import", "", badimp))
    tot += 1
    if not imports or set(imports) - allowed: pass
    forbidden_names = {"math", "isnan", "isinf", "collections", "typing", "dataclasses"}
    used = set()
    for nd in ast.walk(tree):
        if isinstance(nd, ast.Name) and nd.id in forbidden_names: used.add(nd.id)
        if isinstance(nd, ast.Attribute) and isinstance(nd.value, ast.Name) and nd.value.id in forbidden_names:
            used.add(nd.value.id + "." + nd.attr)
    tot += 1
    if used: bad.append(("compliance", "forbidden name usage", "", sorted(used)))
    tot += 1
    calls = sorted({nd.func.id for nd in ast.walk(tree)
                    if isinstance(nd, ast.Call) and isinstance(nd.func, ast.Name)
                    and nd.func.id in {"floor", "ceil", "isnan", "sqrt", "pow"}})
    if calls: bad.append(("compliance", "manual-outside math calls", "", calls))
    tot += 1
    imports_ok = sorted(set(imports))
    print("imports:", imports_ok, "|plot calls:", len(PLOTS), "|output_parameter:", len(OUTPUTS))

    print("逐欄比對:total =", tot, "|mismatch =", len(bad))
    for b in bad[:40]: print("  MISMATCH", b)
    print("RESULT:", "PASS (0 diff)" if not bad else "FAIL")
    print("labels:", [(x["barIndex"], x["direction"], x["quality"], x["grade"]) for x in gl])
    print("label text samples:", [p["args"][3].v[158] if isinstance(p["args"][3], Vec) else p["args"][3]
                                  for p in PLOTS if p["kind"] == "plot_text"][:1])
    return 0 if not bad else 1

sys.exit(main())
本件自足:無外部 CSS/JS/圖片。sha256(本 HTML)=6a0e7b93dace255a…(以最終檔為準)。 席位 A22/A225764|Relay 短帖見議會 66155 回覆|所有私檔 0600、工作目錄 0700。