#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""V4 超級趨勢（自適應版）— Futu 對應版：Pine v6 → Python 逐節移植
源碼（唯一真值）：http://149.118.48.126:8080/v4-supertrend-zh-v6.txt
                  16,808 B  sha256 4d05ef4c07db64570a4c073697507235a4a144e10b47f8c81716b83d79aad1bb
上游：SuperTrendy (c) TheRealDrip2Rip（MPL-2.0，檔案首行原樣保留）
輸入：bars = [{"t":ms,"o":float,"h":float,"l":float,"c":float,"v":float}]（由舊到新）
輸出：每棒 dict，欄位命名對應源碼變數（見報告對照表）
純標準庫、無第三方依賴。
"""
from math import floor

DEF = dict(i_len=14, i_factor=3.5, i_er_len=10, i_confirm=2,
           er_ema=3, atr_base=50, roc_len=5)


def pround(x):
    """Pine math.round：四捨五入（.5 向上），唔用 Python 銀行家捨入。"""
    return int(floor(x + 0.5)) if x >= 0 else -int(floor(-x + 0.5))


def _rma_ema(vals, n, kind="ema"):
    """Pine ta.ema / ta.rma：頭 n 個以 SMA 播種（同 ta.ema 行為）。"""
    out, buf, prev = [], [], None
    for v in vals:
        if v is None:
            out.append(None)
            continue
        if prev is None:
            buf.append(v)
            if len(buf) < n:
                out.append(None)
                continue
            prev = sum(buf) / n
            out.append(prev)
            continue
        k = 2.0 / (n + 1) if kind == "ema" else 1.0 / n
        prev = v * k + prev * (1 - k)
        out.append(prev)
    return out


def _atr(bars, n):
    """ta.atr(i_len) == ta.rma(tr, i_len)；tr 定義同 Pine。"""
    tr = []
    for i, b in enumerate(bars):
        if i == 0:
            tr.append(b["h"] - b["l"])
        else:
            pc = bars[i - 1]["c"]
            tr.append(max(b["h"] - b["l"], abs(b["h"] - pc), abs(b["l"] - pc)))
    return _rma_ema(tr, n, "rma")


def _sma(vals, n):
    out = []
    for i, v in enumerate(vals):
        if v is None or i + 1 < n:
            out.append(None)
            continue
        w = vals[i - n + 1:i + 1]
        out.append(None if any(x is None for x in w) else sum(w) / n)
    return out


def _er(closes, n):
    """Kaufman ER——逐字對應源碼 for 迴圈：total_path += |close[i]-close[i+1]|
    Pine 暖機（i<n）：close[i-n]=na → net_move/total_path 都係 na → 條件 false
    → 走 else 分支 er=0.0（A36 對齊筆記①：棒0..9 er=0.0 非消滅）。"""
    out = []
    for i in range(len(closes)):
        if i < n:
            out.append(0.0)
            continue
        net = abs(closes[i] - closes[i - n])
        path = 0.0
        for k in range(n):
            path += abs(closes[i - k] - closes[i - k - 1])
        out.append(net / path if path > 0 else 0.0)
    return out


def _norm_bar(b):
    """接受 dict {"t","o","h","l","c","v"} 或 list [ts,o,h,l,c,v]。"""
    if isinstance(b, dict):
        return b
    return dict(t=b[0], o=b[1], h=b[2], l=b[3], c=b[4], v=b[5])


def compute(bars, **kw):
    bars = [_norm_bar(b) for b in bars]
    p = dict(DEF)
    p.update({k: v for k, v in kw.items() if k in DEF})

    atr = _atr(bars, p["i_len"])
    closes = [b["c"] for b in bars]
    er_smooth = _rma_ema(_er(closes, p["i_er_len"]), p["er_ema"], "ema")
    atr_baseline = _sma(atr, p["atr_base"])

    out = []
    upper_band = lower_band = None
    trend_dir = None
    locked_bull = None
    streak = 0
    flip_quality = 0
    has_flipped = False
    bull_ct = bear_ct = age = 0

    for i, b in enumerate(bars):
        # ── Pine 暖機逐棒執行（A36 對齊筆記②）：
        #    atr=na → band na、trend_dir 維持 1、locked_bull 棒0 即鎖 true、
        #    streak=0、age 照累（棒13 時 age=14）。呢啲棒唔計分（輸出 None），
        #    但狀態必須同 Pine 一致咁帶落去，否則 flip 位置會移位。
        if atr[i] is None:
            if trend_dir is None:
                trend_dir = 1              # var int trend_dir = 1（棒0 初始化）
            else:
                trend_dir = 1              # close < na → false → 維持 1
            bull = trend_dir == 1
            if locked_bull is None:
                locked_bull = bull         # var bool locked_bull = bull（棒0）
            streak = 0 if bull == locked_bull else streak + 1
            age += 1                       # any_flip 必為 false（streak=0）
            out.append(None)
            continue

        # -- 2. 波動率狀態
        ab = atr_baseline[i]
        vol_ratio = (atr[i] / ab) if (ab is not None and ab > 0) else 1.0
        vol_regime = max(min(vol_ratio, 1.40), 0.75)

        # -- 3. 自適應乘數
        adaptive_factor = p["i_factor"] * vol_regime

        # -- 4. ER 驅動的自適應確認
        e = er_smooth[i]
        if e is None:
            # Pine：na 條件逐級 false → 行最後 else
            adaptive_confirm = max(p["i_confirm"] - 1, 1)
        elif e < 0.25:
            adaptive_confirm = max(p["i_confirm"] + 2, 4)
        elif e < 0.45:
            adaptive_confirm = p["i_confirm"] + 1
        elif e < 0.65:
            adaptive_confirm = p["i_confirm"]
        else:
            adaptive_confirm = max(p["i_confirm"] - 1, 1)

        # -- 5. 反轉訊號品質評分 (0-100)
        prev_c = closes[i - p["roc_len"]] if i >= p["roc_len"] else None
        price_mom_pct = abs(b["c"] - prev_c) / prev_c * 100 if prev_c else 0.0
        atr_pct = (atr[i] / b["c"] * 100) if b["c"] > 0 else 0.0
        mom_norm = min(price_mom_pct / (atr_pct * 2), 1.0) if atr_pct > 0 else 0.0
        vol_score = max(1.0 - abs(1.0 - vol_ratio), 0.0)
        quality_pct = pround((e * 0.50 + vol_score * 0.30 + mom_norm * 0.20) * 100)
        quality_grade = "A" if quality_pct >= 70 else ("B" if quality_pct >= 50 else "C")

        # -- 手動超級趨勢（配合自適應乘數）
        hl2 = (b["h"] + b["l"]) / 2
        upper_basic = hl2 + adaptive_factor * atr[i]
        lower_basic = hl2 - adaptive_factor * atr[i]
        if upper_band is None:
            upper_band, lower_band = upper_basic, lower_basic
        else:
            pc = bars[i - 1]["c"]
            upper_band = upper_basic if (upper_basic < upper_band or pc > upper_band) else upper_band
            lower_band = lower_basic if (lower_basic > lower_band or pc < lower_band) else lower_band

        if trend_dir is None:
            trend_dir = 1                      # var int trend_dir = 1（棒0 初始化）
        elif trend_dir == 1:
            trend_dir = -1 if b["c"] < lower_band else 1
        else:
            trend_dir = 1 if b["c"] > upper_band else -1

        st = lower_band if trend_dir == 1 else upper_band
        bull = trend_dir == 1

        # -- 確認過濾器（棒0 已鎖 locked_bull，呢度只係兜底）
        if locked_bull is None:
            locked_bull = bull
        streak = 0 if bull == locked_bull else streak + 1
        flip_up = streak >= adaptive_confirm and bull
        flip_down = streak >= adaptive_confirm and not bull
        any_flip = flip_up or flip_down
        if any_flip:
            locked_bull = bull
        tc_bull = bool(locked_bull)

        # -- 品質快照（供看板）
        if any_flip:
            flip_quality = quality_pct
            has_flipped = True
        flip_grade = "A" if flip_quality >= 70 else ("B" if flip_quality >= 50 else "C")

        # -- 趨勢強度／確信度
        age = 0 if any_flip else age + 1
        s_time = min(age / 60.0, 1.0)
        s = s_time * 0.65 + e * 0.35

        if flip_up:
            bull_ct += 1
        if flip_down:
            bear_ct += 1

        # -- 看板衍生值
        dist = abs(b["c"] - st) / b["c"] * 100 if b["c"] else 0.0
        er_label = "趨勢明顯" if e > 0.65 else ("多空交戰" if e > 0.40 else "震盪洗盤")
        vol_label = "波動劇烈" if vol_ratio > 1.20 else ("波動壓縮" if vol_ratio < 0.80 else "正常")

        out.append(dict(
            t=b.get("t"), st=st, dir=trend_dir, bull=bull, tb=tc_bull,
            flip_up=flip_up, flip_down=flip_down, any_flip=any_flip, age=age, s=s,
            er=e, vol_ratio=vol_ratio, vol_regime=vol_regime,
            adaptive_factor=adaptive_factor, adaptive_confirm=adaptive_confirm,
            quality_pct=quality_pct, quality_grade=quality_grade,
            flip_quality=flip_quality, flip_grade=flip_grade, has_flipped=has_flipped,
            dist=dist, er_label=er_label, vol_label=vol_label,
            bull_ct=bull_ct, bear_ct=bear_ct, upper_band=upper_band, lower_band=lower_band))
    return out


def dashboard(last):
    """對應源碼【數據看板】11 行（文字照源碼）。"""
    if not last:
        return []
    filled = pround(last["s"] * 10)
    sbar = ("█" * filled) + ("░" * (10 - filled))
    q_text = ('%d / 100  [%s]' % (last["flip_quality"], last["flip_grade"])
              if last["has_flipped"] else "尚未出現訊號")
    return [
        ("自適應超級趨勢", '倍數:%.2f  確認:%d' % (last["adaptive_factor"], last["adaptive_confirm"])),
        ("當前方向", "做多" if last["tb"] else "做空"),
        ("持續K線數", '%d 根' % last["age"]),
        ("趨勢強度", '%s  %d%%' % (sbar, pround(last["s"] * 100))),
        ("趨勢效率", '%s  %.2f' % (last["er_label"], last["er"])),
        ("波動率狀態", '%s  %.2f' % (last["vol_label"], last["vol_ratio"])),
        ("自適應倍數", '%.2f  (基礎 3.5)' % last["adaptive_factor"]),
        ("上次訊號品質", q_text),
        ("距離趨勢線", '%.2f%%' % last["dist"]),
        ("做多訊號次數", str(last["bull_ct"])),
        ("做空訊號次數", str(last["bear_ct"])),
    ]


def alerts(last):
    """對應源碼【警報設定】三條 alertcondition（文字照源碼）。"""
    if not last:
        return []
    if last["flip_up"]:
        return [("做多訊號", "超級趨勢: 做多")]
    if last["flip_down"]:
        return [("做空訊號", "超級趨勢: 做空")]
    return []


if __name__ == "__main__":
    import json
    import random
    random.seed(4)
    bars, px = [], 22100.0
    for i in range(300):
        o = px
        px += random.gauss(0.7, 15)
        bars.append(dict(t=i * 60000, o=o, h=max(o, px) + abs(random.gauss(0, 6)),
                         l=min(o, px) - abs(random.gauss(0, 6)), c=px,
                         v=random.randint(80, 400)))
    rows = compute(bars)
    good = [r for r in rows if r]
    print(json.dumps({"scored": len(good),
                      "flips": sum(1 for r in good if r["any_flip"]),
                      "last": {k: good[-1][k] for k in ("st", "dir", "age", "s", "er",
                                                        "vol_ratio", "adaptive_factor",
                                                        "adaptive_confirm", "flip_quality",
                                                        "dist")},
                      "dashboard": dashboard(good[-1]),
                      "alerts": alerts(good[-1])}, ensure_ascii=False, indent=1))
