<!DOCTYPE html>
<html lang="zh-HK">
<head>
<meta charset="utf-8">
<title>A85 — V2 Indicator Spec &amp; Executable Code: Liquidity Sweeps [LuxAlgo]</title>
<style>
  body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; max-width: 1040px; margin: 28px auto; padding: 0 18px; line-height: 1.55; color: #1a1f29; background: #fafbfc; }
  h1, h2, h3 { color: #0f172a; }
  code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 13px; }
  pre { background: #0f172a; color: #e2e8f0; padding: 14px; border-radius: 6px; overflow-x: auto; }
  table { border-collapse: collapse; width: 100%; margin: 14px 0; background: #fff; }
  th, td { border: 1px solid #cbd5e1; padding: 8px 10px; text-align: left; font-size: 13.5px; }
  th { background: #f1f5f9; }
  .note { background: #eff6ff; border-left: 4px solid #2563eb; padding: 10px 14px; margin: 12px 0; }
</style>
</head>
<body>
<h1>A85 — V2 指標算法設計與可執行編碼（Liquidity Sweeps [LuxAlgo]）</h1>
<p><strong>對應 Relay 決議</strong>：<code>COMMONS seq=65053</code>（接 <code>65024 / 65033</code>，定調為 V2 指標；僅保存算法＋編碼，不改動現行 Line ② <code>market-engine-server.js</code>）。</p>
<p><strong>座席</strong>：<code>A85 (A854611)</code> ｜ <strong>日期</strong>：2026-11-20 ｜ <strong>運行環境</strong>：Node.js v20.20.2</p>

<div class="note">
  <strong>去敏聲明</strong>：本檔僅含公開技術指標算法規格、開源 Pine Script v5 原碼、Node.js 潔淨參考實現與合成單元測試輸出，不含任何密鑰、Relay Session 或環境路徑隱私。
</div>

<h2>一、文件與產物清單（Manifest）</h2>
<table>
  <thead><tr><th>檔名</th><th>Bytes</th><th>SHA-256</th></tr></thead>
  <tbody>
    <tr><td><code>liquidity_sweeps_luxalgo_JRqryeJ5.pine</code></td><td>5796</td><td><code>18be09f34ebf371e4cc8997ba77c29cc1ada4612a5529a79994694ec9b6ba12d</code></td></tr><tr><td><code>v2_liquidity_sweeps.js</code></td><td>7698</td><td><code>054e5b96f344a348237964f16fd20226ad97da91fb69d89ea8fe0aed55d25884</code></td></tr><tr><td><code>test_v2_liquidity_sweeps.js</code></td><td>5294</td><td><code>f64ef4cfe49879b090097738dacc538bc549fa7654069ea466eec09d879693ca</code></td></tr>
  </tbody>
</table>

<h2>二、V2 指標算法規格（嚴格對齊 TradingView <code>JRqryeJ5</code>）</h2>
<ol>
  <li><strong>唯一市場數據輸入</strong>：單一圖表 K 線序列之 <code>high</code>、<code>low</code>、<code>close</code> 與 <code>bar_index</code>（零讀取 <code>open</code>、<code>volume</code>、盤口 DOM 或跨週期資料）。</li>
  <li><strong>Pivot 流動性池（<code>LqL</code>）建立</strong>：
    <ul>
      <li>預設對稱窗口 <code>len = 5</code>（可設 <code>&ge; 1</code>）。</li>
      <li>於收盤索引 <code>n</code> 檢查 <code>mid = n - len</code>：若 <code>high[mid]</code> 嚴格大於左右各 <code>len</code> 根 <code>high</code>，新增 <code>aPivH</code> 物件（<code>prc = high[mid], bix = mid</code>）；<code>low[mid]</code> 嚴格小於左右各 <code>len</code> 根 <code>low</code>，新增 <code>aPivL</code> 物件。具 <code>len</code> 根確認滯後、零未來函數。</li>
    </ul>
  </li>
  <li><strong>三種模式旗標</strong>：<code>Only Wicks</code>（<code>oW</code>，預設）、<code>Only Outbreaks &amp; Retest</code>（<code>oO</code>）、<code>Wicks + Outbreaks &amp; Retest</code>（<code>WO</code>）。</li>
  <li><strong>掃蕩偵測狀態機</strong>（對 <code>aPivH</code>／<code>aPivL</code> 逐一由舊至新掃描未失效項目）：
    <ul>
      <li><strong>高點池（<code>aPivH</code>）未突破（<code>!brk</code>）</strong>：若 <code>close &gt; prc</code>，<code>oW</code> 模式標為 <code>mit = true</code> 淘汰，否則設 <code>brk = true</code>；若 <code>!oO &amp;&amp; !wic &amp;&amp; high &gt; prc &amp;&amp; close &lt; prc</code>，觸發 <code>BEAR_WICK_SWEEP</code>，建立 <code>Sweep Area [top=high, bottom=prc]</code>，設 <code>wic = true</code>。</li>
      <li><strong>高點池已突破（<code>brk</code>）</strong>：若 <code>close &lt; prc</code> 設 <code>mit = true</code>；若 <code>!oW &amp;&amp; low &lt; prc &amp;&amp; close &gt; prc</code>，觸發 <code>BULL_RETEST_SWEEP</code>，建立 <code>Sweep Area [top=prc, bottom=low]</code>，設 <code>tak = true</code>。</li>
      <li><strong>低點池（<code>aPivL</code>）</strong>：條件與方向完全鏡像（<code>BULL_WICK_SWEEP</code>／<code>BEAR_RETEST_SWEEP</code>）。</li>
      <li><strong>回收條件</strong>：<code>n - bix &gt; 2000 || mit || tak</code> 即自追蹤陣列移除。</li>
    </ul>
  </li>
  <li><strong>Sweep Area 延伸與失效</strong>：當 <code>extend = true</code> 且 <code>n - box.left - 1 &le; maxB</code>（預設 <code>300</code>）時持續延伸右界；多頭框（<code>dr = -1</code>）遇 <code>close &lt; bottom</code> 停止延伸，空頭框（<code>dr = 1</code>）遇 <code>close &gt; top</code> 停止延伸。</li>
  <li><strong>備註（整合進 V2 Server 時的實作邊界）</strong>：原 Pine 指標用於圖表實時標記（無內建 <code>alertcondition</code> 與下單邏輯）；日後若接駁進 <code>market-engine-server.js</code> 作為 V2 策略／訊號模組，應綁定 <strong>closed-bar</strong>（已收盤 K 線）才呼叫 <code>LiquiditySweepsEngine.step(bar)</code>，以配合原帖作者「等實體收回確定、止損置於掃蕩極值外」之執行規則。</li>
</ol>

<h2>三、Node.js v20 實測結果（<code>node test_v2_liquidity_sweeps.js</code>，rc=0）</h2>
<pre>PASS 1: Pivot confirmation lag (len=2) &amp; Bearish Wick Sweep + Sweep Area mitigation
PASS 2: Bullish Wick Sweep &amp; close-through retires LqL in Only Wicks
PASS 3: Only Outbreaks &amp; Retest mode ignores wick-only and triggers dashed retest
PASS 4: Strict pivot detection rejects plateau/equal highs
PASS 5: maxB box extension cap and pivot age expiry
ALL_TESTS_PASSED=5/5
</pre>

<h2>四、可執行 Node.js 模組（<code>v2_liquidity_sweeps.js</code>）</h2>
<pre>&#x27;use strict&#x27;;

/**
 * V2 Indicator: Liquidity Sweeps [LuxAlgo] — Exact Node.js Reference Port
 *
 * Primary source:
 *   TradingView JRqryeJ5-Liquidity-Sweeps-LuxAlgo (PUB;26391b932d3145879b67deca62305c9a v1.0)
 *   Pine Script v5 (5793 B, sha256=18be09f34ebf371e4cc8997ba77c29cc1ada4612a5529a79994694ec9b6ba12d)
 *   License of original Pine algorithm: CC BY-NC-SA 4.0 (© LuxAlgo)
 *
 * Inputs used from market bars: ONLY high, low, close, and bar_index (0 open, 0 volume, 0 external).
 */

const VALID_MODES = Object.freeze([
  &#x27;Only Wicks&#x27;,
  &#x27;Only Outbreaks &amp; Retest&#x27;,
  &#x27;Wicks + Outbreaks &amp; Retest&#x27;,
]);

function normalizeBar(bar, fallbackIdx) {
  const h = Number(bar.high !== undefined ? bar.high : bar.h);
  const l = Number(bar.low !== undefined ? bar.low : bar.l);
  const c = Number(bar.close !== undefined ? bar.close : bar.c);
  if (!Number.isFinite(h) || !Number.isFinite(l) || !Number.isFinite(c)) {
    throw new TypeError(`Invalid H/L/C at bar ${fallbackIdx}`);
  }
  return { h, l, c };
}

class LiquiditySweepsEngine {
  constructor(opts = {}) {
    const len = opts.len !== undefined ? Number(opts.len) : 5;
    if (!Number.isInteger(len) || len &lt; 1) {
      throw new RangeError(`len must be integer &gt;= 1, got ${opts.len}`);
    }
    const mode = opts.mode || &#x27;Only Wicks&#x27;;
    if (!VALID_MODES.includes(mode)) {
      throw new RangeError(`Invalid mode: ${mode}`);
    }
    const extend = opts.extend !== undefined ? Boolean(opts.extend) : true;
    const maxB = opts.maxB !== undefined ? Number(opts.maxB) : 300;
    if (!Number.isInteger(maxB) || maxB &lt; 1 || maxB &gt; 5000) {
      throw new RangeError(`maxB must be integer in [1, 5000], got ${opts.maxB}`);
    }
    const maxPivotAge = opts.maxPivotAge !== undefined ? Number(opts.maxPivotAge) : 2000;

    this.len = len;
    this.mode = mode;
    this.oW = mode === &#x27;Only Wicks&#x27;;
    this.oO = mode === &#x27;Only Outbreaks &amp; Retest&#x27;;
    this.WO = mode === &#x27;Wicks + Outbreaks &amp; Retest&#x27;;
    this.extend = extend;
    this.maxB = maxB;
    this.maxPivotAge = maxPivotAge;

    this.bars = [];
    this.aPivH = []; // newest first (unshift), iterated reverse (oldest -&gt; newest)
    this.aPivL = [];
    this.aBoxBr = [];
    this.events = [];
  }

  _pivotHighAtConfirm(n) {
    const L = this.len;
    if (n &lt; 2 * L) return null;
    const midIdx = n - L;
    const midVal = this.bars[midIdx].h;
    for (let k = midIdx - L; k &lt;= n; k++) {
      if (k === midIdx) continue;
      if (!(midVal &gt; this.bars[k].h)) return null; // strict both sides
    }
    return midVal;
  }

  _pivotLowAtConfirm(n) {
    const L = this.len;
    if (n &lt; 2 * L) return null;
    const midIdx = n - L;
    const midVal = this.bars[midIdx].l;
    for (let k = midIdx - L; k &lt;= n; k++) {
      if (k === midIdx) continue;
      if (!(midVal &lt; this.bars[k].l)) return null; // strict both sides
    }
    return midVal;
  }

  step(rawBar) {
    const n = this.bars.length;
    const { h, l, c } = normalizeBar(rawBar, n);
    this.bars.push({ h, l, c });

    const ph = this._pivotHighAtConfirm(n);
    const pl = this._pivotLowAtConfirm(n);

    if (ph !== null) {
      this.aPivH.unshift({
        prc: ph,
        bix: n - this.len,
        brk: false,
        mit: false,
        tak: false,
        wic: false,
      });
    }
    if (pl !== null) {
      this.aPivL.unshift({
        prc: pl,
        bix: n - this.len,
        brk: false,
        mit: false,
        tak: false,
        wic: false,
      });
    }

    const stepEvents = [];

    // Process Pivot Highs (aPivH) from oldest to newest
    for (let i = this.aPivH.length - 1; i &gt;= 0; i--) {
      const get = this.aPivH[i];
      if (!get.mit) {
        if (!get.brk) {
          if (c &gt; get.prc) {
            if (!this.oW) get.brk = true;
            else get.mit = true;
          }
          if (!this.oO &amp;&amp; !get.wic) {
            if (h &gt; get.prc &amp;&amp; c &lt; get.prc) {
              const box = {
                left: n - 1,
                right: n + 1,
                top: h,
                bottom: get.prc,
                br: false,
                dr: 1,
                kind: &#x27;BEAR_WICK_SWEEP&#x27;,
                lqlPrice: get.prc,
                lqlBar: get.bix,
                triggerBar: n,
                dotGuideY: l,
                lineStyle: &#x27;dotted&#x27;,
              };
              this.aBoxBr.unshift(box);
              get.wic = true;
              stepEvents.push(box);
            }
          }
        } else {
          if (c &lt; get.prc) {
            get.mit = true;
          }
          if (!this.oW &amp;&amp; l &lt; get.prc &amp;&amp; c &gt; get.prc) {
            const box = {
              left: n - 1,
              right: n + 1,
              top: get.prc,
              bottom: l,
              br: false,
              dr: -1,
              kind: &#x27;BULL_RETEST_SWEEP&#x27;,
              lqlPrice: get.prc,
              lqlBar: get.bix,
              triggerBar: n,
              dotGuideY: h,
              lineStyle: &#x27;dashed&#x27;,
            };
            this.aBoxBr.unshift(box);
            get.tak = true;
            stepEvents.push(box);
          }
        }
      }
      if (n - get.bix &gt; this.maxPivotAge || get.mit || get.tak) {
        this.aPivH.splice(i, 1);
      }
    }

    // Process Pivot Lows (aPivL) from oldest to newest
    for (let i = this.aPivL.length - 1; i &gt;= 0; i--) {
      const get = this.aPivL[i];
      if (!get.mit) {
        if (!get.brk) {
          if (c &lt; get.prc) {
            if (!this.oW) get.brk = true;
            else get.mit = true;
          }
          if (!this.oO &amp;&amp; !get.wic) {
            if (l &lt; get.prc &amp;&amp; c &gt; get.prc) {
              const box = {
                left: n - 1,
                right: n + 1,
                top: get.prc,
                bottom: l,
                br: false,
                dr: -1,
                kind: &#x27;BULL_WICK_SWEEP&#x27;,
                lqlPrice: get.prc,
                lqlBar: get.bix,
                triggerBar: n,
                dotGuideY: h,
                lineStyle: &#x27;dotted&#x27;,
              };
              this.aBoxBr.unshift(box);
              get.wic = true;
              stepEvents.push(box);
            }
          }
        } else {
          if (c &gt; get.prc) {
            get.mit = true;
          }
          if (!this.oW &amp;&amp; h &gt; get.prc &amp;&amp; c &lt; get.prc) {
            const box = {
              left: n - 1,
              right: n + 1,
              top: h,
              bottom: get.prc,
              br: false,
              dr: 1,
              kind: &#x27;BEAR_RETEST_SWEEP&#x27;,
              lqlPrice: get.prc,
              lqlBar: get.bix,
              triggerBar: n,
              dotGuideY: l,
              lineStyle: &#x27;dashed&#x27;,
            };
            this.aBoxBr.unshift(box);
            get.tak = true;
            stepEvents.push(box);
          }
        }
      }
      if (n - get.bix &gt; this.maxPivotAge || get.mit || get.tak) {
        this.aPivL.splice(i, 1);
      }
    }

    // Extend &amp; mitigate Sweep Area boxes
    if (this.extend) {
      for (const bx of this.aBoxBr) {
        if (!bx.br &amp;&amp; n - bx.left - 1 &lt;= this.maxB) {
          bx.right = n;
          if (bx.dr === -1 &amp;&amp; c &lt; bx.bottom) bx.br = true;
          if (bx.dr === 1 &amp;&amp; c &gt; bx.top) bx.br = true;
        }
      }
    }

    for (const ev of stepEvents) this.events.push(ev);
    return stepEvents;
  }
}

function computeLiquiditySweeps(bars, opts = {}) {
  const eng = new LiquiditySweepsEngine(opts);
  for (const b of bars) eng.step(b);
  return {
    events: eng.events,
    boxes: eng.aBoxBr,
    activePivH: eng.aPivH,
    activePivL: eng.aPivL,
  };
}

module.exports = {
  VALID_MODES,
  LiquiditySweepsEngine,
  computeLiquiditySweeps,
};
</pre>

<h2>五、單元測試腳本（<code>test_v2_liquidity_sweeps.js</code>）</h2>
<pre>&#x27;use strict&#x27;;

const assert = require(&#x27;assert&#x27;);
const { LiquiditySweepsEngine, computeLiquiditySweeps } = require(&#x27;./v2_liquidity_sweeps&#x27;);

function bar(h, l, c) {
  return { high: h, low: l, close: c }; // deliberately NO open, NO volume, NO time
}

let passed = 0;
function runTest(name, fn) {
  fn();
  passed += 1;
  console.log(`PASS ${passed}: ${name}`);
}

// 1. Pivot confirmation lag (len=2 -&gt; confirms at n = bix + 2) &amp; no-lookahead
runTest(&#x27;Pivot confirmation lag (len=2) &amp; Bearish Wick Sweep + Sweep Area mitigation&#x27;, () =&gt; {
  const bars = [
    bar(101, 99, 100),   // 0
    bar(105, 100, 104),  // 1
    bar(110, 103, 108),  // 2 &lt;- pivot high = 110
    bar(106, 102, 103),  // 3
    bar(104, 100, 102),  // 4 &lt;- ph=110 confirmed here (bix=2)
    bar(113, 105, 109),  // 5 &lt;- high=113 &gt; 110, close=109 &lt; 110 =&gt; BEAR_WICK_SWEEP!
    bar(111, 106, 108),  // 6 &lt;- extends box (right=6), not mitigated
    bar(115, 107, 114),  // 7 &lt;- close=114 &gt; top(113) =&gt; box mitigated (br=true)
    bar(114, 109, 111),  // 8 &lt;- stays right=7 (no longer extended)
  ];
  const res = computeLiquiditySweeps(bars, { len: 2, mode: &#x27;Only Wicks&#x27;, extend: true, maxB: 300 });
  assert.strictEqual(res.events.length, 1);
  const ev = res.events[0];
  assert.strictEqual(ev.kind, &#x27;BEAR_WICK_SWEEP&#x27;);
  assert.strictEqual(ev.lqlBar, 2);
  assert.strictEqual(ev.lqlPrice, 110);
  assert.strictEqual(ev.triggerBar, 5);
  assert.strictEqual(ev.top, 113);
  assert.strictEqual(ev.bottom, 110);
  assert.strictEqual(ev.br, true);
  assert.st