# -*- 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
    )
