A23 · V4 指標精準轉換交付

源檔:v4-indicator-source.txt · 5587 B · sha256 b8a0e2e1c934e3f1a05c4c6ff27f12ab2a5e277d8db227aecb85c7fb5ab3b358
轉換日期:2026-11-23 05:58:11 · 席位:A233804(A23) · 指令:66057【主人令|V4 指標】
源結構:56 行 = FLIP LABELS(5–8)+ DASHBOARD(12–50)+ ALERTS(54–56);核心 st / flip_up / flip_down / quality_grade 等計算未包含於源片段
交付內容:① V4 指標 JS 模組(富途 FTNN 页面 + server.js Node 雙環境可用); ② 同一 script 內容 的 Kline 圖渲染版(Canvas,中文提示)。 做之前已讀完整份 code(上附源全文),唔靠估:源未定義的狀態 key 一律走輸入介面, evaluate() 缺 key 即拋錯列出清單;stdCore() 標準 ATR SuperTrend 明確標注為可替換預設,非源作者參數。

0. 源全文(v4-indicator-source.txt,已核 sha)

══════════════════════════════════════════════════
// FLIP LABELS
// Shows direction, quality grade, and price.
// ═══════════════════════════════════════════════════════════════
if i_labels and flip_up
label.new(bar_index, st, text = "LONG [" + 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 = "SHORT [" + 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 == "Top Right" ? position.top_right :
i_pos == "Top Left" ? position.top_left :
i_pos == "Bottom Right" ? 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 ? "TRENDING" : er_smooth > 0.40 ? "MIXED" : "CHOPPY"
er_color = er_smooth > 0.65 ? tc : er_smooth > 0.40 ? color.orange : color.gray
vol_label = vol_ratio > 1.20 ? "ELEVATED" : vol_ratio < 0.80 ? "COMPRESSED" : "NORMAL"
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 + "]" : "no flip yet"
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, "SUPERTREND", text_color=color.white, text_size=size.small, bgcolor=color.new(tc, 42), text_halign=text.align_center)
table.cell(t, 1, 0, "F:" + str.tostring(adaptive_factor, "#.##") + " C:" + 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, "Direction", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 1, locked_bull ? "LONG" : "SHORT",text_color=tc, text_size=size.small, text_halign=text.align_center, bgcolor=color.new(tc, 85))
table.cell(t, 0, 2, "Age", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 2, str.tostring(age) + " bars",text_color=color.silver, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 3, "Conviction", 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, "Efficiency", 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, "Vol Regime", 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, "Adapt Factor",text_color=color.gray, text_size=size.small)
table.cell(t, 1, 6, str.tostring(adaptive_factor, "#.##") + " (base " + str.tostring(i_factor, "#.#") + ")",text_color=color.silver, text_size=size.small, text_halign=text.align_center)
table.cell(t, 0, 7, "Last Flip", 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, "Distance", 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, "Long Flips", 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, "Short Flips", 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, "Long Signal", "SuperTrend: LONG — {{ticker}} {{interval}} @ {{close}}")
alertcondition(flip_down, "Short Signal", "SuperTrend: SHORT — {{ticker}} {{interval}} @ {{close}}")
alertcondition(any_flip, "Any Flip", "SuperTrend: FLIP — {{ticker}} {{interval}} @ {{close}}")

① V4 指標(FTNN + server.js)— v4_indicator.js

UMD:Node require('./v4_indicator.js');FTNN 页面 window.V4Indicator。

/* V4 指標 — SuperTrend flip labels / dashboard / alerts
 * 源: v4-indicator-source.txt 5587B sha256 b8a0e2e1c934e3f1a05c4c6ff27f12ab2a5e277d8db227aecb85c7fb5ab3b358
 * 精準轉換:源檔僅 FLIP LABELS / DASHBOARD / ALERTS 三段(56行),未含 st/flip 核心計算。
 * 不靠估:核心以 state 輸入承接;stdCore() 只是可替換的標準 ATR SuperTrend 預設。
 * 雙環境:Node module.exports / 瀏覽器 window.V4Indicator
 */
(function (root, factory) {
  if (typeof module === 'object' && module.exports) module.exports = factory();
  else root.V4Indicator = factory();
})(typeof self !== 'undefined' ? self : this, function () {
  'use strict';

  function fmtTick(v, mintick) {
    if (v == null) return '';
    var m = mintick || 0.01;
    var d = Math.max(0, Math.ceil(-Math.log10(m)));
    return Number(v).toFixed(d);
  }
  function r(v, d) { return Math.round(v * Math.pow(10, d)) / Math.pow(10, d); }

  /* ---- FLIP LABELS(源 5-8 行精準對應) ---- */
  function buildFlipLabels(state, opts) {
    opts = opts || {};
    var iLabels = opts.i_labels !== false;
    var out = [];
    if (iLabels && state.flip_up) out.push({
      loc: 'belowbar', style: 'label_up', bar: state.bar_index, price: state.close,
      color: state.i_bull, text: 'LONG [' + state.quality_grade + ']\n' + fmtTick(state.close, state.mintick)
    });
    if (iLabels && state.flip_down) out.push({
      loc: 'abovebar', style: 'label_down', bar: state.bar_index, price: state.close,
      color: state.i_bbear || state.i_bear, text: 'SHORT [' + state.quality_grade + ']\n' + fmtTick(state.close, state.mintick)
    });
    return out;
  }

  /* ---- DASHBOARD(源 12-50 行精準對應;只在最新bar) ---- */
  function buildDashboard(state) {
    var s = state.s, dist = Math.abs(state.close - state.st) / state.close * 100;
    var filled = Math.round(s * 10), sbar = '';
    for (var i = 0; i < 10; i++) sbar += i < filled ? '█' : '░';
    var erLabel = state.er_smooth > 0.65 ? 'TRENDING' : state.er_smooth > 0.40 ? 'MIXED' : 'CHOPPY';
    var volLabel = state.vol_ratio > 1.20 ? 'ELEVATED' : state.vol_ratio < 0.80 ? 'COMPRESSED' : 'NORMAL';
    var qText = state.has_flipped ? r(state.flip_quality, 0) + ' / 100 [' + state.flip_grade + ']' : 'no flip yet';
    return {
      title: 'SUPERTREND',
      sub: 'F:' + r(state.adaptive_factor, 2) + ' C:' + state.adaptive_confirm,
      rows: [
        ['Direction', state.locked_bull ? 'LONG' : 'SHORT'],
        ['Age', state.age + ' bars'],
        ['Conviction', sbar + ' ' + Math.round(s * 100) + '%'],
        ['Efficiency', erLabel + ' ' + r(state.er_smooth, 2)],
        ['Vol Regime', volLabel + ' ' + r(state.vol_ratio, 2)],
        ['Adapt Factor', r(state.adaptive_factor, 2) + ' (base ' + r(state.i_factor, 1) + ')'],
        ['Last Flip', qText],
        ['Distance', r(dist, 2) + '%'],
        ['Long Flips', state.bull_ct],
        ['Short Flips', state.bear_ct]
      ],
      dist: dist, erLabel: erLabel, volLabel: volLabel, sbar: sbar
    };
  }

  /* ---- ALERTS(源 54-56 行精準對應) ---- */
  function alertConditions(state, meta) {
    meta = meta || {};
    var tk = meta.ticker || '{{ticker}}', iv = meta.interval || '{{interval}}', cl = fmtTick(state.close, state.mintick);
    var out = [];
    if (state.flip_up) out.push({ name: 'Long Signal', text: 'SuperTrend: LONG — ' + tk + ' ' + iv + ' @ ' + cl });
    if (state.flip_down) out.push({ name: 'Short Signal', text: 'SuperTrend: SHORT — ' + tk + ' ' + iv + ' @ ' + cl });
    if (state.flip_up || state.flip_down) out.push({ name: 'Any Flip', text: 'SuperTrend: FLIP — ' + tk + ' ' + iv + ' @ ' + cl });
    return out;
  }

  var REQUIRED = ['close','bar_index','st','flip_up','flip_down','locked_bull','age','s','er_smooth',
    'vol_ratio','adaptive_factor','adaptive_confirm','i_factor','has_flipped','flip_quality','flip_grade',
    'quality_grade','bull_ct','bear_ct'];

  /* 完整 state 校驗:缺 key 直接報錯,唔靠估 */
  function evaluate(state) {
    var miss = REQUIRED.filter(function (k) { return state[k] === undefined; });
    if (miss.length) throw new Error('V4 state missing keys: ' + miss.join(','));
    return { labels: buildFlipLabels(state), dashboard: buildDashboard(state), alerts: alertConditions(state) };
  }

  /* 可替換預設核心:標準 ATR SuperTrend(factor=3, period=10)。
     源檔未含核心計算——拿到完整源後整段替換,唔好當佢係原作者參數。 */
  function stdCore(candles, opts) {
    opts = opts || {};
    var F = opts.factor == null ? 3 : opts.factor, P = opts.period == null ? 10 : opts.period;
    var n = candles.length, tr = [], atr = [];
    for (var i = 0; i < n; i++) {
      var c = candles[i], h = c.h, l = c.l, pc = i ? candles[i - 1].c : c.c;
      tr.push(Math.max(h - l, Math.abs(h - pc), Math.abs(l - pc)));
    }
    atr[0] = tr[0];
    for (var i2 = 1; i2 < n; i2++) atr[i2] = (atr[i2 - 1] * (P - 1) + tr[i2]) / P;
    var st = [], dir = [], up = true, bull = 0, bear = 0, flips = [];
    var hl2 = function (i) { return (candles[i].h + candles[i].l) / 2; };
    for (var j = 0; j < n; j++) {
      var basic = hl2(j) - F * atr[j], basicU = hl2(j) + F * atr[j];
      if (j === 0) { st[j] = basicU; dir[j] = 1; }
      else {
        var prevSt = st[j - 1];
        var newSt = up ? Math.max(basic, prevSt) : Math.min(basicU, prevSt);
        if (candles[j].c > basicU) up = true;
        else if (candles[j].c < basic) up = false;
        st[j] = newSt; dir[j] = up ? 1 : -1;
      }
      if (j && dir[j] !== dir[j - 1]) {
        flips.push({ bar: j, up: dir[j] === 1 });
        if (dir[j] === 1) bull++; else bear++;
      }
    }
    var last = n - 1, lastFlip = null;
    for (var k = flips.length - 1; k >= 0; k--) { lastFlip = flips[k]; break; }
    return {
      st: st[last], flip_up: !!(lastFlip && lastFlip.up && lastFlip.bar === last),
      flip_down: !!(lastFlip && !lastFlip.up && lastFlip.bar === last),
      locked_bull: dir[last] === 1, age: lastFlip ? last - lastFlip.bar : last,
      bull_ct: bull, bear_ct: bear, close: candles[last].c, bar_index: last,
      _st_series: st, _dir_series: dir, _flips: flips
    };
  }

  /* 由 K 線 + 外部指標狀態合成 evaluate() 輸入;缺 extras 即拋錯(唔靠估) */
  function fromCandles(candles, extras) {
    var core = stdCore(candles, extras && extras.core);
    var need = ['s','er_smooth','vol_ratio','adaptive_factor','adaptive_confirm','i_factor',
      'has_flipped','flip_quality','flip_grade','quality_grade'];
    var miss = need.filter(function (k) { return !extras || extras[k] === undefined; });
    if (miss.length) throw new Error('V4 extras missing (source fragment does not define them): ' + miss.join(','));
    var stt = Object.assign({}, core);
    need.forEach(function (k) { stt[k] = extras[k]; });
    stt.mintick = (extras && extras.mintick) || 0.01;
    return evaluate(stt);
  }

  return {
    buildFlipLabels: buildFlipLabels, buildDashboard: buildDashboard,
    alertConditions: alertConditions, evaluate: evaluate,
    stdCore: stdCore, fromCandles: fromCandles, REQUIRED: REQUIRED
  };
});

② Kline 圖中文提示版 — v4_kline_cn.js

V4KlineCN.drawKline(canvas, candles, state, opts):K 線+SuperTrend 線+▲▼ 翻轉箭頭(做多/做空)+中文儀表板(方向/持倉/信心/效率/量能/自適應/上次翻轉/距離/多頭翻轉/空頭翻轉)+底部中文警報提示(超級趨勢:做多/做空/翻轉)。

/* V4 指標 Kline 圖(中文提示)— 同一 script 內容轉 K 線圖渲染
 * 源: v4-indicator-source.txt 5587B sha256 b8a0e2e1…(labels/dashboard/alerts 三段)
 * 用法: drawKline(canvas, candles, state, opts) — state 由 V4Indicator.stdCore+extras 合成
 * 中文提示: 翻轉/警報/儀表板全部中文文案;數值與源 script 一致。
 */
(function (root, factory) {
  if (typeof module === 'object' && module.exports) module.exports = factory();
  else root.V4KlineCN = factory();
})(typeof self !== 'undefined' ? self : this, function () {
  'use strict';

  var CN = {
    title: 'V4 指標 · K 線圖',
    long: '做多', short: '做空',
    rows: ['方向', '持倉', '信心', '效率', '量能', '自適應', '上次翻轉', '距離', '多頭翻轉', '空頭翻轉'],
    bars: '根K線', pct: '%',
    er: { TRENDING: '趨勢中', MIXED: '混合', CHOPPY: '震盪' },
    vol: { ELEVATED: '放量', COMPRESSED: '縮量', NORMAL: '正常' },
    noFlip: '尚未翻轉',
    alerts: {
      'Long Signal': function (t) { return '超級趨勢:做多 — ' + t; },
      'Short Signal': function (t) { return '超級趨勢:做空 — ' + t; },
      'Any Flip': function (t) { return '超級趨勢:翻轉 — ' + t; }
    },
    tipLong: function (q, p) { return '做多 [' + q + '] @ ' + p; },
    tipShort: function (q, p) { return '做空 [' + q + '] @ ' + p; }
  };

  function fmt(v, d) { return Number(v).toFixed(d == null ? 2 : d); }

  /* 由 V4 dashboard(英文)映射中文行 */
  function cnDashboard(dash) {
    var map = [dash.rows[0][1], dash.rows[1][1], dash.rows[2][1],
      CN.er[dash.erLabel] + ' ' + fmt(parseFloat(dash.rows[3][1].split(' ').pop())),
      CN.vol[dash.volLabel] + ' ' + fmt(parseFloat(dash.rows[4][1].split(' ').pop())),
      dash.rows[5][1],
      dash.has_flipped === false ? CN.noFlip : dash.rows[6][1],
      dash.rows[7][1], dash.rows[8][1], dash.rows[9][1]];
    return CN.rows.map(function (k, i) { return [k, map[i]]; });
  }

  /* 中文警報文案(同源 alertcondition 規則) */
  function cnAlerts(state, meta) {
    meta = meta || {};
    var tk = (meta.ticker || '未知代號') + ' ' + (meta.interval || '');
    var cl = fmt(state.close);
    var out = [];
    if (state.flip_up) out.push(CN.alerts['Long Signal'](tk + ' @ ' + cl));
    if (state.flip_down) out.push(CN.alerts['Short Signal'](tk + ' @ ' + cl));
    if (state.flip_up || state.flip_down) out.push(CN.alerts['Any Flip'](tk + ' @ ' + cl));
    return out;
  }

  function drawKline(canvas, candles, state, opts) {
    opts = opts || {};
    var ctx = canvas.getContext('2d');
    var W = canvas.width, H = canvas.height, padL = 8, padR = 150, padT = 28, padB = 24;
    var n = candles.length;
    var hi = -Infinity, lo = Infinity;
    for (var i = 0; i < n; i++) { hi = Math.max(hi, candles[i].h); lo = Math.min(lo, candles[i].l); }
    if (state._st_series) for (var j = 0; j < state._st_series.length; j++) {
      hi = Math.max(hi, state._st_series[j]); lo = Math.min(lo, state._st_series[j]);
    }
    var span = (hi - lo) || 1; hi += span * 0.05; lo -= span * 0.05;
    var pw = W - padL - padR, ph = H - padT - padB;
    var X = function (i) { return padL + (i + 0.5) * pw / n; };
    var Y = function (p) { return padT + (hi - p) / (hi - lo) * ph; };
    var cw = Math.max(1, pw / n * 0.6);

    ctx.fillStyle = '#0d1117'; ctx.fillRect(0, 0, W, H);
    ctx.fillStyle = '#c9d1d9'; ctx.font = '13px sans-serif';
    ctx.fillText(CN.title, padL, 18);

    /* K 線 */
    for (var k = 0; k < n; k++) {
      var c = candles[k], up = c.c >= c.o;
      ctx.strokeStyle = ctx.fillStyle = up ? '#26a69a' : '#ef5350';
      var x = X(k);
      ctx.beginPath(); ctx.moveTo(x, Y(c.h)); ctx.lineTo(x, Y(c.l)); ctx.stroke();
      var y1 = Y(Math.max(c.o, c.c)), y2 = Y(Math.min(c.o, c.c));
      ctx.fillRect(x - cw / 2, y1, cw, Math.max(1, y2 - y1));
    }

    /* SuperTrend 線(源 st 序列) */
    if (state._st_series) {
      ctx.strokeStyle = '#f0b90b'; ctx.lineWidth = 1.5; ctx.beginPath();
      for (var m = 0; m < n; m++) {
        var sx = X(m), sy = Y(state._st_series[m]);
        if (m === 0) ctx.moveTo(sx, sy); else ctx.lineTo(sx, sy);
      }
      ctx.stroke(); ctx.lineWidth = 1;
    }

    /* 翻轉箭頭 + 中文提示 */
    if (state._flips) state._flips.forEach(function (f) {
      var x2 = X(f.bar), y2 = f.up ? Y(candles[f.bar].l) + 14 : Y(candles[f.bar].h) - 14;
      ctx.fillStyle = f.up ? '#26a69a' : '#ef5350';
      ctx.font = 'bold 12px sans-serif';
      ctx.fillText(f.up ? '▲' : '▼', x2 - 5, y2);
      ctx.fillText(f.up ? CN.long : CN.short, x2 - 12, f.up ? y2 + 14 : y2 - 12);
    });

    /* 當前 flip 標籤(同源 label.new 文案) */
    if (state.flip_up) {
      ctx.fillStyle = '#26a69a';
      ctx.fillText(CN.tipLong(state.quality_grade, fmt(state.close)), X(n - 1) - 60, Y(state.close) + 30);
    } else if (state.flip_down) {
      ctx.fillStyle = '#ef5350';
      ctx.fillText(CN.tipShort(state.quality_grade, fmt(state.close)), X(n - 1) - 60, Y(state.close) - 20);
    }

    /* 中文儀表板(右側) */
    var dash = (typeof V4Indicator !== 'undefined' && V4Indicator.buildDashboard)
      ? V4Indicator.buildDashboard(state) : null;
    var rows = dash ? cnDashboard(dash) : CN.rows.map(function (k) { return [k, '—']; });
    var bx = W - padR + 6, by = padT + 6;
    ctx.fillStyle = '#161b22'; ctx.fillRect(bx - 4, by - 16, padR - 8, rows.length * 18 + 40);
    ctx.fillStyle = '#f0b90b'; ctx.font = 'bold 12px sans-serif';
    ctx.fillText('SUPERTREND 儀表板', bx, by);
    ctx.font = '11px sans-serif';
    rows.forEach(function (row, idx) {
      ctx.fillStyle = '#8b949e'; ctx.fillText(row[0], bx, by + 18 + idx * 18);
      ctx.fillStyle = '#c9d1d9'; ctx.fillText(String(row[1]), bx + 62, by + 18 + idx * 18);
    });

    /* 底部中文警報提示 */
    var alerts = cnAlerts(state, opts.meta);
    ctx.fillStyle = '#8b949e'; ctx.font = '11px sans-serif';
    alerts.forEach(function (a, i2) { ctx.fillText('⚡ ' + a, padL, H - 8 - (alerts.length - 1 - i2) * 14); });

    return { alerts: alerts, dashboard: rows, title: CN.title };
  }

  return { drawKline: drawKline, cnDashboard: cnDashboard, cnAlerts: cnAlerts, CN: CN };
});

自測(node 實跑)

接入提示

本頁零憑證。A23 · seat A233804 · file: A23_V4_INDICATOR.html