# 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("I", "V5 副圖貼頂極右 轉向支阻＋5｜6｜7 寬鬆間距 v7 (67022)", False, "A36 r2(覆67022③④)：拿走緊縮間隔(66832收緊值→寬鬆 cjk=14,asc=8,_hwp=6,_gap=4＋字內雙空格)＋拿走2環8向純黑光暈(40呼叫移除)；開頭新項=轉向質素▲/▼𝐀-𝐂＋現時支阻點(L2線值，_fmt_max3_str剝尾零上限3位)字色跟轉向：綠#00a357/紅#e02d48(覆67042，取代0x0f1112固定色)；總計9呼叫<=50，17出參與r1逐值相同")

USE_HK_WORDING = True      # True＝香港中文字眼（造好／造淡：A6 66315 拍板＋A36 底版＋A99 66313＋A25 66314）
                           # False＝源碼原文字眼（做多／做空）；數值層兩版恆等
USE_DYNAMIC_LABEL_TEXT = False
                           # False＝每級靜態字（A36 已證路徑）＋「翻轉棒收盤價」output 作誠實 fallback（A88 66318③）
                           # True ＝close().apply(...) 出 Sequence[str] 攞返源碼兩行文字（A88 66318②）
                           # ⚠ Sequence[str] 仍未在真機驗證 ⇒ 交 A99 貼框試；失敗即改返 False，唔可聲稱 label 文字 100%
NA_AS = "nan"              # 暖機期 na 表示法："nan"＝float("nan")；"none"＝None（視乎真機接邊個）
LABEL_Y_ANCHOR = "bar"     # 標籤 y 錨："bar"＝依源碼 yloc 語義（flip_up→low、flip_down→high，同 TV 渲染位一致）
                           #            "st"＝用 st 字面值（等於 A36 fixture expected_labels.y 嘅記錄值）
                           # 源碼 label.new(bar_index, st, yloc=yloc.belowbar/abovebar)：Pine 語義下 yloc≠price 時
                           # y 參數被忽略、改以 bar 嘅 low/high 渲染 ⇒ "bar" 先係 TV 實際點位（主持 66145/66149）。
                           # 兩個錨嘅 st 值都照樣經 output_parameter 輸出，產生值層 100% 保留。

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": "",   # A6 66315 拍板：造好＝做多、造淡＝沽空／做空；A36 底版同字
        # 若要「好倉／沽空」或「[A級]」後綴，改呢兩行即可（數值層唔受影響）
        "_alt_long": "好倉", "_alt_short": "沽空", "_alt_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 = str(float(mintick))
    dec = 0
    if "." in txt:
        dec = len(txt.split(".")[1].rstrip("0"))
    return ("%%.%df" % dec) % n



def _fmt_max3_str(x):
    # 依 seq=66487：上限 3 位小數、尾數 0 剝除、整數唔出小數點（41.300->"41.3", 65.150->"65.15", 65.0->"65"）
    if x is None or x != x:
        return ""
    neg = x < 0.0
    ax = -x if neg else x
    milli = _round_half_away(ax * 1000.0)
    if milli == 0:
        return "0"
    ip = milli // 1000
    fp = milli % 1000
    if fp == 0:
        s = str(ip)
    else:
        if fp < 10:
            fs = "00" + str(fp)
        elif fp < 100:
            fs = "0" + str(fp)
        else:
            fs = str(fp)
        fs = fs.rstrip("0")
        s = str(ip) + "." + fs
    return ("-" + s) if neg else s

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] if n > 0 else True
    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}


def _half_px(txt, cjk_w, asc_w):
    tot = 0.0
    for ch in txt:
        tot += cjk_w if ord(ch) > 127 else asc_w
    return int(round(tot * 0.5))


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("最小報價單位(0自動原價)", 0.0)
    P_LABELS = input_parameter("多空訊號標籤", True)
    P_GLOW = input_parameter("發光光暈", False)
    P_SHADE = input_parameter("漸層底色", True)
    P_RIGHT_BACK = input_parameter("右錨前推K數(0=最末K)", 0)
    P_RIGHT_PADX = input_parameter("右緣向右推像素", 32)

    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
    C_BULL_LBL = Color.rgb(86, 212, 198) # 深底清晰淡青字色
    C_BEAR_LBL = Color.rgb(255, 118, 115)# 深底清晰淡紅字色

    _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"]

    def _na():
        return float("nan") if NA_AS == "nan" else None

    _cs = close()
    _st = _cs * 0.0
    _locked_dir = _cs * 0.0
    _bull_dir = _cs * 0.0
    _up = {"A": _cs * 0.0, "B": _cs * 0.0, "C": _cs * 0.0}
    _dn = {"A": _cs * 0.0, "B": _cs * 0.0, "C": _cs * 0.0}
    _age = _cs * 0.0
    _conv_pct = _cs * 0.0
    _er_s = _cs * 0.0
    _vol_ratio = _cs * 0.0
    _ad_factor = _cs * 0.0
    _ad_confirm = _cs * 0.0
    _flip_q = _cs * 0.0
    _dist_pct = _cs * 0.0
    _bull_ct = _cs * 0.0
    _bear_ct = _cs * 0.0
    _lbl_st = _cs * 0.0
    _lbl_y = _cs * 0.0
    _flip_close = _cs * 0.0      # 全精度原始翻轉價（供數據窗口＋output_parameter，絕不捨入）
    _flip_close_disp = _cs * 0.0 # 僅供圖表標籤文字 display 專用之近 3 位顯示序列
    _mirror = _cs * 0.0
    _na_v = _na()

    for i in range(N):
        _stv = R["st"][i]
        _st[i] = _stv if _stv is not None else _na_v
        _locked_dir[i] = 1.0 if R["locked"][i] else 0.0
        _bull_dir[i] = 1.0 if R["bull"][i] else 0.0
        _g = R["qGrade"][i]
        if R["flipUp"][i] and _g in _up:
            _up[_g][i] = 1.0
        if R["flipDown"][i] and _g in _dn:
            _dn[_g][i] = 1.0
        _age[i] = float(R["age"][i])
        _conv_pct[i] = float(_round_half_away(R["conv"][i] * 100.0))
        _er_s[i] = float(R["erSmooth"][i])
        _vol_ratio[i] = float(R["volRatio"][i])
        _ad_factor[i] = float(R["adFactor"][i])
        _ad_confirm[i] = float(R["adConfirm"][i])
        _flip_q[i] = float(R["flipQ"][i])
        _dist_pct[i] = (abs(_c[i] - _stv) / abs(_c[i]) * 100.0) if (_stv is not None and _c[i] != 0.0) else 0.0
        _bull_ct[i] = float(R["bullCt"][i])
        _bear_ct[i] = float(R["bearCt"][i])
        if R["flipUp"][i] or R["flipDown"][i]:
            _lbl_st[i] = _stv if _stv is not None else 0.0
            if LABEL_Y_ANCHOR == "bar":
                _lbl_y[i] = _l[i] if R["flipUp"][i] else _h[i]
            else:
                _lbl_y[i] = _stv if _stv is not None else 0.0
            _fc_raw = float(_round_half_away(_c[i] / P_TICK) * P_TICK) if P_TICK > 0.0 else _c[i]
            _flip_close[i] = _fc_raw
            _flip_close_disp[i] = float(_round_half_away(_fc_raw * 1000.0) / 1000.0)
        else:
            _lbl_st[i] = 0.0
            _lbl_y[i] = 0.0
            _flip_close[i] = _na_v
            _flip_close_disp[i] = _na_v
        _mirror[i] = _c[i]

    # ── 17 項具名序列綁定 ──
    _dir_locked_01 = iff(_locked_dir > 0.5, 1, 0)
    _dir_bull_01 = iff(_bull_dir > 0.5, 1, 0)
    _self_chk = _cs - _mirror

    # ── 副圖 (is_overlay=False) 貼頂極右 轉向支阻＋5｜6｜7（67022③④：無黑光暈、寬鬆間距，總計 9 呼叫 <= 50）──
    _TV_BULL = Color.rgb(38, 166, 154, 255)      # TV i_bull #26a69a
    _TV_BEAR = Color.rgb(239, 83, 80, 255)       # TV i_bear #ef5350
    _TV_ORANGE = Color.rgb(255, 152, 0, 255)     # TV color.orange
    _TV_AQUA = Color.rgb(0, 188, 212, 255)       # TV color.aqua
    _TV_GRAY = Color.rgb(120, 123, 134, 255)     # TV color.gray (保留予第5/6項中性)
    _TV_WHITE = Color.rgb(255, 255, 255, 255)    # 僅原 TV color.silver 改純白 #FFFFFF (第7項正常)
    C_TURN_UP = Color.rgb(0, 163, 87)             # 67042：向好／轉綠字色 V5 綠 #00a357
    C_TURN_DN = Color.rgb(224, 45, 72)            # 67042：向淡／轉紅字色 V5 紅 #e02d48（取代 0x0f1112 固定色）
    _TRANS_Y = Color.rgb(0, 0, 0, 0)             # 副圖 [0,100] 頂底界隱形錨

    _y_100_seq = _cs * 0.0 + 5000
    _y_0_seq = _cs * 0.0
    _y_top_seq = _cs * 0.0 + 8800
    _cond_anc = _cs * 0.0

    _val_0 = " "
    _val_5 = " "
    _val_6 = " "
    _val_7 = " "
    _col_0 = C_TURN_UP
    _col_5 = _TV_GRAY
    _col_6 = _TV_GRAY
    _col_7 = _TV_WHITE

    if N > 0:
        _li = N - 1
        _is_lk = bool(R["locked"][_li])
        _tc_col = _TV_BULL if _is_lk else _TV_BEAR

        # 第 5 項：趨勢強度直出 XX%（普通 <=0.5 保留 TV color.gray，>0.5 用 tc）
        _s_raw = float(R["conv"][_li])
        _val_5 = str(int(_conv_pct[_li])) + "%"
        _col_5 = _tc_col if _s_raw > 0.5 else _TV_GRAY

        # 第 6 項：趨勢效率（>0.65 tc, >0.40 orange, 普通 <=0.40 保留 TV color.gray）
        _er_val = float(_er_s[_li])
        _er_tag = W["er_hi"] if _er_val > 0.65 else (W["er_mid"] if _er_val > 0.40 else W["er_lo"])
        _val_6 = _er_tag + "  " + _fmt_max3_str(_er_val)
        _col_6 = _tc_col if _er_val > 0.65 else (_TV_ORANGE if _er_val > 0.40 else _TV_GRAY)

        # 第 7 項：波幅狀態（>1.20 orange, <0.80 aqua, 原銀色正常 0.80..1.20 改純白 #FFFFFF）
        _vr_val = float(_vol_ratio[_li])
        _vr_tag = W["vol_hi"] if _vr_val > 1.20 else (W["vol_lo"] if _vr_val < 0.80 else W["vol_ok"])
        _val_7 = _vr_tag + "  " + _fmt_max3_str(_vr_val)

        # 67022④ 開頭項：轉向及質素（▲/▼＋𝐀/𝐁/𝐂）＋現時支／阻點（L2 線值；尾零剝除、上限 3 位小數；字色跟轉向 綠#00a357/紅#e02d48，覆 67042）
        if bool(R["hasFlip"][_li]):
            _mk = ("▲" if _is_lk else "▼") + {"A": "𝐀", "B": "𝐁", "C": "𝐂"}[R["flipG"][_li]]
        else:
            _mk = "—"
        _val_0 = (_mk + " " + _fmt_max3_str(R["st"][_li])).strip()
        _col_0 = C_TURN_UP if _is_lk else C_TURN_DN   # 67042：字色跟轉向（綠/紅）
        _col_7 = _TV_ORANGE if _vr_val > 1.20 else (_TV_AQUA if _vr_val < 0.80 else _TV_WHITE)

        # 最右錨點（預設 _li=N-1 最末棒，夾限 [0, _li]，N=1..300 零越界）
        _rb = int(P_RIGHT_BACK) if int(P_RIGHT_BACK) >= 0 else 0
        _anc_i = _li - _rb
        if _anc_i < 0:
            _anc_i = 0
        if _anc_i > _li:
            _anc_i = _li
        _cond_anc[_anc_i] = 1.0

    # 67022③ 拿走緊縮間隔：回復寬鬆字寬估算與「｜」間距（cjk=14, asc=8, _hwp=6, _gap=4；字內雙空格）並右對齊末K向左展開
    _hw0 = _half_px(_val_0, 14.0, 8.0)
    _hw5 = _half_px(_val_5, 14.0, 8.0)
    _hwp = 6
    _hw6 = _half_px(_val_6, 14.0, 8.0)
    _hw7 = _half_px(_val_7, 14.0, 8.0)
    _gap = 4
    _total_w = (_hw0 * 2) + (_hw5 * 2) + (_hwp * 6) + (_hw6 * 2) + (_hw7 * 2) + (_gap * 6)
    _cx = int(P_RIGHT_PADX) - _total_w
    _ox0 = _cx + _hw0
    _cx = _cx + (_hw0 * 2) + _gap
    _oxp0 = _cx + _hwp
    _cx = _cx + (_hwp * 2) + _gap
    _ox5 = _cx + _hw5
    _cx = _cx + (_hw5 * 2) + _gap
    _oxp1 = _cx + _hwp
    _cx = _cx + (_hwp * 2) + _gap
    _ox6 = _cx + _hw6
    _cx = _cx + (_hw6 * 2) + _gap
    _oxp2 = _cx + _hwp
    _cx = _cx + (_hwp * 2) + _gap
    _ox7 = _cx + _hw7

    _ac = _cond_anc > 0.5

    plot("　",            _cs * 0.0, color=Color.rgb(15, 17, 18, 100), linewidth=1)
    plot("　　",          _cs * 0.0, color=Color.rgb(15, 17, 18, 100), linewidth=1)
    plot("　　　",        _cs * 0.0, color=Color.rgb(15, 17, 18, 100), linewidth=1)
    plot("　　　　",      _cs * 0.0, color=Color.rgb(15, 17, 18, 100), linewidth=1)
    plot("　　　　　",    _cs * 0.0, color=Color.rgb(15, 17, 18, 100), linewidth=1)
    plot("　　　　　　",  _cs * 0.0, color=Color.rgb(15, 17, 18, 100), linewidth=1)
    plot("　　　　　　　",  _cs * 0.0, color=Color.rgb(15, 17, 18, 100), linewidth=1)
    plot("　　　　　　　　　　　　　",  _cs * 0.0, color=Color.rgb(15, 17, 18, 100), linewidth=1)    # 副圖隱形 [0, 100] 上下界（令 y=93 穩居副圖最頂，不影響主圖Y軸）
    plot("副圖頂錨", _y_100_seq, color=_TRANS_Y, linewidth=1)
    plot("副圖底錨", _y_0_seq, color=_TRANS_Y, linewidth=1)


    # 上層前景彩色文字（67022③④：黑光暈已移除；開頭項＋分隔線0 為新輸出；總計 9 呼叫 <= 50）
    plot_text("項00轉向支阻", _ac, _y_top_seq, _val_0, color=_col_0, size=4, offseth=_ox0, offsetv=0)
    plot_text("分隔線0",      _ac, _y_top_seq, "｜",   color=_TV_GRAY, size=4, offseth=_oxp0, offsetv=0)
    plot_text("項05趨勢強度", _ac, _y_top_seq, _val_5, color=_col_5,   size=4, offseth=_ox5,  offsetv=0)
    plot_text("分隔線1",      _ac, _y_top_seq, "｜",   color=_TV_GRAY, size=4, offseth=_oxp1, offsetv=0)
    plot_text("項06趨勢效率", _ac, _y_top_seq, _val_6, color=_col_6,   size=4, offseth=_ox6,  offsetv=0)
    plot_text("分隔線2",      _ac, _y_top_seq, "｜",   color=_TV_GRAY, size=4, offseth=_oxp2, offsetv=0)
    plot_text("項07波幅狀態", _ac, _y_top_seq, _val_7, color=_col_7,   size=4, offseth=_ox7,  offsetv=0)

    output_parameter(
        波幅比率=_vol_ratio,
        翻轉棒收盤價=_flip_close,
        超級趨勢線數值=_st,
        方向好倉為1=_dir_locked_01,
        即時方向好倉為1=_dir_bull_01,
        持續陰陽燭數=_age,
        趨勢信念百分比=_conv_pct,
        趨勢效率=_er_s,
        動態乘數=_ad_factor,
        確認閘=_ad_confirm,
        最近訊號質素=_flip_q,
        偏離趨勢線百分比=_dist_pct,
        好倉翻轉數=_bull_ct,
        沽空翻轉數=_bear_ct,
        翻轉棒趨勢線值=_lbl_st,
        翻轉棒標籤y錨=_lbl_y,
        綁定對齊自檢=_self_chk,
    )
