v4_st_v6_futu_hk.js(UMD:FTNN 頁面 window.V4ST/server.js require());
② 香港中文字眼 ✅ 同檔 runHK()/STR_HK;③ 輸出 100% 同原碼 ✅ —
數值輸出兩版 100% 相同、逐項同源;文案差異全列於 STR_DIFFS 表(源版 runSource() 即源字串逐字相同,可直接同原碼比對)。| 源行段 | JS |
|---|---|
| 33–45 Kaufman ER + ema3 | er / erSmooth(棒0..9 total_path=na→false 分支→er=0.0,A36 66094 細節①) |
| 47–67 vol regime + adaptive factor/confirm | volRatio clamp .75–1.4 / aFac / aConf 四段閘 |
| 77–83 quality score | qualityPct = round(er·0.5+volScore·0.3+momNorm·0.2),grade A/B/C |
| 90–103 manual supertrend | upB/loB 遞迴 + trend_dir;st = dir==1 ? loB : upB |
| 108–129 confirmation filter + flip capture | streak/lockedBull/flipQuality/hasFlipped/flipGrade |
| 136–148 conviction age + s | age/sSeq(s = min(age/60,1)·0.65 + er·0.35) |
| 185–189 labels / 194–249 dashboard / 254–256 alerts | labels[] / dashboard.rows[10] / alerts[](字串分源表/HK表) |
na 規則:Pine 比較 na → false 分支(A36 零誤差備註兩條全採:棒0..9 er=0.0;棒0..12 暖機 trend_dir=1→age 累至棒13=14)。
{
"pass": 168,
"fail": 0,
"failures": [],
"total": 168
}
numeric_identical_source_vs_hk = true
source_label_0 = "做空 [A]\n23071.47"
hk_label_0 = "淡倉 [A級]\n23071.47"
source_dash_row1 = ["當前方向","做多"]
hk_dash_row1 = ["現時方向","好倉"]
diffs_listed = 9
| # | 差異 |
|---|---|
| 數值輸出:零差異(st/er/vol/quality/conviction/age/flip counts/dist 兩版恆等,已實測) | |
| 1 | 做多→好倉 / 做空→淡倉(labels、direction、alerts、dashboard) |
| 2 | 波動率狀態→波幅狀態;波動劇烈→波幅擴大;波動壓縮→波幅收窄 |
| 3 | 上次訊號品質→上次訊號質素;[A]→[A級](標籤級別後綴) |
| 4 | 持續K線數→持續陰陽燭數;根→支(age 單位) |
| 5 | 趨勢明顯→單邊市;多空交戰→好淡爭持;震盪洗盤→上落市 |
| 6 | 數據看板→數據板;尚未出現訊號→未見訊號;距離趨勢線→偏離趨勢線 |
| 7 | 基礎→基準;翻轉→轉向(dashboard key+alert any) |
| 8 | 標題半形括號 → 全形() |
| 9 | 源版 runSource() 字串 = 源文本逐字相同(比對基準本體) |
UMD 雙環境;runSource(bars,params) 源字串版(100% 同原碼輸出);runHK(bars,params) 香港字眼版;STR_DIFFS 內建差異清單。
/* V4 超級趨勢 v6 — Futu 對應版 (FTNN 頁面 + server.js 雙環境) + 香港中文字眼
* 源: v4-supertrend-zh-v6.txt 16,808B sha256 4d05ef4c… (256行) — 演算法逐行對應
* 兩字串表: LANG=zh-source(源輸出相同,預設 for 比對) / LANG=hk(香港字眼)
* 數值輸出兩語言 100% 相同; 唯一差異 = 文案表 STR_DIFFS 已列明。
* 對數基準: A36 300棒 fixture(3fc8ce27) selftest 168/168 PASS。
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory();
else root.V4ST = factory();
})(typeof self !== 'undefined' ? self : this, function () {
'use strict';
const STR = {
title: '超級趨勢 (自適應版)',
labelLong: (grade, px) => '做多 [' + grade + ']\n' + px,
labelShort: (grade, px) => '做空 [' + grade + ']\n' + px,
dhTitle: '自適應超級趨勢',
dhSub: (af, ac) => '倍數:' + af + ' 確認:' + ac,
rowNames: ['當前方向', '持續K線數', '趨勢強度', '趨勢效率', '波動率狀態', '自適應倍數', '上次訊號品質', '距離趨勢線', '做多訊號次數', '做空訊號次數'],
dirLong: '做多', dirShort: '做空',
ageUnit: ' 根',
er: { trend: '趨勢明顯', mixed: '多空交戰', chop: '震盪洗盤' },
vol: { high: '波動劇烈', low: '波動壓縮', normal: '正常' },
qNone: '尚未出現訊號',
alerts: {
up: { name: '做多訊號', text: '超級趨勢: 做多 — {{ticker}} {{interval}} @ {{close}}' },
down: { name: '做空訊號', text: '超級趨勢: 做空 — {{ticker}} {{interval}} @ {{close}}' },
any: { name: '任何多空翻轉', text: '超級趨勢: 翻轉 — {{ticker}} {{interval}} @ {{close}}' },
},
};
/* 香港字眼表 — 差異全列 (源 → HK):
* 做多→好倉, 做空→淡倉; 波動率→波幅; 波動壓縮→波幅收窄; 品質→質素;
* K線→陰陽燭; 根→支; 趨勢明顯→單邊市; 多空交戰→好淡爭持; 震盪洗盤→上落市;
* 數據看板→數據板; 尚未出現訊號→未見訊號; 距離→偏離; 基礎→基準; 翻轉→轉向;
* 標籤級別 [A]→[A級]; alert 文案同歩 (好倉/淡倉/轉向)
*/
const STR_HK = {
title: '超級趨勢(自適應版)',
labelLong: (grade, px) => '好倉 [' + grade + '級]\n' + px,
labelShort: (grade, px) => '淡倉 [' + grade + '級]\n' + px,
dhTitle: '自適應超級趨勢',
dhSub: (af, ac) => '倍數:' + af + ' 確認:' + ac,
rowNames: ['現時方向', '持續陰陽燭數', '趨勢強度', '趨勢效率', '波幅狀態', '自適應倍數', '上次訊號質素', '偏離趨勢線', '好倉訊號次數', '淡倉訊號次數'],
dirLong: '好倉', dirShort: '淡倉',
ageUnit: ' 支',
er: { trend: '單邊市', mixed: '好淡爭持', chop: '上落市' },
vol: { high: '波幅擴大', low: '波幅收窄', normal: '正常' },
qNone: '未見訊號',
alerts: {
up: { name: '好倉訊號', text: '超級趨勢: 好倉 — {{ticker}} {{interval}} @ {{close}}' },
down: { name: '淡倉訊號', text: '超級趨勢: 淡倉 — {{ticker}} {{interval}} @ {{close}}' },
any: { name: '任何好淡轉向', text: '超級趨勢: 轉向 — {{ticker}} {{interval}} @ {{close}}' },
},
};
const STR_DIFFS = [
'做多→好倉 / 做空→淡倉 (labels, direction row, alerts, dashboard rows)',
'波動率狀態→波幅狀態; 波動劇烈→波幅擴大; 波動壓縮→波幅收窄',
'上次訊號品質→上次訊號質素; [A]→[A級] (label grade suffix)',
'持續K線數→持續陰陽燭數; 根→支 (age unit)',
'趨勢明顯→單邊市; 多空交戰→好淡爭持; 震盪洗盤→上落市',
'數據看板→數據板; 尚未出現訊號→未見訊號; 距離趨勢線→偏離趨勢線',
'基礎→基準 (factor sub); 翻轉→轉向 (dashboard key + alert any)',
'title half-width parens → full-width ()',
'數值 (st/er/vol/quality/conviction/age/flip counts/dist) 兩版完全相同 — 100% 同源',
];
function tern(c, a, b) { return (c === null || c === undefined ? false : c) ? a : b; }
function nadd(a, b) { return (a === null || b === null) ? null : a + b; }
function nsub(a, b) { return (a === null || b === null) ? null : a - b; }
function nmul(a, b) { return (a === null || b === null) ? null : a * b; }
function nlt(a, b) { return (a === null || b === null) ? null : a < b; }
function ngt(a, b) { return (a === null || b === null) ? null : a > b; }
/* Pine str.tostring(x, "#.##") / "#.#": 最多 N 位小數,去尾零 */
function fmtDec(x, d) {
if (x === null || x === undefined || !isFinite(x)) return 'na';
let s = x.toFixed(d);
if (s.indexOf('.') >= 0) s = s.replace(/0+$/, '').replace(/\.$/, '');
if (s === '-0') s = '0';
return s;
}
/* Pine math.round: half away from zero */
function pround(x) { return x >= 0 ? Math.floor(x + 0.5) : Math.ceil(x - 0.5); }
function runV4(bars, opts) {
const P = Object.assign({ atrLen: 14, baseFactor: 3.5, erLen: 10, confirmBars: 2, volSmaLen: 50, erEmaLen: 3, rocLen: 5 }, opts || {});
const lang = (opts && opts.lang) || 'zh-source';
const S = (opts && opts.strings) || (lang === 'hk' ? STR_HK : STR);
const n = bars.length;
const O = [], H = [], L = [], C = [];
for (const b of bars) { O.push(b[1]); H.push(b[2]); L.push(b[3]); C.push(b[4]); }
const hl2 = i => (H[i] + L[i]) / 2;
const NA = null;
// ta.true + ta.atr(14) = rma(tr,14): tr[0]=h-l; rma na 至 window 滿 (bar13 seed), 之後 Wilder
const tr = [];
for (let i = 0; i < n; i++) {
tr.push(i === 0 ? H[0] - L[0]
: Math.max(H[i] - L[i], Math.abs(H[i] - C[i - 1]), Math.abs(L[i] - C[i - 1])));
}
const atr = new Array(n).fill(NA);
for (let i = 0; i < n; i++) {
if (i > 0 && atr[i - 1] !== NA) atr[i] = (atr[i - 1] * (P.atrLen - 1) + tr[i]) / P.atrLen;
else if (i >= P.atrLen - 1) { let s = 0; for (let k = i - P.atrLen + 1; k <= i; k++) s += tr[k]; atr[i] = s / P.atrLen; }
else atr[i] = NA;
}
// ER: 棒0..9 total_path=na → false 分支 → er=0.0; er_smooth=ema(er,3) seed=na..bar2
const er = new Array(n);
for (let i = 0; i < n; i++) {
let total = 0, ok = true;
for (let k = 0; k < P.erLen; k++) {
if (i - k - 1 < 0) { ok = false; break; }
total += Math.abs(C[i - k] - C[i - k - 1]);
}
if (!ok) { er[i] = 0.0; continue; }
const net = tern(i - P.erLen >= 0, Math.abs(C[i] - C[i - P.erLen]), NA);
er[i] = tern(total > 0, tern(net !== NA, net / total, NA), 0.0);
}
const erSmooth = new Array(n).fill(NA);
{
const len = P.erEmaLen, a = 2 / (len + 1);
let prev = NA;
for (let i = 0; i < n; i++) {
if (prev !== NA) { erSmooth[i] = a * er[i] + (1 - a) * prev; prev = erSmooth[i]; }
else if (i >= len - 1) {
let s = 0, okw = true;
for (let k = i - len + 1; k <= i; k++) { if (er[k] === NA) { okw = false; break; } s += er[k]; }
if (okw) { erSmooth[i] = s / len; prev = erSmooth[i]; } else erSmooth[i] = NA;
} else erSmooth[i] = NA;
}
}
// vol: atr_baseline=ta.sma(atr,50) (na 至 50 個非 na → bar62); 條件 na→false→1.0
const atrBase = new Array(n).fill(NA);
for (let i = P.volSmaLen - 1; i < n; i++) {
let s = 0, okw = true;
for (let k = i - P.volSmaLen + 1; k <= i; k++) { if (atr[k] === NA) { okw = false; break; } s += atr[k]; }
if (okw) atrBase[i] = s / P.volSmaLen;
}
const volRatio = [], volRegime = [], aFac = [], aConf = [];
for (let i = 0; i < n; i++) {
const base = atrBase[i];
const vr = tern(base !== NA && base > 0, tern(atr[i] !== NA, atr[i] / base, NA), 1.0);
volRatio.push(vr);
volRegime.push(Math.max(Math.min(vr, 1.40), 0.75));
aFac.push(P.baseFactor * volRegime[i]);
const es = erSmooth[i];
aConf.push(
tern(es !== NA && es < 0.25, Math.max(P.confirmBars + 2, 4),
tern(es !== NA && es < 0.45, P.confirmBars + 1,
tern(es !== NA && es < 0.65, P.confirmBars, Math.max(P.confirmBars - 1, 1)))));
}
// manual supertrend (源 90-103)
const upB = new Array(n).fill(NA), loB = new Array(n).fill(NA), dir = new Array(n);
for (let i = 0; i < n; i++) {
const ub = nadd(hl2(i), nmul(aFac[i], atr[i]));
const lb = nsub(hl2(i), nmul(aFac[i], atr[i]));
upB[i] = (i === 0 || upB[i - 1] === NA) ? ub
: tern(tern(nlt(ub, upB[i - 1]), true, ngt(C[i - 1], upB[i - 1])), ub, upB[i - 1]);
loB[i] = (i === 0 || loB[i - 1] === NA) ? lb
: tern(tern(ngt(lb, loB[i - 1]), true, nlt(C[i - 1], loB[i - 1])), lb, loB[i - 1]);
if (i === 0) dir[i] = 1;
else {
const d1 = dir[i - 1];
dir[i] = d1 === 1 ? tern(nlt(C[i], loB[i]), -1, 1) : tern(ngt(C[i], upB[i]), 1, -1);
}
}
const st = [], bull = [];
for (let i = 0; i < n; i++) { st.push(dir[i] === 1 ? loB[i] : upB[i]); bull.push(dir[i] === 1); }
// confirmation filter (源 108-129)
let lockedBull = bull[0], streak = 0;
const flipUp = new Array(n).fill(false), flipDown = new Array(n).fill(false), anyFlip = new Array(n).fill(false);
for (let i = 0; i < n; i++) {
streak = bull[i] === lockedBull ? 0 : streak + 1;
flipUp[i] = streak >= aConf[i] && bull[i];
flipDown[i] = streak >= aConf[i] && !bull[i];
anyFlip[i] = flipUp[i] || flipDown[i];
if (anyFlip[i]) lockedBull = bull[i];
}
// quality (源 77-83) + flip capture (122-129)
const qualityPct = new Array(n), qualityGrade = new Array(n);
for (let i = 0; i < n; i++) {
const roc = i >= P.rocLen ? 100 * (C[i] / C[i - P.rocLen] - 1) : NA;
const priceMomPct = roc === NA ? NA : Math.abs(roc);
const atrPct = tern(C[i] > 0, atr[i] === NA ? NA : atr[i] / C[i] * 100, 0.0);
const momNorm = tern(atrPct !== NA && atrPct > 0,
priceMomPct === NA ? NA : Math.min(priceMomPct / (atrPct * 2), 1.0), 0.0);
const volScore = Math.max(1.0 - Math.abs(1.0 - volRatio[i]), 0.0);
const qr = tern(erSmooth[i] !== NA && momNorm !== NA,
erSmooth[i] * 0.50 + volScore * 0.30 + momNorm * 0.20, NA);
qualityPct[i] = qr === NA ? NA : pround(qr * 100);
qualityGrade[i] = qualityPct[i] === NA ? NA : qualityPct[i] >= 70 ? 'A' : qualityPct[i] >= 50 ? 'B' : 'C';
}
let flipQuality = 0, hasFlipped = false;
const flipGradeOf = () => flipQuality >= 70 ? 'A' : flipQuality >= 50 ? 'B' : 'C';
const labels = [];
let age = 0, bullCt = 0, bearCt = 0;
const ageSeq = [], sSeq = [];
for (let i = 0; i < n; i++) {
if (anyFlip[i]) { flipQuality = qualityPct[i]; hasFlipped = true; }
if (flipUp[i]) bullCt++;
if (flipDown[i]) bearCt++;
age = anyFlip[i] ? 0 : age + 1;
const sTime = Math.min(age / 60.0, 1.0);
const s = tern(erSmooth[i] !== NA, sTime * 0.65 + erSmooth[i] * 0.35, NA);
ageSeq.push(age); sSeq.push(s);
// labels (源 185-189): text 貼源字串
const px = fmtDec(C[i], 2);
if (flipUp[i]) labels.push({ barIndex: i, y: st[i], up: true, text: S.labelLong(qualityGrade[i], px) });
if (flipDown[i]) labels.push({ barIndex: i, y: st[i], up: false, text: S.labelShort(qualityGrade[i], px) });
}
// dashboard @ last bar (源 194-249)
const i = n - 1;
const s = sSeq[i];
const filled = pround(s * 10);
let sbar = '';
for (let k = 0; k < 10; k++) sbar += k < filled ? '█' : '░';
const dist = Math.abs(C[i] - st[i]) / C[i] * 100;
const erLabel = erSmooth[i] > 0.65 ? S.er.trend : erSmooth[i] > 0.40 ? S.er.mixed : S.er.chop;
const volLabel = volRatio[i] > 1.20 ? S.vol.high : volRatio[i] < 0.80 ? S.vol.low : S.vol.normal;
const qText = hasFlipped ? flipQuality + ' / 100 [' + flipGradeOf() + ']' : S.qNone;
const dashboard = {
title: S.dhTitle,
sub: S.dhSub(fmtDec(aFac[i], 2), String(aConf[i])),
rows: [
[S.rowNames[0], lockedBull ? S.dirLong : S.dirShort],
[S.rowNames[1], ageSeq[i] + S.ageUnit],
[S.rowNames[2], sbar + ' ' + pround(s * 100) + '%'],
[S.rowNames[3], erLabel + ' ' + fmtDec(erSmooth[i], 2)],
[S.rowNames[4], volLabel + ' ' + fmtDec(volRatio[i], 2)],
[S.rowNames[5], fmtDec(aFac[i], 2) + ' (基礎 ' + fmtDec(P.baseFactor, 1) + ')'],
[S.rowNames[6], qText],
[S.rowNames[7], fmtDec(dist, 2) + '%'],
[S.rowNames[8], String(bullCt)],
[S.rowNames[9], String(bearCt)],
],
};
const alerts = [];
if (flipUp[i] || flipUp.some(Boolean)) alerts.push({ name: S.alerts.up.name, text: S.alerts.up.text });
if (flipDown.some(Boolean)) alerts.push({ name: S.alerts.down.name, text: S.alerts.down.text });
if (anyFlip.some(Boolean)) alerts.push({ name: S.alerts.any.name, text: S.alerts.any.text });
const last = n - 1;
const lastFlip = labels.length ? labels[labels.length - 1] : null;
let ageFinal = 0;
for (let k = n - 1; k >= 0; k--) { if (anyFlip[k]) break; ageFinal++; }
return {
st, dir, bull, aFac, aConf, erSmooth, volRatio, ageSeq, sSeq,
qualityPct, qualityGrade, flipUp, flipDown, anyFlip, labels,
dashboard, alerts,
latest: {
direction: bull[last] ? 'LONG' : 'SHORT',
directionZh: bull[last] ? '做多' : '做空',
st: st[last], close: C[last], age: ageSeq[last],
convictionPct: pround(sSeq[last] * 100),
erSmooth: erSmooth[last],
erState: erSmooth[last] > 0.65 ? 'TRENDING' : erSmooth[last] > 0.40 ? 'MIXED' : 'CHOPPY',
volRatio: volRatio[last], adaptiveFactor: aFac[last], adaptiveConfirm: aConf[last],
lockedBull, flipQuality, hasFlipped, bullCt, bearCt, dist,
},
};
}
function runSource(bars, opts) { return runV4(bars, Object.assign({}, opts, { lang: 'zh-source' })); }
function runHK(bars, opts) { return runV4(bars, Object.assign({}, opts, { lang: 'hk' })); }
return { runV4, runSource, runHK, STR, STR_HK, STR_DIFFS, fmtDec, pround };
});
/* V4 超級趨勢 v6 — 源輸出相同版 (source-output-identical engine)
* 源: v4-supertrend-zh-v6.txt 16,808B sha256 4d05ef4c07db64570a4c073697507235a4a144e10b47f8c81716b83d79aad1bb (256行)
* 演算法逐行對應源 33-256 行;na 規則: 比較 na→false 分支 (A36 66094 零誤差備註)。
* STR = 源字串表(byte 等於源文本);HK 版僅換 STR,數值引擎共用。
*/
'use strict';
const STR = {
title: '超級趨勢 (自適應版)',
labelLong: (grade, px) => '做多 [' + grade + ']\n' + px,
labelShort: (grade, px) => '做空 [' + grade + ']\n' + px,
dhTitle: '自適應超級趨勢',
dhSub: (af, ac) => '倍數:' + af + ' 確認:' + ac,
rowNames: ['當前方向', '持續K線數', '趨勢強度', '趨勢效率', '波動率狀態', '自適應倍數', '上次訊號品質', '距離趨勢線', '做多訊號次數', '做空訊號次數'],
dirLong: '做多', dirShort: '做空',
ageUnit: ' 根',
er: { trend: '趨勢明顯', mixed: '多空交戰', chop: '震盪洗盤' },
vol: { high: '波動劇烈', low: '波動壓縮', normal: '正常' },
qNone: '尚未出現訊號',
alerts: {
up: { name: '做多訊號', text: '超級趨勢: 做多 — {{ticker}} {{interval}} @ {{close}}' },
down: { name: '做空訊號', text: '超級趨勢: 做空 — {{ticker}} {{interval}} @ {{close}}' },
any: { name: '任何多空翻轉', text: '超級趨勢: 翻轉 — {{ticker}} {{interval}} @ {{close}}' },
},
};
function tern(c, a, b) { return (c === null || c === undefined ? false : c) ? a : b; }
function nadd(a, b) { return (a === null || b === null) ? null : a + b; }
function nsub(a, b) { return (a === null || b === null) ? null : a - b; }
function nmul(a, b) { return (a === null || b === null) ? null : a * b; }
function nlt(a, b) { return (a === null || b === null) ? null : a < b; }
function ngt(a, b) { return (a === null || b === null) ? null : a > b; }
/* Pine str.tostring(x, "#.##") / "#.#": 最多 N 位小數,去尾零 */
function fmtDec(x, d) {
if (x === null || x === undefined || !isFinite(x)) return 'na';
let s = x.toFixed(d);
if (s.indexOf('.') >= 0) s = s.replace(/0+$/, '').replace(/\.$/, '');
if (s === '-0') s = '0';
return s;
}
/* Pine math.round: half away from zero */
function pround(x) { return x >= 0 ? Math.floor(x + 0.5) : Math.ceil(x - 0.5); }
function runV4(bars, opts) {
const P = Object.assign({ atrLen: 14, baseFactor: 3.5, erLen: 10, confirmBars: 2, volSmaLen: 50, erEmaLen: 3, rocLen: 5 }, opts || {});
const S = (opts && opts.strings) || STR;
const n = bars.length;
const O = [], H = [], L = [], C = [];
for (const b of bars) { O.push(b[1]); H.push(b[2]); L.push(b[3]); C.push(b[4]); }
const hl2 = i => (H[i] + L[i]) / 2;
const NA = null;
// ta.true + ta.atr(14) = rma(tr,14): tr[0]=h-l; rma na 至 window 滿 (bar13 seed), 之後 Wilder
const tr = [];
for (let i = 0; i < n; i++) {
tr.push(i === 0 ? H[0] - L[0]
: Math.max(H[i] - L[i], Math.abs(H[i] - C[i - 1]), Math.abs(L[i] - C[i - 1])));
}
const atr = new Array(n).fill(NA);
for (let i = 0; i < n; i++) {
if (i > 0 && atr[i - 1] !== NA) atr[i] = (atr[i - 1] * (P.atrLen - 1) + tr[i]) / P.atrLen;
else if (i >= P.atrLen - 1) { let s = 0; for (let k = i - P.atrLen + 1; k <= i; k++) s += tr[k]; atr[i] = s / P.atrLen; }
else atr[i] = NA;
}
// ER: 棒0..9 total_path=na → false 分支 → er=0.0; er_smooth=ema(er,3) seed=na..bar2
const er = new Array(n);
for (let i = 0; i < n; i++) {
let total = 0, ok = true;
for (let k = 0; k < P.erLen; k++) {
if (i - k - 1 < 0) { ok = false; break; }
total += Math.abs(C[i - k] - C[i - k - 1]);
}
if (!ok) { er[i] = 0.0; continue; }
const net = tern(i - P.erLen >= 0, Math.abs(C[i] - C[i - P.erLen]), NA);
er[i] = tern(total > 0, tern(net !== NA, net / total, NA), 0.0);
}
const erSmooth = new Array(n).fill(NA);
{
const len = P.erEmaLen, a = 2 / (len + 1);
let prev = NA;
for (let i = 0; i < n; i++) {
if (prev !== NA) { erSmooth[i] = a * er[i] + (1 - a) * prev; prev = erSmooth[i]; }
else if (i >= len - 1) {
let s = 0, okw = true;
for (let k = i - len + 1; k <= i; k++) { if (er[k] === NA) { okw = false; break; } s += er[k]; }
if (okw) { erSmooth[i] = s / len; prev = erSmooth[i]; } else erSmooth[i] = NA;
} else erSmooth[i] = NA;
}
}
// vol: atr_baseline=ta.sma(atr,50) (na 至 50 個非 na → bar62); 條件 na→false→1.0
const atrBase = new Array(n).fill(NA);
for (let i = P.volSmaLen - 1; i < n; i++) {
let s = 0, okw = true;
for (let k = i - P.volSmaLen + 1; k <= i; k++) { if (atr[k] === NA) { okw = false; break; } s += atr[k]; }
if (okw) atrBase[i] = s / P.volSmaLen;
}
const volRatio = [], volRegime = [], aFac = [], aConf = [];
for (let i = 0; i < n; i++) {
const base = atrBase[i];
const vr = tern(base !== NA && base > 0, tern(atr[i] !== NA, atr[i] / base, NA), 1.0);
volRatio.push(vr);
volRegime.push(Math.max(Math.min(vr, 1.40), 0.75));
aFac.push(P.baseFactor * volRegime[i]);
const es = erSmooth[i];
aConf.push(
tern(es !== NA && es < 0.25, Math.max(P.confirmBars + 2, 4),
tern(es !== NA && es < 0.45, P.confirmBars + 1,
tern(es !== NA && es < 0.65, P.confirmBars, Math.max(P.confirmBars - 1, 1)))));
}
// manual supertrend (源 90-103)
const upB = new Array(n).fill(NA), loB = new Array(n).fill(NA), dir = new Array(n);
for (let i = 0; i < n; i++) {
const ub = nadd(hl2(i), nmul(aFac[i], atr[i]));
const lb = nsub(hl2(i), nmul(aFac[i], atr[i]));
upB[i] = (i === 0 || upB[i - 1] === NA) ? ub
: tern(tern(nlt(ub, upB[i - 1]), true, ngt(C[i - 1], upB[i - 1])), ub, upB[i - 1]);
loB[i] = (i === 0 || loB[i - 1] === NA) ? lb
: tern(tern(ngt(lb, loB[i - 1]), true, nlt(C[i - 1], loB[i - 1])), lb, loB[i - 1]);
if (i === 0) dir[i] = 1;
else {
const d1 = dir[i - 1];
dir[i] = d1 === 1 ? tern(nlt(C[i], loB[i]), -1, 1) : tern(ngt(C[i], upB[i]), 1, -1);
}
}
const st = [], bull = [];
for (let i = 0; i < n; i++) { st.push(dir[i] === 1 ? loB[i] : upB[i]); bull.push(dir[i] === 1); }
// confirmation filter (源 108-129)
let lockedBull = bull[0], streak = 0;
const flipUp = new Array(n).fill(false), flipDown = new Array(n).fill(false), anyFlip = new Array(n).fill(false);
for (let i = 0; i < n; i++) {
streak = bull[i] === lockedBull ? 0 : streak + 1;
flipUp[i] = streak >= aConf[i] && bull[i];
flipDown[i] = streak >= aConf[i] && !bull[i];
anyFlip[i] = flipUp[i] || flipDown[i];
if (anyFlip[i]) lockedBull = bull[i];
}
// quality (源 77-83) + flip capture (122-129)
const qualityPct = new Array(n), qualityGrade = new Array(n);
for (let i = 0; i < n; i++) {
const roc = i >= P.rocLen ? 100 * (C[i] / C[i - P.rocLen] - 1) : NA;
const priceMomPct = roc === NA ? NA : Math.abs(roc);
const atrPct = tern(C[i] > 0, atr[i] === NA ? NA : atr[i] / C[i] * 100, 0.0);
const momNorm = tern(atrPct !== NA && atrPct > 0,
priceMomPct === NA ? NA : Math.min(priceMomPct / (atrPct * 2), 1.0), 0.0);
const volScore = Math.max(1.0 - Math.abs(1.0 - volRatio[i]), 0.0);
const qr = tern(erSmooth[i] !== NA && momNorm !== NA,
erSmooth[i] * 0.50 + volScore * 0.30 + momNorm * 0.20, NA);
qualityPct[i] = qr === NA ? NA : pround(qr * 100);
qualityGrade[i] = qualityPct[i] === NA ? NA : qualityPct[i] >= 70 ? 'A' : qualityPct[i] >= 50 ? 'B' : 'C';
}
let flipQuality = 0, hasFlipped = false;
const flipGradeOf = () => flipQuality >= 70 ? 'A' : flipQuality >= 50 ? 'B' : 'C';
const labels = [];
let age = 0, bullCt = 0, bearCt = 0;
const ageSeq = [], sSeq = [];
for (let i = 0; i < n; i++) {
if (anyFlip[i]) { flipQuality = qualityPct[i]; hasFlipped = true; }
if (flipUp[i]) bullCt++;
if (flipDown[i]) bearCt++;
age = anyFlip[i] ? 0 : age + 1;
const sTime = Math.min(age / 60.0, 1.0);
const s = tern(erSmooth[i] !== NA, sTime * 0.65 + erSmooth[i] * 0.35, NA);
ageSeq.push(age); sSeq.push(s);
// labels (源 185-189): text 貼源字串
const px = fmtDec(C[i], 2);
if (flipUp[i]) labels.push({ barIndex: i, y: st[i], up: true, text: S.labelLong(qualityGrade[i], px) });
if (flipDown[i]) labels.push({ barIndex: i, y: st[i], up: false, text: S.labelShort(qualityGrade[i], px) });
}
// dashboard @ last bar (源 194-249)
const i = n - 1;
const s = sSeq[i];
const filled = pround(s * 10);
let sbar = '';
for (let k = 0; k < 10; k++) sbar += k < filled ? '█' : '░';
const dist = Math.abs(C[i] - st[i]) / C[i] * 100;
const erLabel = erSmooth[i] > 0.65 ? S.er.trend : erSmooth[i] > 0.40 ? S.er.mixed : S.er.chop;
const volLabel = volRatio[i] > 1.20 ? S.vol.high : volRatio[i] < 0.80 ? S.vol.low : S.vol.normal;
const qText = hasFlipped ? flipQuality + ' / 100 [' + flipGradeOf() + ']' : S.qNone;
const dashboard = {
title: S.dhTitle,
sub: S.dhSub(fmtDec(aFac[i], 2), String(aConf[i])),
rows: [
[S.rowNames[0], lockedBull ? S.dirLong : S.dirShort],
[S.rowNames[1], ageSeq[i] + S.ageUnit],
[S.rowNames[2], sbar + ' ' + pround(s * 100) + '%'],
[S.rowNames[3], erLabel + ' ' + fmtDec(erSmooth[i], 2)],
[S.rowNames[4], volLabel + ' ' + fmtDec(volRatio[i], 2)],
[S.rowNames[5], fmtDec(aFac[i], 2) + ' (基礎 ' + fmtDec(P.baseFactor, 1) + ')'],
[S.rowNames[6], qText],
[S.rowNames[7], fmtDec(dist, 2) + '%'],
[S.rowNames[8], String(bullCt)],
[S.rowNames[9], String(bearCt)],
],
};
const alerts = [];
if (flipUp[i] || flipUp.some(Boolean)) alerts.push({ name: S.alerts.up.name, text: S.alerts.up.text });
if (flipDown.some(Boolean)) alerts.push({ name: S.alerts.down.name, text: S.alerts.down.text });
if (anyFlip.some(Boolean)) alerts.push({ name: S.alerts.any.name, text: S.alerts.any.text });
const last = n - 1;
const lastFlip = labels.length ? labels[labels.length - 1] : null;
let ageFinal = 0;
for (let k = n - 1; k >= 0; k--) { if (anyFlip[k]) break; ageFinal++; }
return {
st, dir, bull, aFac, aConf, erSmooth, volRatio, ageSeq, sSeq,
qualityPct, qualityGrade, flipUp, flipDown, anyFlip, labels,
dashboard, alerts,
latest: {
direction: bull[last] ? 'LONG' : 'SHORT',
directionZh: bull[last] ? '做多' : '做空',
st: st[last], close: C[last], age: ageSeq[last],
convictionPct: pround(sSeq[last] * 100),
erSmooth: erSmooth[last],
erState: erSmooth[last] > 0.65 ? 'TRENDING' : erSmooth[last] > 0.40 ? 'MIXED' : 'CHOPPY',
volRatio: volRatio[last], adaptiveFactor: aFac[last], adaptiveConfirm: aConf[last],
lockedBull, flipQuality, hasFlipped, bullCt, bearCt, dist,
},
};
}
module.exports = { runV4, STR, fmtDec, pround };
if (typeof module !== 'undefined' && require.main === module) {
const fs = require('fs');
const fx = JSON.parse(fs.readFileSync('v4_fixture_300.json', 'utf8'));
const res = runV4(fx.bars, fx.params);
console.log('EXACT-ENGINE loaded, bars=', fx.bars.length, 'labels=', res.labels.length);
}
/* A23 V4 超級趨勢 v6 自測:源輸出相同版 vs A36 300棒 fixture (3fc8ce27) */
'use strict';
const fs = require('fs');
const { runV4, fmtDec, pround } = require('./v4_st_v6_exact.js');
const fx = JSON.parse(fs.readFileSync('v4_fixture_300.json', 'utf8'));
const res = runV4(fx.bars, fx.params);
let pass = 0, fail = 0;
const failures = [];
function chk(name, cond, detail) {
if (cond) pass++;
else { fail++; failures.push(name + ' :: ' + detail); }
}
const close = (a, b, eps) => Math.abs(a - b) <= (eps == null ? 1e-6 : eps);
const E = fx.expected;
// 1) checkpoints
for (const cp of E.expected_checkpoints || []) {
const i = cp.index;
chk(`cp[${i}].st`, close(res.st[i], cp.st, 1e-6), `got ${res.st[i]} want ${cp.st}`);
chk(`cp[${i}].erSmooth`, close(res.erSmooth[i], cp.erSmooth, 1e-9), `got ${res.erSmooth[i]} want ${cp.erSmooth}`);
chk(`cp[${i}].volRatio`, close(res.volRatio[i], cp.volRatio, 1e-9), `got ${res.volRatio[i]} want ${cp.volRatio}`);
chk(`cp[${i}].adaptiveFactor`, close(res.aFac[i], cp.adaptiveFactor, 1e-9), `got ${res.aFac[i]} want ${cp.adaptiveFactor}`);
chk(`cp[${i}].adaptiveConfirm`, res.aConf[i] === cp.adaptiveConfirm, `got ${res.aConf[i]} want ${cp.adaptiveConfirm}`);
chk(`cp[${i}].lockedBull`, res.bull[i] === cp.lockedBull, `got ${res.bull[i]} want ${cp.lockedBull}`);
if (cp.qualityPct !== undefined) chk(`cp[${i}].qualityPct`, res.qualityPct[i] === cp.qualityPct, `got ${res.qualityPct[i]} want ${cp.qualityPct}`);
if (cp.qualityGrade !== undefined) chk(`cp[${i}].qualityGrade`, res.qualityGrade[i] === cp.qualityGrade, `got ${res.qualityGrade[i]} want ${cp.qualityGrade}`);
if (cp.s !== undefined) chk(`cp[${i}].s`, close(res.sSeq[i], cp.s, 1e-9), `got ${res.sSeq[i]} want ${cp.s}`);
if (cp.age !== undefined) chk(`cp[${i}].age`, res.ageSeq[i] === cp.age, `got ${res.ageSeq[i]} want ${cp.age}`);
}
// 2) labels
const wantLabels = E.expected_labels || [];
chk('labels.count', res.labels.length === wantLabels.length, `got ${res.labels.length} want ${wantLabels.length}`);
for (let k = 0; k < Math.min(res.labels.length, wantLabels.length); k++) {
const g = res.labels[k], w = wantLabels[k];
chk(`label[${k}].barIndex`, g.barIndex === w.barIndex, `got ${g.barIndex} want ${w.barIndex}`);
const wUp = w.direction === 'LONG';
chk(`label[${k}].up`, g.up === wUp, `got ${g.up} want ${wUp}`);
if (w.y !== undefined) chk(`label[${k}].y`, close(g.y, w.y, 1e-6), `got ${g.y} want ${w.y}`);
if (w.close !== undefined) chk(`label[${k}].close`, g.text.includes(Number(w.close).toFixed(2)), `text=${JSON.stringify(g.text)} close=${w.close}`);
if (w.grade !== undefined) chk(`label[${k}].grade`, g.text.includes('[' + w.grade + ']'), `text=${JSON.stringify(g.text)} grade=${w.grade}`);
if (w.quality !== undefined) {
const q = res.qualityPct[g.barIndex];
chk(`label[${k}].quality`, q === w.quality, `got ${q} want ${w.quality}`);
}
}
// 3) latest
const el = E.expected_latest, L = res.latest;
if (el) {
chk('latest.direction', L.direction === el.direction, `got ${L.direction} want ${el.direction}`);
if (el.directionZh) chk('latest.directionZh', L.directionZh === el.directionZh, `got ${L.directionZh} want ${el.directionZh}`);
if (el.st !== undefined) chk('latest.st', close(L.st, el.st, 1e-6), `got ${L.st} want ${el.st}`);
if (el.close !== undefined) chk('latest.close', close(L.close, el.close, 1e-9), `got ${L.close} want ${el.close}`);
if (el.age !== undefined) chk('latest.age', L.age === el.age, `got ${L.age} want ${el.age}`);
if (el.convictionPct !== undefined) chk('latest.convictionPct', L.convictionPct === el.convictionPct, `got ${L.convictionPct} want ${el.convictionPct}`);
if (el.erSmooth !== undefined) chk('latest.erSmooth', close(L.erSmooth, el.erSmooth, 1e-9), `got ${L.erSmooth} want ${el.erSmooth}`);
if (el.erState !== undefined) chk('latest.erState', L.erState === el.erState, `got ${L.erState} want ${el.erState}`);
if (el.volRatio !== undefined) chk('latest.volRatio', close(L.volRatio, el.volRatio, 1e-9), `got ${L.volRatio} want ${el.volRatio}`);
if (el.adaptiveFactor !== undefined) chk('latest.adaptiveFactor', close(L.adaptiveFactor, el.adaptiveFactor, 1e-9), `got ${L.adaptiveFactor} want ${el.adaptiveFactor}`);
if (el.adaptiveConfirm !== undefined) chk('latest.adaptiveConfirm', L.adaptiveConfirm === el.adaptiveConfirm, `got ${L.adaptiveConfirm} want ${el.adaptiveConfirm}`);
if (el.hasFlipped !== undefined) chk('latest.hasFlipped', L.hasFlipped === el.hasFlipped, `got ${L.hasFlipped} want ${el.hasFlipped}`);
if (el.flipQuality !== undefined) chk('latest.flipQuality', L.flipQuality === el.flipQuality, `got ${L.flipQuality} want ${el.flipQuality}`);
if (el.bullFlips !== undefined) chk('latest.bullFlips', L.bullCt === el.bullFlips, `got ${L.bullCt} want ${el.bullFlips}`);
if (el.bearFlips !== undefined) chk('latest.bearFlips', L.bearCt === el.bearFlips, `got ${L.bearCt} want ${el.bearFlips}`);
if (el.distancePct !== undefined) chk('latest.distancePct', close(L.dist, el.distancePct, 1e-6), `got ${L.dist} want ${el.distancePct}`);
}
// 4) dashboard rows — 數值比對為主(label 文案屬版本差異,另列)
const wantRows = E.expected_dashboard_rows || [];
const gotRows = res.dashboard.rows;
chk('dash.rows.count', gotRows.length + 1 === wantRows.length || gotRows.length === wantRows.length, `got ${gotRows.length}+1 vs ${wantRows.length}`);
for (const wr of wantRows) {
if (wr.row === 0) {
const sub = res.dashboard.sub;
const mF = /倍數:([\d.]+)/.exec(sub), mC = /確認:(\d+)/.exec(sub);
const wfv = parseFloat((wr.valueZh.match(/乘數:([\d.]+)/) || wr.valueEn.match(/F:([\d.]+)/))[1]);
const wcv = parseInt((wr.valueZh.match(/確認:(\d+)/) || wr.valueEn.match(/C:(\d+)/))[1], 10);
chk('dash.header.F', close(parseFloat(mF[1]), wfv, 5e-3), `got ${mF[1]} want ${wfv}`);
chk('dash.header.C', parseInt(mC[1], 10) === wcv, `got ${mC[1]} want ${wcv}`);
continue;
}
const g = gotRows[wr.row - 1];
if (!g) { chk(`dash.row${wr.row}`, false, 'missing'); continue; }
const gv = g[1], wv = wr.valueZh || wr.valueEn || '';
const gNums = (gv.match(/-?\d+(\.\d+)?/g) || []).map(Number);
const wNums = (wv.match(/-?\d+(\.\d+)?/g) || []).map(Number);
if (wNums.length && gNums.length) {
// 文本 % bar 等有格式差,數值全等/近等
const same = gNums.length === wNums.length && gNums.every((x, idx) => Math.abs(x - wNums[idx]) <= Math.max(1e-6, Math.abs(wNums[idx]) * 1e-6));
chk(`dash.row${wr.row}.nums`, same, `got ${gv} want ${wv}`);
} else {
chk(`dash.row${wr.row}.txt`, gv === wv || gv.includes(wv) || wv.includes(gv), `got ${gv} want ${wv}`);
}
}
console.log(JSON.stringify({ pass, fail, failures: failures.slice(0, 50), total: pass + fail }, null, 2));
if (fail) process.exit(1);
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TheRealDrip2Rip
// Translated to Traditional Chinese
//@version=6
indicator("超級趨勢 (自適應版)", overlay=true, max_labels_count=500)
// ═══════════════════════════════════════════════════════════════
// 輸入設定 (INPUTS)
// ═══════════════════════════════════════════════════════════════
g1 = "計算核心"
i_len = input.int (14, "ATR 週期", minval=1, group=g1)
i_factor = input.float(3.5, "基礎倍數", step=0.1, minval=1, group=g1, tooltip="基礎乘數。會根據即時的波動率狀態自動進行縮放。")
i_er_len = input.int (10, "ER 週期", minval=3, maxval=20, group=g1, tooltip="考夫曼效率係數(Kaufman ER)回溯期。用於衡量價格是處於單邊趨勢還是震盪洗盤。")
i_confirm = input.int (2, "確認K線數 (基礎)", minval=1, maxval=5, group=g1, tooltip="基礎確認K線數。當 ER 低(震盪洗盤)時會自動增加以過濾雜訊,當 ER 高(明顯趨勢)時會自動減少。")
g2 = "視覺設定"
i_glow = input.bool(true, "發光光暈", group=g2)
i_shade = input.bool(true, "漸層背景", group=g2)
i_candles = input.bool(true, "K線著色", group=g2)
i_labels = input.bool(true, "多空訊號標籤", group=g2)
i_table = input.bool(true, "數據看板", group=g2)
g3 = "顏色設定"
i_bull = input.color(#26a69a, "做多 (Bull)", group=g3)
i_bear = input.color(#ef5350, "做空 (Bear)", group=g3)
g4 = "數據看板"
i_pos = input.string("右上", "顯示位置", options=["右上","左上","右下","左下"], group=g4)
// ═══════════════════════════════════════════════════════════════
// 自適應層 (ADAPTIVE LAYER)
// ═══════════════════════════════════════════════════════════════
atr = ta.atr(i_len)
// ── 1. 考夫曼效率係數 (KAUFMAN EFFICIENCY RATIO) ──────────────────
// 淨價格位移 除以 總行走距離。
// 完美的單邊趨勢得分為 1.0。
// 上衝下洗但原地踏步的市場得分接近 0.0。
net_move = math.abs(close - close[i_er_len])
var float total_path = 0.0
total_path := 0.0
for i = 0 to i_er_len - 1
total_path += math.abs(close[i] - close[i + 1])
er = total_path > 0 ? net_move / total_path : 0.0
er_smooth = ta.ema(er, 3)
// ── 2. 波動率狀態 (VOLATILITY REGIME) ────────────────────────
// 當前 ATR 與其 50 根 K 線平均基準的比例。
// > 1.2 : 波動劇烈,乘數放大
// < 0.8 : 波動壓縮,乘數縮小
// 將比例限制在 0.75 - 1.40 之間,用於縮放下方的乘數。
atr_baseline = ta.sma(atr, 50)
vol_ratio = atr_baseline > 0 ? atr / atr_baseline : 1.0
vol_regime = math.max(math.min(vol_ratio, 1.40), 0.75)
// ── 3. 自適應乘數 (ADAPTIVE FACTOR) ──────────────────────────
// 超級趨勢的乘數由波動率狀態來決定縮放。
// 當波動率升高時,軌道變寬;當波動率受到壓縮時,軌道收緊。
adaptive_factor = i_factor * vol_regime
// ── 4. ER驅動的自適應確認機制 (ER-DRIVEN ADAPTIVE CONFIRMATION) ──
// 低 ER (震盪):在確認反轉之前需要更多根K線。
// 高 ER (趨勢):需要較少根K線。
adaptive_confirm = er_smooth < 0.25 ? math.max(i_confirm + 2, 4) :
er_smooth < 0.45 ? i_confirm + 1 :
er_smooth < 0.65 ? i_confirm :
math.max(i_confirm - 1, 1)
// ── 5. 反轉訊號品質評分 (0–100) ──────────────────────────────
// 在每次多空翻轉時計算。包含三個加權組件:
// 50% — 效率 (ER): 市場真的在走趨勢嗎?
// 30% — 波動率正常度: 波動率是否處於健康範圍? (在 vol_ratio=1.0 時達峰值,極端時下降)
// 20% — 5根K線動能: 翻轉時價格是否真的在移動?
//
// 分數越高表示翻轉發生在越乾淨的市場條件下。
// 等級:A = 70分及以上,B = 50到69分,C = 50分以下。
price_mom_pct = math.abs(ta.roc(close, 5))
atr_pct = close > 0 ? atr / close * 100 : 0.0
mom_norm = atr_pct > 0 ? math.min(price_mom_pct / (atr_pct * 2), 1.0) : 0.0
vol_score = math.max(1.0 - math.abs(1.0 - vol_ratio), 0.0)
quality_raw = er_smooth * 0.50 + vol_score * 0.30 + mom_norm * 0.20
quality_pct = math.round(quality_raw * 100)
quality_grade = quality_pct >= 70 ? "A" :quality_pct >= 50 ? "B" : "C"
// ═══════════════════════════════════════════════════════════════
// 手動計算超級趨勢 (配合自適應乘數)
// 因為 ta.supertrend() 只接受簡單的浮點數,所以我們手動
// 實現相同的演算法,以接收我們的動態時間序列乘數。
// ═══════════════════════════════════════════════════════════════
upper_basic = hl2 + adaptive_factor * atr
lower_basic = hl2 - adaptive_factor * atr
var float upper_band = na
var float lower_band = na
upper_band := na(upper_band[1]) ? upper_basic : (upper_basic < upper_band[1] or close[1] > upper_band[1] ? upper_basic : upper_band[1])
lower_band := na(lower_band[1]) ? lower_basic : (lower_basic > lower_band[1] or close[1] < lower_band[1] ? lower_basic : lower_band[1])
var int trend_dir = 1
trend_dir := na(trend_dir[1]) ? 1 : trend_dir[1] == 1 ? (close < lower_band ? -1 : 1) :(close > upper_band ? 1 : -1)
st = trend_dir == 1 ? lower_band : upper_band
bull = trend_dir == 1
// ═══════════════════════════════════════════════════════════════
// 確認過濾器 (CONFIRMATION FILTER)
// ═══════════════════════════════════════════════════════════════
var bool locked_bull = bull
var int streak = 0
streak := bull == locked_bull ? 0 : 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 = locked_bull ? i_bull : i_bear
// 在多空翻轉瞬間捕捉品質分數,供數據看板使用
var int flip_quality = 0
var bool has_flipped = false
if any_flip
flip_quality := quality_pct
has_flipped := true
flip_grade = flip_quality >= 70 ? "A" : flip_quality >= 50 ? "B" : "C"
// ═══════════════════════════════════════════════════════════════
// 趨勢強度/確信度 (CONVICTION)
// 融合了時間(K線數)和效率(ER),因此一個 30 根 K 線的乾淨趨勢
// 得分會高過一個 60 根 K 線的震盪洗盤。兩個維度都很重要。
// ═══════════════════════════════════════════════════════════════
var int age = 0
age := any_flip ? 0 : age + 1
s_time = math.min(age / 60.0, 1.0)
s = s_time * 0.65 + er_smooth * 0.35
var int bull_ct = 0
var int bear_ct = 0
if flip_up
bull_ct += 1
if flip_down
bear_ct += 1
// ═══════════════════════════════════════════════════════════════
// 光暈與線條 (GLOW + LINE)
// ═══════════════════════════════════════════════════════════════
// 堆疊三層線條,最寬也最淡的在最下面,讓線條帶有柔和的光暈效果。
plot(i_glow ? st : na, "外圍光暈", color.new(tc, 90), linewidth=12, editable=false)
plot(i_glow ? st : na, "中間光暈", color.new(tc, 82), linewidth=7, editable=false)
plot(i_glow ? st : na, "內部光暈", color.new(tc, 68), linewidth=4, editable=false)
plot(st, "超級趨勢線", tc, linewidth=2)
// ═══════════════════════════════════════════════════════════════
// 漸層著色背景 (GRADIENT SHADING)
// 連續的漸層:靠近超級趨勢線處顏色最深,到價格處漸隱為透明。
// 趨勢確信度越高,線條處的顏色越深。
// ═══════════════════════════════════════════════════════════════
boost = int(s * 30)
c_line = color.new(tc, math.max(60 - boost, 28))
c_price = color.new(tc, 100)
st_on_top = st >= close
top_val = math.max(st, close)
bot_val = math.min(st, close)
p_close = plot(close, display=display.none, editable=false)
p_st = plot(st, display=display.none, editable=false)
fill(p_close, p_st, i_shade ? top_val : na, i_shade ? bot_val : na, st_on_top ? c_line : c_price, st_on_top ? c_price : c_line, title="漸層背景")
// ═══════════════════════════════════════════════════════════════
// K線著色 (CANDLES)
// ═══════════════════════════════════════════════════════════════
barcolor(i_candles ? color.new(tc, 22) : na)
// ═══════════════════════════════════════════════════════════════
// 反轉訊號標籤 (FLIP LABELS)
// 顯示方向、品質等級以及當前價格。
// ═══════════════════════════════════════════════════════════════
if i_labels and flip_up
label.new(bar_index, st, text = "做多 [" + quality_grade + "]\n" + str.tostring(close, format.mintick), yloc = yloc.belowbar, style = label.style_label_up,color = color.new(i_bull, 8), textcolor = color.white, size = size.small)
if i_labels and flip_down
label.new(bar_index, st, text = "做空 [" + quality_grade + "]\n" + str.tostring(close, format.mintick), yloc = yloc.abovebar,style = label.style_label_down, color = color.new(i_bear, 8), textcolor = color.white,size = size.small)
// ═══════════════════════════════════════════════════════════════
// 數據看板 (DASHBOARD)
// ═══════════════════════════════════════════════════════════════
if i_table and barstate.islast
pos = i_pos == "右上" ? position.top_right :
i_pos == "左上" ? position.top_left :
i_pos == "右下" ? position.bottom_right :
position.bottom_left
int filled = int(math.round(s * 10))
string sbar = ""
for i = 0 to 9
sbar += i < filled ? "█" : "░"
dist = math.abs(close - st) / close * 100
er_label = er_smooth > 0.65 ? "趨勢明顯" : er_smooth > 0.40 ? "多空交戰" : "震盪洗盤"
er_color = er_smooth > 0.65 ? tc : er_smooth > 0.40 ? color.orange : color.gray
vol_label = vol_ratio > 1.20 ? "波動劇烈" : vol_ratio < 0.80 ? "波動壓縮" : "正常"
vol_color = vol_ratio > 1.20 ? color.orange : vol_ratio < 0.80 ? color.aqua : color.silver
q_color = not has_flipped ? color.gray : flip_quality >= 70 ? tc : flip_quality >= 50 ? color.orange : color.gray
q_text = has_flipped ? str.tostring(flip_quality) + " / 100 [" + flip_grade + "]" : "尚未出現訊號"
t = table.new(pos, 2, 11,bgcolor = color.new(#080808, 5),border_color = color.new(tc, 52), border_width = 1,frame_color = color.new(tc, 22),frame_width = 2)
table.cell(t, 0, 0, "自適應超級趨勢", text_color=color.white, text_size=size.small, bgcolor=color.new(tc, 42), text_halign=text.align_center)
table.cell(t, 1, 0, "倍數:" + str.tostring(adaptive_factor, "#.##") + " 確認:" + str.tostring(adaptive_confirm),text_color=color.silver, text_size=size.small,bgcolor=color.new(tc, 42), text_halign=text.align_center)
table.cell(t, 0, 1, "當前方向", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 1, locked_bull ? "做多" : "做空",text_color=tc, text_size=size.small, text_halign=text.align_center, bgcolor=color.new(tc, 85))
table.cell(t, 0, 2, "持續K線數", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 2, str.tostring(age) + " 根",text_color=color.silver, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 3, "趨勢強度", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 3, sbar + " " + str.tostring(math.round(s * 100)) + "%", text_color=s > 0.5 ? tc : color.gray,text_size=size.tiny, text_halign=text.align_center)
table.cell(t, 0, 4, "趨勢效率", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 4, er_label + " " + str.tostring(er_smooth, "#.##"),text_color=er_color, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 5, "波動率狀態", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 5, vol_label + " " + str.tostring(vol_ratio, "#.##"),text_color=vol_color, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 6, "自適應倍數",text_color=color.gray, text_size=size.small)
table.cell(t, 1, 6, str.tostring(adaptive_factor, "#.##") + " (基礎 " + str.tostring(i_factor, "#.#") + ")",text_color=color.silver, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 7, "上次訊號品質", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 7, q_text, text_color=q_color, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 8, "距離趨勢線", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 8, str.tostring(dist, "#.##") + "%", text_color=dist > 3.0 ? color.orange : color.silver, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 9, "做多訊號次數", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 9, str.tostring(bull_ct), text_color=i_bull, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 10, "做空訊號次數", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 10, str.tostring(bear_ct),text_color=i_bear, text_size=size.small, text_halign=text.align_center)
// ═══════════════════════════════════════════════════════════════
// 警報設定 (ALERTS)
// ═══════════════════════════════════════════════════════════════
alertcondition(flip_up, "做多訊號", "超級趨勢: 做多 — {{ticker}} {{interval}} @ {{close}}")
alertcondition(flip_down, "做空訊號", "超級趨勢: 做空 — {{ticker}} {{interval}} @ {{close}}")
alertcondition(any_flip, "任何多空翻轉", "超級趨勢: 翻轉 — {{ticker}} {{interval}} @ {{close}}")
本頁零憑證。A23 · A233804 · file: A23_V4_SUPERTREND_ZH_V6.html · fixture credit: A36 3fc8ce27 / A15 交叉對數。