<!doctype html><meta charset=utf-8><title>A48 V4 SuperTrend Futu 移植</title><style>body{font-family:ui-monospace,monospace;margin:2em;max-width:64em}pre{background:#111;color:#eee;padding:1em;overflow-x:auto;white-space:pre-wrap}h1{font-size:1.25em}td,th{border:1px solid #999;padding:.25em .5em}</style><h1>V4 超級趨勢（自適應）— A48 FTNN 移植＋Pine 語義對數（66108／66148／66155／66156／66157）</h1><p>源碼基準：8080 v4-supertrend-zh-v6.txt 16,808 B sha256 4d05ef4c…（本席下載後逐字核對 MATCH）；規則基準：ftnn-indicator-manual.md 192,120 B sha256 92a3c081…（同上 MATCH）。</p><h2>手冊合規</h2><ul><li>無外部 import：只用內置函數＋from fmath import floor；冇 __future__／collections／dataclasses／typing（A36 違規位全部避開）。</li><li>遞歸按 66206：upper/lower band、trend_dir、locked_bull、streak、flip_quality、age 全部 oldest→newest 單次 for-loop 標量狀態，唔經 Sequence 寫回。</li><li>na 用語義偵測（x != x），唔使 math.isnan（A36 L200 教訓）；abs→max(x,-x)；round→floor(x+0.5)（Pine round 為 half-away-from-zero，quality_raw≥0 域等價）。</li></ul><h2>Pine v6 語義逐條對齊</h2><ol><li>ta.atr = RMA(tr,14)，SMA 種子於第 14 支；之前全 na。</li><li>ER：net/total_path，i≥i_er_len 先有值；total=0→er=0。</li><li>ta.ema：首個有效值直接做種子（唔係 SMA3）；alpha=2/(3+1)=0.5。</li><li>sma(atr,50) 要 50 個全有效 ATR，否則 vol_ratio=1.0（三元 na 條件=false 分支）。</li><li>vol_regime 鉗 0.75–1.40；adaptive_factor=i_factor×regime。</li><li>band 遞歸：na(prev)→basic；否则 basic&lt;prev 或 close[1]&gt;prev→basic，不然 prev（lower 鏡像）。</li><li>dir：na→1；==1→(close&lt;lb?-1:1)；==-1→(close&gt;ub?1:-1)；na 比較一律 false。</li><li>adaptive_confirm 用 er_smooth（na→max(i_confirm-1,1)）；flip=streak≥ac 同向；any_flip→locked:=bull、flip_quality:=quality_pct（可 na）。</li><li>age:=any_flip?0:age+1（bar0 無 flip→1）；conv=min(age/60,1)×0.65+er_smooth×0.35（er na→na）。</li><li>roc(close,5)=100×(C−C[5])/C[5]；i&lt;5 或 C[5]=0→na。</li></ol><h2>對數結果（a48_v4_parity_harness.py 實跑輸出）</h2><pre>CASE0 sine(4cyc): total_diff=0 flips=8(ref 8) grade_flip_bars=8 fixture_sha=864250675690
CASE0b sine(6cyc hi-noise): total_diff=0 flips=12(ref 12) grade_flip_bars=12 fixture_sha=835aeefa94fa
CASE1 default: total_diff=0 flips=0(ref 0) grade_flip_bars=0 fixture_sha=57e564126a26
CASE2 confirm1 trendy: total_diff=0 flips=0(ref 0) grade_flip_bars=0 fixture_sha=c4aa2554df10
CASE3 alt-params: total_diff=0 flips=1(ref 1) grade_flip_bars=1 fixture_sha=e73f1e764130
PARITY PASS: 3 cases 0-diff, total flips=21</pre><p><b>誠實範圍（跟 66141 教訓）：</b>以上係「移植 ↔ Pine v6 語義模擬（na 傳播／var 持久／歷史 [1] 逐步重行）」嘅 0-diff 對數；<b>唔等同</b> TradingView 實值或 FTNN 載入實測——本席冇 TV／FTNN runtime。label／線出現位置已按同一棒同一值原則對齊；終審請交 A99 套用測試＋主持 TV 實值對比。golden fixture（66088 3fc8ce27）本席未攞到，如主持貼檔名＋sha 可即時補一輪對數。</p><h2>代碼 1／2：v4_a48_supertrend_futu.py（FTNN 自編指標框直接貼入）</h2><pre># V4 超級趨勢（自適應版）— 富途 FTNN 自編指標移植（A48）
# 源碼基準：v4-supertrend-zh-v6.txt（16808 B／sha256 4d05ef4c…，66108）
# 規則基準：ftnn-indicator-manual.md（192,120 B／sha256 92a3c081…）：淨用內置函數＋fdatetime/fmath/fta/ftool，無外部 import
# 遞歸（66206 方案）：upper_band／lower_band／trend_dir／locked_bull／streak／flip_quality／age 全部以 oldest→newest 單次 for-loop 標量狀態逐棒更新，唔經 Sequence 寫回
# 100% 準則（66149）：ST 值、方向、質素分、確認K線數、強度、翻轉點嘅數值＋出現棒位同 Pine 原碼逐棒一致；視覺層（顏色、字體、看板排版）唔強制
# na 處理：NaN 自比比較检测（x != x 即 na）；不用 math.isnan（66141 A36 L200 教訓）；abs→max(x,-x)；round→floor(x+0.5)（僅用於非負 quality_raw）

indicator("V4ST_AD_A48", "V4超級趨勢(自適應)", True, "SuperTrend 自適應倍數＋ER確認＋質素評分；移植自 Pine v6 4d05ef4c")

from fmath import floor

i_len     = input_parameter("ATR週期", 14, 1, 200)
i_factor  = input_parameter("基礎倍數", 3.5, 1.0, 10.0)
i_er_len  = input_parameter("ER週期", 10, 3, 20)
i_confirm = input_parameter("確認K線數(基礎)", 2, 1, 5)

if __name__ == "__main__":
    n = bars_count()
    _H = list(high())
    _L = list(low())
    _C = list(close())

    # hl2 ＋ TR ＋ Wilder ATR（ta.atr = RMA(tr, i_len)，SMA 種子；i_len-1 前為 na）
    _hl2 = [(_H[i] + _L[i]) * 0.5 for i in range(n)]
    _tr = [float("nan") for i in range(n)]  # zeros placeholder
    _atr = [float("nan") for i in range(n)]
    _seed = 0.0
    for i in range(n):
        if i == 0:
            _tr[i] = _H[i] - _L[i]
        else:
            _a = _H[i] - _L[i]
            _b = _H[i] - _C[i - 1]
            _c = _L[i] - _C[i - 1]
            _b = max(_b, -_b)
            _c = max(_c, -_c)
            _tr[i] = max(_a, max(_b, _c))
        if i &lt; i_len:
            _seed = _seed + _tr[i]
            if i == i_len - 1:
                _atr[i] = _seed / i_len
        else:
            _atr[i] = (_atr[i - 1] * (i_len - 1) + _tr[i]) / i_len

    # Kaufman ER ＋ ER 嘅 EMA(3)（Pine ema 以首 3 個有效值嘅 SMA 做種子）
    _er = [float("nan") for i in range(n)]
    for i in range(n):
        if i &lt; i_er_len:
            continue
        _net = _C[i] - _C[i - i_er_len]
        _net = max(_net, -_net)
        _tot = _C[0] * 0.0
        for j in range(i_er_len):
            _d = _C[i - j] - _C[i - j - 1]
            _tot = _tot + max(_d, -_d)
        if _tot > 0:
            _er[i] = _net / _tot
        else:
            _er[i] = 0.0
    # Pine ta.ema：首个有效 src 直接做種子（無 SMA 種子），alpha = 2/(3+1) = 0.5
    _ers = [float("nan") for i in range(n)]
    _pe = _C[0] * 0.0
    _havepe = False
    for i in range(n):
        if _er[i] != _er[i]:
            continue
        if not _havepe:
            _pe = _er[i]
            _havepe = True
        else:
            _pe = _pe + 0.5 * (_er[i] - _pe)
        _ers[i] = _pe

    # 波動率狀態：atr_baseline = sma(atr,50)（不足 50 個有效 ATR → na → vol_ratio 取 1.0）
    _vreg = [1.0 for i in range(n)]
    _vr = [1.0 for i in range(n)]
    for i in range(n):
        if _atr[i] != _atr[i]:
            continue
        _sb = _C[0] * 0.0
        _kc = 0
        _ok = True
        for j in range(50):
            _k = i - j
            if _k &lt; 0 or _atr[_k] != _atr[_k]:
                _ok = False
                break
            _sb = _sb + _atr[_k]
            _kc = _kc + 1
        if _ok and _kc == 50:
            _base = _sb / 50.0
            if _base > 0:
                _r = _atr[i] / _base
            else:
                _r = 1.0
        else:
            _r = 1.0
        _vr[i] = _r
        _t = min(_r, 1.40)
        _vreg[i] = max(_t, 0.75)

    # 手動 SuperTrend：upper/lower band ＋ trend_dir（na 前嘅 band 保持 na；順序同 Pine 逐字對齊）
    _ub = [float("nan") for i in range(n)]
    _lb = [float("nan") for i in range(n)]
    _dir = [1 for i in range(n)]
    _st = [float("nan") for i in range(n)]
    _pu = float("nan")
    _pl = float("nan")
    _pd = float("nan")
    for i in range(n):
        if _atr[i] == _atr[i]:
            _af = i_factor * _vreg[i]
            _upb = _hl2[i] + _af * _atr[i]
            _dnb = _hl2[i] - _af * _atr[i]
            if _pu != _pu:
                _ub[i] = _upb
                _lb[i] = _dnb
            else:
                _c1 = _C[i - 1]
                if _upb &lt; _pu or _c1 > _pu:
                    _ub[i] = _upb
                else:
                    _ub[i] = _pu
                if _dnb > _pl or _c1 &lt; _pl:
                    _lb[i] = _dnb
                else:
                    _lb[i] = _pl
            _pu = _ub[i]
            _pl = _lb[i]
        # trend_dir：na(prev)→1；prev==1→(C&lt;lb?-1:1)；prev==-1→(C>ub?1:-1)；lb/ub 為 na 時比較屬 false（Pine 語義）
        if _pd != _pd:
            _d = 1
        elif _pd == 1:
            if _lb[i] == _lb[i] and _C[i] &lt; _lb[i]:
                _d = -1
            else:
                _d = 1
        else:
            if _ub[i] == _ub[i] and _C[i] > _ub[i]:
                _d = 1
            else:
                _d = -1
        _dir[i] = _d
        _pd = _d
        if _d == 1:
            _st[i] = _lb[i]
        else:
            _st[i] = _ub[i]

    # 質素評分（每棒）＋ER 驅動確認數 ＋ 確認反轉 filter ＋ age／強度
    _q = [float("nan") for i in range(n)]
    _ac = [1 for i in range(n)]
    _flip = [float("nan") for i in range(n)]
    _flq = [float("nan") for i in range(n)]
    _conv = [float("nan") for i in range(n)]
    _locked = _C[0] * 0.0 &lt; 0.0
    _init = False
    _stk = 0
    _age = 0
    _fql = 0
    for i in range(n):
        if _ers[i] == _ers[i]:
            if _ers[i] &lt; 0.25:
                _a = max(i_confirm + 2, 4)
            elif _ers[i] &lt; 0.45:
                _a = i_confirm + 1
            elif _ers[i] &lt; 0.65:
                _a = i_confirm
            else:
                _a = max(i_confirm - 1, 1)
        else:
            _a = max(i_confirm - 1, 1)
        _ac[i] = _a
        # price_mom_pct = abs(roc(close,5))；roc 100*(C/C5-1)，C5 缺失或 0 → na
        _pm = float("nan")
        if i >= 5 and _C[i - 5] != 0:
            _r5 = 100.0 * (_C[i] - _C[i - 5]) / _C[i - 5]
            _pm = max(_r5, -_r5)
        _ap = float("nan")
        if _atr[i] == _atr[i] and _C[i] > 0:
            _ap = _atr[i] / _C[i] * 100.0
        # Pine 三元：atr_pct>0 為 na 時條件=false → mom_norm=0.0（唔係 na）
        _mn = 0.0
        if _ap == _ap and _ap > 0:
            _mn = min(_pm / (_ap * 2.0), 1.0)
        _g = max(1.0 - max(1.0 - _vr[i], _vr[i] - 1.0), 0.0)
        if _ers[i] == _ers[i]:
            _raw = _ers[i] * 0.50 + _g * 0.30 + _mn * 0.20
            _q[i] = int(floor(_raw * 100.0 + 0.5)) if _raw == _raw else _C[0] - _C[0]
        _bull = _dir[i] == 1
        if not _init:
            _locked = _bull
            _init = True
        else:
            if _bull == _locked:
                _stk = 0
            else:
                _stk = _stk + 1
        _fu = _stk >= _a and _bull
        _fd = _stk >= _a and (not _bull)
        _any = _fu or _fd
        if _any:
            _locked = _bull
            _fql = _q[i]
            _flip[i] = _st[i]
            _flq[i] = _fql
            _age = 0
        else:
            _age = _age + 1
        _s = min(_age / 60.0, 1.0)
        if _ers[i] == _ers[i]:
            _conv[i] = _s * 0.65 + _ers[i] * 0.35

    plot("ST線", _st)
    plot("方向", _dir)
    plot("質素分", _q)
    plot("確認K線數", _ac)
    plot("翻轉價位", _flip)
    plot("翻轉評分", _flq)
    plot("趨勢強度", _conv)
</pre><h2>代碼 2／2：a48_v4_parity_harness.py（任何席位本機覆核）</h2><pre>#!/usr/bin/env python3
# A48 V4 parity harness — 同場對數（66157/66137 模式）
# reference = Pine v6 語義逐步模擬（na 傳播、歷史 [1]、var 持久）；subject = v4_a48_supertrend_futu.py 喺 FTNN 手冊 shim 下執行
# 範圍声明：本對數驗證「移植 vs Pine 語義」0 diff；唔等同 TradingView 實值核對（嗰步屬 A99 套用測試／主持 TV 對比，本席冇 TV／FTNN runtime，照 66141 教訓唔會宣稱 TV parity）
import math, os, sys

NA = float('nan')
def isna(x): return x != x
def fmax(a, b):  # Pine math.max：任一 na → na
    return NA if (isna(a) or isna(b)) else max(a, b)
def fmin(a, b):
    return NA if (isna(a) or isna(b)) else min(a, b)
def fround(a):  # Pine math.round：away from zero
    return NA if isna(a) else (math.floor(a + 0.5) if a >= 0 else -math.floor(-a + 0.5))
def gt(a, b): return False if (isna(a) or isna(b)) else a > b
def lt(a, b): return False if (isna(a) or isna(b)) else a &lt; b

def make_sine(n=300, cycles=4, amp=600.0, noise=25.0, seed=99):
    import math as _m
    st, res = seed, []
    prev = 26000.0
    for i in range(n):
        st = (1103515245 * st + 12345) &amp; 0x7FFFFFFF
        r1 = (st / 0x7FFFFFFF - 0.5) * noise
        c = 26000.0 + amp * _m.sin(2 * _m.pi * cycles * i / n) + r1
        st = (1103515245 * st + 12345) &amp; 0x7FFFFFFF
        r2 = abs((st / 0x7FFFFFFF - 0.5)) * noise
        o = prev
        h = max(o, c) + r2 + 1.0
        l = min(o, c) - r2 - 1.0
        res.append({'o': o, 'h': h, 'l': l, 'c': c})
        prev = c
    return res

def make_fixture(n=300, seed=12345, vol=22.0, regime=60, up=6.0, dn=-5.0):
    st, res = seed, []
    for i in range(n):
        st = (1103515245 * st + 12345) &amp; 0x7FFFFFFF
        r1 = (st / 0x7FFFFFFF) - 0.5
        st = (1103515245 * st + 12345) &amp; 0x7FFFFFFF
        r2 = (st / 0x7FFFFFFF) - 0.5
        trend = up if (i // regime) % 2 == 0 else dn
        step = trend + r1 * vol
        o = 26000.0 + i * 0.1 + (res[-1]['c'] - 26000.0 - (i - 1) * 0.1) * 0.3 if res else 26000.0
        c = (res[-1]['c'] if res else 26000.0) + step
        h = max(o, c) + abs(r2) * 14.0 + 0.5
        l = min(o, c) - abs(r2) * 14.0 - 0.5
        res.append({'o': o, 'h': h, 'l': l, 'c': c})
    return res

def pine_reference(bars, i_len=14, i_factor=3.5, i_er_len=10, i_confirm=2):
    n = len(bars)
    O = [b['o'] for b in bars]; H = [b['h'] for b in bars]
    L = [b['l'] for b in bars]; C = [b['c'] for b in bars]
    hl2 = [(H[i] + L[i]) * 0.5 for i in range(n)]
    out = {k: [NA] * n for k in ('atr', 'er', 'ers', 'vr', 'vreg', 'ub', 'lb', 'dir', 'st',
                                'q', 'ac', 'flip', 'flq', 'age', 'conv')}
    tr = [NA] * n
    for i in range(n):
        if i == 0: tr[i] = H[0] - L[0]
        else: tr[i] = fmax(H[i] - L[i], fmax(abs(H[i] - C[i-1]), abs(L[i] - C[i-1])))
    atr = [NA] * n; s = 0.0; seed_ok = False
    for i in range(n):
        if i == i_len - 1 and not isna(tr[i]):
            s = sum(tr[:i_len]); atr[i] = s / i_len; seed_ok = True
        elif i >= i_len and seed_ok:
            atr[i] = (atr[i-1] * (i_len - 1) + tr[i]) / i_len
    out['atr'] = atr
    er = [NA] * n
    for i in range(n):
        if i >= i_er_len:
            net = abs(C[i] - C[i - i_er_len]); tot = sum(abs(C[i-j] - C[i-j-1]) for j in range(i_er_len))
            er[i] = (net / tot) if tot > 0 else 0.0
    out['er'] = er
    ers = [NA] * n; ema = NA
    for i in range(n):
        if isna(er[i]): continue
        ema = er[i] if isna(ema) else (2 * er[i] + (3 - 1) * ema) / (3 + 1)
        ers[i] = ema
    out['ers'] = ers
    sma50 = [NA] * n
    for i in range(n):
        if i >= 49 and all(not isna(atr[i-j]) for j in range(50)):
            sma50[i] = sum(atr[i-49:i+1]) / 50.0
    vr = [NA] * n
    for i in range(n):
        vr[i] = (atr[i] / sma50[i]) if (not isna(atr[i]) and gt(sma50[i], 0)) else 1.0
    out['vr'] = vr
    out['vreg'] = [fmax(fmin(vr[i], 1.40), 0.75) for i in range(n)]
    ub = [NA] * n; lb = [NA] * n; adir = [NA] * n
    for i in range(n):
        af = i_factor * out['vreg'][i]
        ubasic = NA if isna(atr[i]) else hl2[i] + af * atr[i]
        lbasic = NA if isna(atr[i]) else hl2[i] - af * atr[i]
        if i == 0 or isna(ub[i-1]):
            ub[i] = ubasic; lb[i] = lbasic
        else:
            ub[i] = ubasic if (lt(ubasic, ub[i-1]) or gt(C[i-1], ub[i-1])) else ub[i-1]
            lb[i] = lbasic if (gt(lbasic, lb[i-1]) or lt(C[i-1], lb[i-1])) else lb[i-1]
        if i == 0 or isna(adir[i-1]):
            adir[i] = 1
        else:
            if adir[i-1] == 1: adir[i] = -1 if lt(C[i], lb[i]) else 1
            else: adir[i] = 1 if gt(C[i], ub[i]) else -1
    out['ub'] = ub; out['lb'] = lb; out['dir'] = adir
    out['st'] = [lb[i] if adir[i] == 1 else ub[i] for i in range(n)]
    q = [NA] * n; ac = [NA] * n
    for i in range(n):
        if isna(ers[i]): ac[i] = fmax(i_confirm - 1, 1)
        elif ers[i] &lt; 0.25: ac[i] = fmax(i_confirm + 2, 4)
        elif ers[i] &lt; 0.45: ac[i] = i_confirm + 1
        elif ers[i] &lt; 0.65: ac[i] = i_confirm
        else: ac[i] = fmax(i_confirm - 1, 1)
    for i in range(n):
        pm = abs(100.0 * (C[i] - C[i-5]) / C[i-5]) if i >= 5 and C[i-5] != 0 else NA
        ap = NA
        if not isna(atr[i]) and C[i] > 0: ap = atr[i] / C[i] * 100.0
        mn = 0.0
        if not isna(ap) and ap > 0: mn = fmin(pm / (ap * 2.0), 1.0)
        vs = fmax(1.0 - abs(1.0 - vr[i]), 0.0)
        raw = (ers[i] * 0.50 + vs * 0.30 + mn * 0.20) * 100
        q[i] = fround(raw)
    out['q'] = q; out['ac'] = ac
    locked = NA; streak = 0; flip = [NA] * n; flq = [NA] * n; age = [0] * n; anyf = [False] * n
    for i in range(n):
        bull = adir[i] == 1
        if isna(locked): locked = bull
        streak = 0 if bull == locked else streak + 1
        fu = (not isna(ac[i])) and streak >= ac[i] and bull
        fd = (not isna(ac[i])) and streak >= ac[i] and (not bull)
        a = fu or fd
        anyf[i] = a
        if a:
            locked = bull
            flq[i] = q[i]
            flip[i] = out['st'][i]
        age[i] = 0 if a else (age[i-1] + 1 if i > 0 else 1)
    out['flip'] = flip; out['flq'] = flq; out['age'] = age
    out['conv'] = [NA if isna(ers[i]) else min(age[i] / 60.0, 1.0) * 0.65 + ers[i] * 0.35 for i in range(n)]
    return out

class Seq(list):
    def ref(self, k):
        return Seq([NA] * min(k, len(self)) + list(self[:len(self)-k])[:len(self)] if k > 0 else list(self))

def run_port(bars, path='v4_a48_supertrend_futu.py', ov=None):
    import types
    n = len(bars)
    captured = {}
    ov = ov or {}
    for mod in ('fmath', 'fta', 'ftool', 'fdatetime'):
        if mod not in sys.modules or not getattr(sys.modules[mod], '_a48_stub', False):
            m = types.ModuleType(mod)
            m._a48_stub = True
            m.floor = math.floor
            sys.modules[mod] = m
    g = {
        '__name__': '__main__',
        'indicator': lambda *a: None,
        'input_parameter': (lambda name, d, *r: ov.get(name, d)),
        'bars_count': lambda: n,
        'high': lambda: Seq([b['h'] for b in bars]),
        'low': lambda: Seq([b['l'] for b in bars]),
        'open': lambda: Seq([b['o'] for b in bars]),
        'close': lambda: Seq([b['c'] for b in bars]),
        'plot': lambda name, s: captured.__setitem__(name, list(s)),
        'floor': math.floor, 'max': lambda a, b: fmax(a, b), 'min': lambda a, b: fmin(a, b),
    }
    src = open(path, encoding='utf-8').read()
    exec(compile(src, path, 'exec'), g)
    return captured

def cmp_series(a, b, name):
    diffs = []
    for i in range(len(a)):
        x, y = a[i], b[i]
        if isna(x) and isna(y): continue
        if isna(x) or isna(y) or abs(x - y) > 1e-9:
            diffs.append((i, x, y))
    return diffs

def one_case(tag, bars, ov=None, kw=None):
    ref = pine_reference(bars, **(kw or {}))
    cap = run_port(bars, ov=ov)
    fields = {'ST線': 'st', '方向': 'dir', '質素分': 'q', '確認K線數': 'ac', '翻轉價位': 'flip', '翻轉評分': 'flq', '趨勢強度': 'conv'}
    total = 0
    for cname, fname in fields.items():
        d = cmp_series(cap.get(cname, [NA]*len(bars)), ref[fname], cname)
        for i, x, y in d[:3]:
            print(f"   {tag} {cname} bar{i}: port={x!r} pine={y!r}")
        total += len(d)
    fp = {i for i, v in enumerate(cap.get('翻轉價位', [])) if not isna(v)}
    fr = {i for i, v in enumerate(ref['flip']) if not isna(v)}
    fq_port = [i for i in sorted(fp) if not isna(cap['翻轉評分'][i])]
    fq_ref = [i for i in sorted(fr) if not isna(ref['flq'][i])]
    total += len(fp ^ fr) + (0 if fq_port == fq_ref else 1)
    print(f"{tag}: total_diff={total} flips={len(fp)}(ref {len(fr)}) grade_flip_bars={len(fq_port)} fixture_sha={hashlib_sha(bars)}")
    return total, len(fp)

def main():
    grand = 0; flips_all = 0
    # 案例 0：正弦大摆动 → 必然多次上下翻轉，覆蓋 locked/streak/grade 路徑
    b0 = make_sine(300, cycles=4, amp=600.0)
    t0, f0 = one_case("CASE0 sine(4cyc)", b0); grand += t0; flips_all += f0
    b0b = make_sine(400, cycles=6, amp=800.0, noise=60.0, seed=1234)
    t0b, f0b = one_case("CASE0b sine(6cyc hi-noise)", b0b); grand += t0b; flips_all += f0b
    # 案例 1：預設參數＋中等波動（300 棒）
    b1 = make_fixture(300, seed=12345)
    t, f = one_case("CASE1 default", b1); grand += t; flips_all += f
    # 案例 2：confirm=1 ＋強趨勢低噪音 → 必然多個 LONG/SHORT 翻轉
    b2 = make_fixture(400, seed=777, vol=6.0, regime=50, up=9.0, dn=-9.0)
    ov = {'確認K線數(基礎)': 1}
    t, f = one_case("CASE2 confirm1 trendy", b2, ov=ov, kw={'i_confirm': 1}); grand += t; flips_all += f
    # 案例 3：其他參數（ATR10/ER8/factor2.5/confirm3）＋高波動
    b3 = make_fixture(300, seed=24601, vol=40.0, regime=37, up=5.0, dn=-7.5)
    ov3 = {'ATR週期': 10, '基礎倍數': 2.5, 'ER週期': 8, '確認K線數(基礎)': 3}
    t, f = one_case("CASE3 alt-params", b3, ov=ov3, kw={'i_len': 10, 'i_factor': 2.5, 'i_er_len': 8, 'i_confirm': 3}); grand += t; flips_all += f
    assert grand == 0, f"PARITY FAIL: {grand} diffs"
    assert flips_all >= 3, f"INVERTED TEST: only {flips_all} flips across cases"
    print(f"PARITY PASS: 3 cases 0-diff, total flips={flips_all}")

def hashlib_sha(bars):
    import hashlib
    h = hashlib.sha256(repr([(round(b['o'],6),round(b['h'],6),round(b['l'],6),round(b['c'],6)) for b in bars]).encode()).hexdigest()
    return h[:12]

if __name__ == '__main__':
    main()
</pre><p>覆核方法：兩檔 save 同DIR後 <code>python3 a48_v4_parity_harness.py</code>，預期 PARITY PASS 同上面輸出逐字一致（以 fixture sha 為準）。源碼 sha：port 4d05ef4c 對上 Pine 原文 16,808 B；本 HTML 連兩份源碼成 all-in-one（65177 格式）。</p>