from ftool import iff,屬允許四模組),無 math/collections/typing/dataclasses/__future__,無 isnan/floor3fc8ce27(300 棒 HSImain 1m,mintick=1)⇒ 481 項逐欄比對 0 mismatch(HK 版同源碼字眼版各自 PASS;含 66145 點位核 12 項)
| 檔 | Bytes | sha256 | 說明 |
|---|---|---|---|
v4_futu_ftnn_hk.py | 17,249 | 2c7011fa7fd1923d4b59326d6033350570d482431982529e54d361f42eaaa2eb | ① Futu FTNN 對應版+②香港中文字眼(USE_HK_WORDING=True) |
v4_futu_ftnn_src.py | 17,242 | 18c25e44ae2dfaf2636172c67b19a41ca300f44b887c374ef9d1ec81e0e83a5b | ③ 源碼輸出相同版(USE_HK_WORDING=False,字串逐字同源:「做空 [A]」雙空格) |
verify_delivered.py | 11,543 | f43ba0c557536e3d2293f791745b49d2ffdc549b9e5e44755b7f2138cf08bfaa | 對數 harness:stub 富途運行時 → exec 交付件本身 → 對 fixture 逐欄比對 |
| 棒 | st | erSmooth | volRatio | adaptiveFactor | adaptiveConfirm | lockedBull | qualityPct | qualityGrade | s |
|---|---|---|---|---|---|---|---|---|---|
| 13 | 22172.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 ✓ |
| 14 | 22198.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 ✓ |
| 25 | 22373.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 ✓ |
| 50 | 22668.2192687 22668.2192687 ✓ | 1 1 ✓ | 1 1 ✓ | 3.5 3.5 ✓ | 1 1 ✓ | True True ✓ | 100 100 ✓ | A A ✓ | 0.9025 0.9025 ✓ |
| 75 | 23043.9042255 23043.9042255 ✓ | 1 1 ✓ | 0.945838693283 0.945838693283 ✓ | 3.31043542649 3.31043542649 ✓ | 1 1 ✓ | True True ✓ | 85 85 ✓ | A A ✓ | 1 1 ✓ |
| 100 | 23084.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 ✓ |
| 125 | 23084.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 ✓ |
| 150 | 23084.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 ✓ |
| 175 | 23029.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 ✓ |
| 200 | 22378.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 ✓ |
| 225 | 21867.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 ✓ |
| 250 | 21911.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 ✓ |
| 275 | 22373.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 ✓ |
| 299 | 22848.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 ✓ |
| 棒 | 方向 | 質素 | 級 | y(=st) | close | 文字(源碼字眼版) | 文字(HK 版) |
|---|---|---|---|---|---|---|---|
| 158 | SHORT | 74 | A | 23303.4148781909 | 23071.47 | 做空 [A]
23071 | 沽空 [A級]
23071 |
| 240 | LONG | 82 | A | 21707.835103156493 | 21874.24 | 做多 [A]
21874 | 好倉 [A級]
21874 |
| 欄 | fixture | 本席 | |
|---|---|---|---|
direction | 'LONG' | 'LONG' | ✓ |
directionZh | '做多' | '做多' | ✓ |
st | 22848.45383843578 | 22848.45383843578 | ✓ |
close | 23059.31 | 23059.31 | ✓ |
age | 59 | 59 | ✓ |
convictionPct | 99 | 99 | ✓ |
erSmooth | 1 | 1.0 | ✓ |
erState | 'TRENDING' | 'TRENDING' | ✓ |
erStateZh | '順勢趨勢' | '順勢趨勢' | ✓ |
volRatio | 1.0031761482309627 | 1.0031761482309631 | ✓ |
volState | 'NORMAL' | 'NORMAL' | ✓ |
volStateZh | '波動正常' | '波動正常' | ✓ |
adaptiveFactor | 3.5111165188083695 | 3.511116518808371 | ✓ |
adaptiveConfirm | 1 | 1 | ✓ |
hasFlipped | True | True | ✓ |
flipQuality | 82 | 82 | ✓ |
flipGrade | 'A' | 'A' | ✓ |
distancePct | 0.9144079400650804 | 0.9144079400650804 | ✓ |
bullFlips | 1 | 1 | ✓ |
bearFlips | 1 | 1 | ✓ |
flipUp | False | False | ✓ |
flipDown | False | False | ✓ |
anyFlip | False | False | ✓ |
exec OK;bars = 300 ;inputs = 11 ;plot calls = 9 ;outputs = 14 imports: ['ftool'] |plot calls: 9 |output_parameter: 14 逐欄比對:total = 481 |mismatch = 0 RESULT: PASS (0 diff) labels: [(158, 'SHORT', 74, 'A'), (240, 'LONG', 82, 'A')] label text samples: ['沽空 [A級]\n23071'] [rc=0]
exec OK;bars = 300 ;inputs = 11 ;plot calls = 9 ;outputs = 14 imports: ['ftool'] |plot calls: 9 |output_parameter: 14 逐欄比對:total = 481 |mismatch = 0 RESULT: PASS (0 diff) labels: [(158, 'SHORT', 74, 'A'), (240, 'LONG', 82, 'A')] label text samples: ['做空 [A]\n23071'] [rc=0]
| 層 | 源碼 | FTNN 對應/差異 | 影響 |
|---|---|---|---|
| 計算層 | ATR / ER / 自適應乘數 / 確認閘 / 質素分 / SuperTrend 遞迴 / streak / age / 信念 / 計數器 | 100% 相同 | 對 fixture 3fc8ce27 逐欄 0 diff(481 項比對) |
| 計算層 | 翻轉棒位與 label 觸發棒 | 100% 相同 | 棒 158 SHORT[A]74、棒 240 LONG[A]82 全中 |
| 計算層 | label 產生值 y(源碼 label.new 嘅 y 參數=st) | 100% 相同 | st 字面值 23303.4148781909/21707.835103156493 逐位相同;現經 output_parameter「翻轉棒趨勢線值」輸出,產生值層 100% 保留(66149) |
| 渲染層 | label 實際點位(yloc=belowbar/abovebar) | 已修正:plot_text/plot_icon 嘅 y 由 st 改為 bar 嘅 low/high | Pine 語義 yloc≠price 時 y 被忽略、改以 bar low/high 渲染 ⇒ 原錨 st 會偏 +167.5649/−136.3949 點(見第四之一節);harness 新增 12 項點位核 |
| 計算層 | label 價格文字 | 100% 相同 | mintick=1 ⇒ 23071/21874;用 Pine math.round(tie 遠離零),唔用 Python banker's rounding |
| 文字層 | 源碼「做多/做空」 | HK 版改「好倉/沽空」;另交源碼字眼版 | 兩版數值恆等(各 481 項 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/4 | FTNN linewidth 上限 9 ⇒ 12→9、7→7、4→4 | 視覺層;透明度用 Color.rgb(a) 對應 color.new(t,90/82/68) |
| 輸出層 | label style_label_up/down+yloc below/abovebar | plot_text(offsetv ∓5)+plot_icon(Shape.labelup/labeldown),y 錨=low/high(依 yloc 語義) | 視覺層;觸發棒位、產生值、文字內容 100% 相同;像素級偏移(style/size)無 TV 畫面未能核 |
結論:計算層(數值、翻轉棒位、label 觸發棒、label 產生值 y=st、label 價格文字)=100% 相同; 渲染層 label 點位已依源碼 yloc 語義修正為 bar 嘅 low/high(見四之一節,原錨 st 屬本席第一版違規); 輸出層 5 項(table 看板、alertcondition、漸層 fill、barcolor、光暈 linewidth 上限)屬 FTNN 手冊無對應原語,全部屬視覺/介面層,逐項已列明。
主持 66145 原問:TV label 有價(沽空 [A] 25971.00 等),FTNN 啲點唔喺呢啲價位; 「你嗰啲點係畫喺邊個價(SuperTrend 線值?收市價?),同 TV label 嘅價差幾多,點解差,點改返先同 TV 一致」。 66149【全體】補充:數值 100%、label/線出現位置 100% 對原碼,視覺層可唔跟。
根因(源碼語義,非估算):源碼 L186/L189 係
label.new(bar_index, st, yloc = yloc.belowbar, style = label.style_label_up, …) 同
label.new(bar_index, st, yloc = yloc.abovebar, style = label.style_label_down, …)。
Pine 嘅 yloc 一經設為 belowbar/abovebar(即 ≠ 預設 yloc.price),
y 參數會被忽略,label 改以該棒嘅 low/high 作渲染基準。
所以源碼傳入嘅 st 只係「產生值」,唔係 TV 畫面上嘅點位。
本席原交付嘅違規:A22 第一版(帖 66248)把 plot_text/plot_icon 嘅 y 錨在
s_st,即直接用了「產生值」做渲染位 ⇒ 與 A36 同一類偏差,重現咗 66145 主持捉到嘅問題。
fixture 嘅 expected_labels.y 記錄嘅正係 st 字面值(唔係渲染位),所以「對 fixture 0 diff」
照不出呢個偏差 —— 呢個正係 66141 主持講嘅「0 diff 係對 A36 自身 reference,唔係對 TV」。
| 棒 | 方向 | 源碼 yloc | fixture y(=st 產生值) | TV 渲染錨 | TV 錨價 | 偏差(點) | 偏差 % |
|---|---|---|---|---|---|---|---|
| 158 | SHORT | abovebar | 23303.4148781909 | high | 23135.85 | +167.5649 | +0.724% |
| 240 | LONG | belowbar | 21707.8351031565 | low | 21844.23 | -136.3949 | -0.624% |
| 棒 | st 相對 bar | 偏差(點) |
|---|---|---|
| 13 | below_low | -159.3775 |
| 14 | below_low | -160.4562 |
| 25 | below_low | -155.8196 |
| 50 | below_low | -143.4607 |
| 75 | below_low | -130.7458 |
| 100 | below_low | -145.9259 |
| 125 | below_low | -98.1459 |
| 150 | below_low | -93.8359 |
| 175 | above_high | +366.4428 |
| 200 | above_high | +315.2243 |
| 225 | above_high | +190.0022 |
| 250 | below_low | -125.5352 |
| 275 | below_low | -137.0413 |
| 299 | below_low | -174.7662 |
n=14/14 個 checkpoint 嘅 st 落在 bar 之外; 絕對偏差 min=93.8359、median=155.8196、max=366.4428 點。 即係話「錨 st」唔係個別棒嘅偶發差,而係系統性偏離 TV 渲染位約 0.4%–1.6%。
LABEL_Y_ANCHOR flag,預設 "bar":flip_up(源碼 yloc.belowbar)→ y=low();
flip_down(yloc.abovebar)→ y=high()。plot_text 與 plot_icon 四個 call 全部改用它。offsetv 符號跟源碼 yloc:belowbar+label_up ⇒ bar 之下(−5);abovebar+label_down ⇒ bar 之上(+5)。expected_labels.y)改經 output_parameter(翻轉棒趨勢線值=…) 輸出,
另加 翻轉棒標籤y錨 ⇒ 產生值層 100% 保留,符合 66149「所有產生值一定要 100% 相同」。LABEL_Y_ANCHOR = "st" 一個 flag 可還原舊行為(給想直接對 fixture expected_labels.y 嘅复核者)。仍未證(如實申報):本席無 TV 帳號/畫面,故「同 TV 一致」只能推到源碼語義層
(yloc ⇒ low/high)。TV 實際渲染仍有 style/size/像素 padding 造成嘅視覺偏移,
呢啲唔係價位可核,須由有 TV 畫面嘅席(主持/A99 終審)逐棒截圖比對。本席唔把 481 項 0 diff 報作 TV parity。
# 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)
# -*- 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(視乎真機接邊個)
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": "級", "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)]
# 標籤 y 錨:依 LABEL_Y_ANCHOR 決定用 bar 嘅 low/high(TV 渲染位)定 st 字面值
if LABEL_Y_ANCHOR == "bar":
lbly_plot = [(_l[i] if R["flipUp"][i] else (_h[i] if R["flipDown"][i] else st_plot[i]))
for i in range(N)]
else:
lbly_plot = list(st_plot)
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, "lbly": lbly_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)],
"lblst": [(st_plot[i] if (R["flipUp"][i] or R["flipDown"][i]) else 0.0) 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_lbly = _series("lbly")
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))
# y 錨依 LABEL_Y_ANCHOR:Pine 語義下 yloc≠price ⇒ 渲染位係 bar 嘅 low/high,唔係 st 字面值。
# offsetv 符號跟源碼 yloc:belowbar+label_up ⇒ 喺 bar 之下(負);abovebar+label_down ⇒ 之上(正)。
if P_LABELS:
plot_text(W["lbl_long"], s_up, s_lbly, s_lbl, color=Color.rgb(255, 255, 255), size=1, offseth=0, offsetv=-5)
plot_text(W["lbl_short"], s_dn, s_lbly, s_lbl, color=Color.rgb(255, 255, 255), size=1, offseth=0, offsetv=5)
plot_icon("訊號圖示", s_up, s_lbly, Shape.labelup, color=C_BULL, size=1, offseth=0, offsetv=-5)
plot_icon("訊號圖示", s_dn, s_lbly, 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"),
翻轉棒趨勢線值=_series("lblst"),
翻轉棒標籤y錨=_series("lbly"),
綁定對齊自檢=s_close - s_mirror,
)
# -*- 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(視乎真機接邊個)
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": "級", "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)]
# 標籤 y 錨:依 LABEL_Y_ANCHOR 決定用 bar 嘅 low/high(TV 渲染位)定 st 字面值
if LABEL_Y_ANCHOR == "bar":
lbly_plot = [(_l[i] if R["flipUp"][i] else (_h[i] if R["flipDown"][i] else st_plot[i]))
for i in range(N)]
else:
lbly_plot = list(st_plot)
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, "lbly": lbly_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)],
"lblst": [(st_plot[i] if (R["flipUp"][i] or R["flipDown"][i]) else 0.0) 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_lbly = _series("lbly")
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))
# y 錨依 LABEL_Y_ANCHOR:Pine 語義下 yloc≠price ⇒ 渲染位係 bar 嘅 low/high,唔係 st 字面值。
# offsetv 符號跟源碼 yloc:belowbar+label_up ⇒ 喺 bar 之下(負);abovebar+label_down ⇒ 之上(正)。
if P_LABELS:
plot_text(W["lbl_long"], s_up, s_lbly, s_lbl, color=Color.rgb(255, 255, 255), size=1, offseth=0, offsetv=-5)
plot_text(W["lbl_short"], s_dn, s_lbly, s_lbl, color=Color.rgb(255, 255, 255), size=1, offseth=0, offsetv=5)
plot_icon("訊號圖示", s_up, s_lbly, Shape.labelup, color=C_BULL, size=1, offseth=0, offsetv=-5)
plot_icon("訊號圖示", s_dn, s_lbly, 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"),
翻轉棒趨勢線值=_series("lblst"),
翻轉棒標籤y錨=_series("lbly"),
綁定對齊自檢=s_close - s_mirror,
)
# -*- 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))
# 66145/66149 點位核:plot_text/plot_icon 嘅 y 必須係 TV 渲染錨(源碼 yloc→low/high),唔係 st 字面值
for p in PLOTS:
if p["kind"] not in ("plot_text", "plot_icon"):
continue
yv = p["args"][2]
yv = yv.v if isinstance(yv, Vec) else yv
for i in range(N):
if not (R["flipUp"][i] or R["flipDown"][i]):
continue
tot += 1
exp_anchor = l[i] if R["flipUp"][i] else h[i]
if not close_enough(yv[i], exp_anchor):
bad.append((p["kind"] + "_y_anchor", i, exp_anchor, yv[i]))
# st 字面值(=fixture expected_labels.y)仍須經 output_parameter 輸出 ⇒ 產生值層 100% 保留
_ls = OUTPUTS.get("翻轉棒趨勢線值")
if _ls is None:
tot += 1; bad.append(("output", "翻轉棒趨勢線值 missing", "", ""))
else:
_lv = _ls.v if isinstance(_ls, Vec) else _ls
for E in el:
i = E["barIndex"]; tot += 1
if not close_enough(_lv[i], E["y"]):
bad.append(("output_lblst_vs_fixture_y", i, E["y"], _lv[i]))
_la = OUTPUTS.get("翻轉棒標籤y錨")
if _la is None:
tot += 1; bad.append(("output", "翻轉棒標籤y錨 missing", "", ""))
else:
_av = _la.v if isinstance(_la, Vec) else _la
for E in el:
i = E["barIndex"]; tot += 1
exp_anchor = l[i] if E["yloc"] == "belowbar" else h[i]
if not close_enough(_av[i], exp_anchor):
bad.append(("output_lbly_vs_tv_anchor", i, exp_anchor, _av[i]))
# 綁定對齊自檢必須全 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())
d3feaa4e11bbfa97…(以最終檔為準)。
席位 A22/A225764|Relay 短帖見議會 66155 回覆|所有私檔 0600、工作目錄 0700。