<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>V2 指標歸檔｜Liquidity Sweeps [LuxAlgo] 算法規格＋Node.js 實作＋驗證測試（A59 / seq=65053）</title>
<style>
  :root { --bg:#0d1117; --card:#161b22; --bd:#30363d; --tx:#e6edf3; --muted:#8b949e; --acc:#58a6ff; --ok:#3fb950; --warn:#d29922; }
  * { box-sizing:border-box; }
  body { margin:0; padding:24px; background:var(--bg); color:var(--tx); font:14px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Noto Sans TC",sans-serif; }
  .wrap { max-width:1080px; margin:0 auto; }
  h1,h2,h3 { color:#fff; margin-top:1.4em; }
  h1 { margin-top:0; font-size:1.65rem; border-bottom:1px solid var(--bd); padding-bottom:10px; }
  .card { background:var(--card); border:1px solid var(--bd); border-radius:8px; padding:16px 20px; margin:14px 0; }
  .badge { display:inline-block; padding:2px 8px; border-radius:12px; font-size:12px; font-weight:600; background:#1f6feb33; color:var(--acc); border:1px solid #1f6feb66; margin-right:6px; }
  .badge.ok { background:#23863633; color:var(--ok); border-color:#23863666; }
  table { width:100%; border-collapse:collapse; margin:10px 0; font-size:13px; }
  th,td { border:1px solid var(--bd); padding:7px 10px; text-align:left; vertical-align:top; }
  th { background:#21262d; color:#fff; }
  pre { background:#090c10; border:1px solid var(--bd); border-radius:6px; padding:14px; overflow-x:auto; font:12.5px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; color:#c9d1d9; }
  code { font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; background:#21262d; padding:1px 5px; border-radius:4px; font-size:12.5px; }
  pre code { background:none; padding:0; }
  .muted { color:var(--muted); font-size:12.5px; }
  .formula { background:#111827; border-left:3px solid var(--acc); padding:10px 14px; margin:8px 0; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:13px; }
</style>
</head>
<body>
<div class="wrap">
  <h1>V2 指標定版歸檔：Liquidity Sweeps [LuxAlgo]（算法規格＋可落地編碼＋單元測試）</h1>
  <div class="card">
    <span class="badge">定調：V2 指標</span>
    <span class="badge">seq=65024 / 65033 / 65053</span>
    <span class="badge ok">Node v20.20.2 測試 9/9 PASS</span>
    <p class="muted">
      整理與實作：A59 (<code>A594117</code>)｜日期：2026-11-20｜狀態：算法＋編碼＋實測一次歸檔保存，供後續修改 <code>market-engine/server.js</code>（<code>eed819a94078</code>）時直接加插。<br>
      官方源碼來源：TradingView <code>JRqryeJ5</code> / <code>PUB;26391b932d3145879b67deca62305c9a</code>（Pine Script v5，160 行，5,796 B，<code>CC BY-NC-SA 4.0 © LuxAlgo</code>，<code>sha256=18be09f34ebf371e…</code>）。<br>
      本歸檔內嵌檔案指紋：<code>v2_liquidity_sweeps.js</code>（11406 B，<code>sha256=e72cfd2f121b6639…</code>）、<code>test_v2_liquidity_sweeps.js</code>（9075 B，<code>sha256=85df658d186232af…</code>）。
    </p>
  </div>

  <h2>一、來源核實摘要（X 原串＋TradingView 開源實碼）</h2>
  <div class="card">
    <ul>
      <li><strong>X 原串（5 連帖 + 3 張概念圖）</strong>：作者 <code>べーた (@foodloss_otoko)</code> 於 2026-11-19T17:00:19Z 發佈 <code>2123461381030834442</code>，推薦 TradingView 指標 <strong><code>Liquidity Sweeps [LuxAlgo]</code></strong>（非 TeamViewer；尾帖導流 LINE 領 EA 與本指標無關且未驗證）。</li>
      <li><strong>純普通 K 線輸入（零外部數據）</strong>：逐行審計官方 160 行 Pine 源碼確認，僅使用連續歷史 K 線序列之 <code>high</code>、<code>low</code>、<code>close</code> 與順序索引 <code>bar_index</code>（外加 4 個參數 <code>len/opt/extend/maxB</code>）。<strong>完全不使用 <code>open</code>（0 次）、<code>volume</code>（0 次）、<code>ta.atr</code>（0 次）、<code>request.*</code>（0 次）或任何 L2 盤口數據。</strong></li>
    </ul>
  </div>

  <h2>二、完整算法規格（零跳步，100% 對應官方 L14–L157）</h2>
  <div class="card">
    <h3>2.1 輸入參數</h3>
    <table>
      <thead><tr><th>參數</th><th>預設值</th><th>範圍 / 選項</th><th>說明</th></tr></thead>
      <tbody>
        <tr><td><code>len</code> (Swings)</td><td><code>5</code></td><td>整數 &ge; 1</td><td>對稱擺動樞紐左右窗口，確認滯後 <code>len</code> 根（確認後不重繪）</td></tr>
        <tr><td><code>opt</code> (options)</td><td><code>'Only Wicks'</code></td><td><code>Only Wicks</code> / <code>Only Outbreaks &amp; Retest</code> / <code>Wicks + Outbreaks &amp; Retest</code></td><td>控制掃蕩偵測型態</td></tr>
        <tr><td><code>extend</code></td><td><code>true</code></td><td>bool</td><td>是否持續向右延伸 Sweep Area 區域框</td></tr>
        <tr><td><code>maxB</code></td><td><code>300</code></td><td><code>1..5000</code></td><td>Sweep Area 最多延伸 K 線根數</td></tr>
        <tr><td><code>maxPivotAge</code></td><td><code>2000</code></td><td>整數 &ge; 1</td><td>歷史樞紐最長保留根數（超過 <code>n - bix &gt; 2000</code> 淘汰）</td></tr>
        <tr><td><code>pivotTieMode</code></td><td><code>'pine'</code></td><td><code>pine</code> / <code>strict</code></td><td><code>pine</code> 採左 <code>&le;/&ge;</code>、右嚴格 <code>&lt;/&gt;</code>（平頂/平底取最右端，防雙重入池）；<code>strict</code> 兩側嚴格</td></tr>
      </tbody>
    </table>

    <h3>2.2 四步驟狀態機公式（每根 K 線 <code>n = bar_index</code>）</h3>
    <div class="formula">
      <strong>Step 1 — 樞紐確認（L91–L98）</strong>：<br>
      當 <code>n &ge; 2*len</code>，檢查候選柱 <code>c = n - len</code>：<br>
      • 若 <code>high[c]</code> 為窗口 <code>[c-len .. c+len]</code> 局部高點 → <code>aPivH.unshift({prc: high[c], bix: c, brk:false, mit:false, tak:false, wic:false})</code><br>
      • 若 <code>low[c]</code> 為窗口 <code>[c-len .. c+len]</code> 局部低點 → <code>aPivL.unshift({prc: low[c], bix: c, brk:false, mit:false, tak:false, wic:false})</code>
    </div>
    <div class="formula">
      <strong>Step 2 — 高點池 <code>aPivH</code> 掃蕩與突破判定（L100–L123，記 <code>P = get.prc</code>）</strong>：<br>
      • 未破位（<code>!brk</code>）：若 <code>close[n] &gt; P</code> → <code>Only Wicks</code> 設 <code>mit=true</code>（真突破淘汰），否則設 <code>brk=true</code>。<br>
      • <strong>看空影線掃蕩（Type 1, dotted）</strong>：<code>!oO &amp;&amp; !wic &amp;&amp; high[n] &gt; P &amp;&amp; close[n] &lt; P</code> → 建看空框（<code>dr=+1, top=high[n], bottom=P</code>）+ 3-bar 輔助線 <code>y=low[n]</code> + <code>wic=true</code>。<br>
      • 已破位（<code>brk</code>）：若 <code>close[n] &lt; P</code> 設 <code>mit=true</code>；<strong>看多突破回測掃蕩（Type 2, dashed）</strong>：<code>!oW &amp;&amp; low[n] &lt; P &amp;&amp; close[n] &gt; P</code> → 建看多框（<code>dr=-1, top=P, bottom=low[n]</code>）+ 3-bar 輔助線 <code>y=high[n]</code> + <code>tak=true</code>。<br>
      • 清理：<code>(n - bix &gt; 2000) || mit || tak</code> 移除該樞紐。
    </div>
    <div class="formula">
      <strong>Step 3 — 低點池 <code>aPivL</code> 對稱狀態機（L125–L147）</strong>：<br>
      • 未破位（<code>!brk</code>）：若 <code>close[n] &lt; P</code> → <code>Only Wicks</code> 設 <code>mit=true</code>，否則 <code>brk=true</code>。<br>
      • <strong>看多影線掃蕩（Type 1, dotted）</strong>：<code>!oO &amp;&amp; !wic &amp;&amp; low[n] &lt; P &amp;&amp; close[n] &gt; P</code> → 建看多框（<code>dr=-1, top=P, bottom=low[n]</code>）+ 3-bar 輔助線 <code>y=high[n]</code> + <code>wic=true</code>。<br>
      • 已破位（<code>brk</code>）：若 <code>close[n] &gt; P</code> 設 <code>mit=true</code>；<strong>看空突破回測掃蕩（Type 2, dashed）</strong>：<code>!oW &amp;&amp; high[n] &gt; P &amp;&amp; close[n] &lt; P</code> → 建看空框（<code>dr=+1, top=high[n], bottom=P</code>）+ 3-bar 輔助線 <code>y=low[n]</code> + <code>tak=true</code>。<br>
      • 清理：<code>(n - bix &gt; 2000) || mit || tak</code> 移除該樞紐。
    </div>
    <div class="formula">
      <strong>Step 4 — Sweep Area 區域框延伸與失效（L149–L157）</strong>：<br>
      若 <code>extend == true</code>，對每個未失效（<code>!bx.br</code>）且 <code>n - bx.left - 1 &lt;= maxB</code> 之區域框：<code>bx.right = n</code>；<br>
      • 看多框（<code>dr == -1</code>）若 <code>close[n] &lt; bx.bottom</code> → <code>bx.br = true</code>（停止延伸）；<br>
      • 看空框（<code>dr == +1</code>）若 <code>close[n] &gt; bx.top</code> → <code>bx.br = true</code>（停止延伸）。
    </div>
    <p class="muted">
      <code>market-engine/server.js</code> 串接介面：直接讀取 <code>IDX = { TS:0, TIME:1, OPEN:2, HIGH:3, LOW:4, CLOSE:5, VOL:6, AMT:7 }</code>（<code>L407</code>）與 <code>PRICE_SCALE = 10000</code>（<code>L400</code>），整數原值精確比較零浮點誤差，僅於輸出還原顯示價；支援串流 <code>step()</code> 與批次 <code>computeLiquiditySweepsFromServerBars()</code>。
    </p>
  </div>

  <h2>三、可落地 Node.js 模組源碼（<code>v2_liquidity_sweeps.js</code>）</h2>
  <div class="card">
    <pre><code>&quot;use strict&quot;;

/**
 * V2 Indicator: Liquidity Sweeps (Faithful JS Port of LuxAlgo Pine Script v5 JRqryeJ5)
 *
 * Official Pine source reference:
 *   TradingView PUB;26391b932d3145879b67deca62305c9a (160 lines, CC BY-NC-SA 4.0 © LuxAlgo)
 *
 * Pure K-line inputs required:
 *   - high, low, close (continuous historical bar sequence)
 *   - sequential bar_index (0, 1, 2, ...)
 * Zero dependency on open, volume, ATR, L2 order book, or external APIs.
 *
 * Compatible with Node.js v20+ and market-engine server.js bar tuples:
 *   IDX = { TS: 0, TIME: 1, OPEN: 2, HIGH: 3, LOW: 4, CLOSE: 5, VOL: 6, AMT: 7 }
 */

const MODES = Object.freeze({
  ONLY_WICKS: &quot;Only Wicks&quot;,
  ONLY_OUTBREAKS: &quot;Only Outbreaks &amp; Retest&quot;,
  WICKS_AND_OUTBREAKS: &quot;Wicks + Outbreaks &amp; Retest&quot;,
});

const SERVER_BAR_IDX = Object.freeze({
  TS: 0,
  TIME: 1,
  OPEN: 2,
  HIGH: 3,
  LOW: 4,
  CLOSE: 5,
  VOL: 6,
  AMT: 7,
});

function validateOptions(opts = {}) {
  const len = opts.len === undefined ? 5 : Number(opts.len);
  if (!Number.isInteger(len) || len &lt; 1) {
    throw new RangeError(`len must be an integer &gt;= 1, got ${opts.len}`);
  }
  const opt = opts.opt === undefined ? MODES.ONLY_WICKS : String(opts.opt);
  if (
    opt !== MODES.ONLY_WICKS &amp;&amp;
    opt !== MODES.ONLY_OUTBREAKS &amp;&amp;
    opt !== MODES.WICKS_AND_OUTBREAKS
  ) {
    throw new RangeError(`Invalid opt mode: ${opt}`);
  }
  const extend = opts.extend === undefined ? true : Boolean(opts.extend);
  const maxB = opts.maxB === undefined ? 300 : Number(opts.maxB);
  if (!Number.isInteger(maxB) || maxB &lt; 1 || maxB &gt; 5000) {
    throw new RangeError(`maxB must be an integer in [1, 5000], got ${opts.maxB}`);
  }
  const maxPivotAge = opts.maxPivotAge === undefined ? 2000 : Number(opts.maxPivotAge);
  if (!Number.isInteger(maxPivotAge) || maxPivotAge &lt; 1) {
    throw new RangeError(`maxPivotAge must be an integer &gt;= 1, got ${opts.maxPivotAge}`);
  }
  // TradingView ta.pivothigh/low tie semantics:
  // &quot;pine&quot;   =&gt; cand &gt;= left &amp;&amp; cand &gt; right (rightmost bar wins flat tops/bottoms, no double-fire)
  // &quot;strict&quot; =&gt; cand &gt; left &amp;&amp; cand &gt; right  (strict inequality on both sides)
  const pivotTieMode = opts.pivotTieMode === undefined ? &quot;pine&quot; : String(opts.pivotTieMode);
  if (pivotTieMode !== &quot;pine&quot; &amp;&amp; pivotTieMode !== &quot;strict&quot;) {
    throw new RangeError(`pivotTieMode must be &quot;pine&quot; or &quot;strict&quot;, got ${pivotTieMode}`);
  }
  // Optional cap to bound memory in long-running server daemons (default 500 matches Pine max_boxes_count)
  const maxBoxes = opts.maxBoxes === undefined ? 500 : Number(opts.maxBoxes);
  if (!Number.isInteger(maxBoxes) || maxBoxes &lt; 1) {
    throw new RangeError(`maxBoxes must be an integer &gt;= 1, got ${opts.maxBoxes}`);
  }
  return { len, opt, extend, maxB, maxPivotAge, pivotTieMode, maxBoxes };
}

class LiquiditySweepsEngine {
  constructor(opts = {}) {
    this.cfg = validateOptions(opts);
    this.oW = this.cfg.opt === MODES.ONLY_WICKS;
    this.oO = this.cfg.opt === MODES.ONLY_OUTBREAKS;
    this.n = -1;
    // Rolling window of last (2 * len + 1) highs/lows for O(len) pivot checks with O(len) memory
    this._winCap = 2 * this.cfg.len + 1;
    this._winH = [];
    this._winL = [];
    // Active pivot pools (matches LuxAlgo aPivH / aPivL)
    this.aPivH = [];
    this.aPivL = [];
    // Active / historical Sweep Area boxes (matches LuxAlgo aBoxBr)
    this.aBoxBr = [];
  }

  /**
   * Feed one confirmed bar (high, low, close). Optional meta (e.g. { ts, time }) is carried on events.
   * Returns { barIndex, newPivotHigh, newPivotLow, events, mitigatedBoxes }.
   */
  step(high, low, close, meta = null) {
    const h = Number(high);
    const l = Number(low);
    const c = Number(close);
    if (!Number.isFinite(h) || !Number.isFinite(l) || !Number.isFinite(c)) {
      throw new TypeError(`Non-finite bar price: h=${high}, l=${low}, c=${close}`);
    }

    this.n += 1;
    const n = this.n;
    const { len, extend, maxB, maxPivotAge, pivotTieMode, maxBoxes } = this.cfg;

    this._winH.push(h);
    this._winL.push(l);
    if (this._winH.length &gt; this._winCap) {
      this._winH.shift();
      this._winL.shift();
    }

    let newPivotHigh = null;
    let newPivotLow = null;

    // Step 1: ta.pivothigh(len, len) and ta.pivotlow(len, len) (Pine L91-98)
    if (this._winH.length === this._winCap) {
      const ch = this._winH[len];
      const cl = this._winL[len];
      let isPH = true;
      let isPL = true;
      for (let k = 0; k &lt; len; k++) {
        if (pivotTieMode === &quot;strict&quot;) {
          if (!(this._winH[k] &lt; ch)) isPH = false;
          if (!(this._winL[k] &gt; cl)) isPL = false;
        } else {
          if (!(this._winH[k] &lt;= ch)) isPH = false;
          if (!(this._winL[k] &gt;= cl)) isPL = false;
        }
      }
      for (let k = len + 1; k &lt; this._winCap; k++) {
        if (!(this._winH[k] &lt; ch)) isPH = false;
        if (!(this._winL[k] &gt; cl)) isPL = false;
      }
      if (isPH) {
        newPivotHigh = {
          prc: ch,
          bix: n - len,
          brk: false,
          mit: false,
          tak: false,
          wic: false,
        };
        this.aPivH.unshift(newPivotHigh);
      }
      if (isPL) {
        newPivotLow = {
          prc: cl,
          bix: n - len,
          brk: false,
          mit: false,
          tak: false,
          wic: false,
        };
        this.aPivL.unshift(newPivotLow);
      }
    }

    const events = [];

    const pushBox = (dir, top, bottom, pivotBix, pivotPrc, kind, lineStyle, guidePrice) =&gt; {
      const box = {
        left: n - 1,
        right: n + 1,
        triggerBar: n,
        top,
        bottom,
        br: false, // mitigated flag
        dr: dir,   // +1 bearish (resistance), -1 bullish (support)
        pivotBix,
        pivotPrc,
        kind,
        lineStyle, // &quot;dotted&quot; | &quot;dashed&quot;
        guideLine: { x1: n, x2: n + 3, y: guidePrice }, // lnDot 3-bar opposite-wick helper
      };
      this.aBoxBr.unshift(box);
      if (this.aBoxBr.length &gt; maxBoxes) {
        this.aBoxBr.length = maxBoxes;
      }
      events.push({
        barIndex: n,
        meta,
        side: dir === -1 ? &quot;BULL&quot; : &quot;BEAR&quot;,
        kind, // &quot;WICK_SWEEP&quot; | &quot;OUTBREAK_RETEST_SWEEP&quot;
        lineStyle,
        pivotBix,
        level: pivotPrc,
        wickExtreme: dir === 1 ? top : bottom,
        sweepArea: { top, bottom },
        guidePrice,
      });
    };

    // Step 2: aPivH state machine (Pine L100-123)
    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) {
              pushBox(1, h, get.prc, get.bix, get.prc, &quot;WICK_SWEEP&quot;, &quot;dotted&quot;, l);
              get.wic = true;
            }
          }
        } else {
          if (c &lt; get.prc) {
            get.mit = true;
          }
          if (!this.oW &amp;&amp; l &lt; get.prc &amp;&amp; c &gt; get.prc) {
            pushBox(-1, get.prc, l, get.bix, get.prc, &quot;OUTBREAK_RETEST_SWEEP&quot;, &quot;dashed&quot;, h);
            get.tak = true;
          }
        }
      }
      if (n - get.bix &gt; maxPivotAge || get.mit || get.tak) {
        this.aPivH.splice(i, 1);
      }
    }

    // Step 3: aPivL state machine (Pine L125-147)
    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) {
              pushBox(-1, get.prc, l, get.bix, get.prc, &quot;WICK_SWEEP&quot;, &quot;dotted&quot;, h);
              get.wic = true;
            }
          }
        } else {
          if (c &gt; get.prc) {
            get.mit = true;
          }
          if (!this.oW &amp;&amp; h &gt; get.prc &amp;&amp; c &lt; get.prc) {
            pushBox(1, h, get.prc, get.bix, get.prc, &quot;OUTBREAK_RETEST_SWEEP&quot;, &quot;dashed&quot;, l);
            get.tak = true;
          }
        }
      }
      if (n - get.bix &gt; maxPivotAge || get.mit || get.tak) {
        this.aPivL.splice(i, 1);
      }
    }

    // Step 4: Sweep Area box extension &amp; mitigation (Pine L149-157)
    const mitigatedBoxes = [];
    if (extend) {
      for (let i = 0; i &lt; this.aBoxBr.length; i++) {
        const bx = this.aBoxBr[i];
        if (!bx.br &amp;&amp; n - bx.left - 1 &lt;= maxB) {
          bx.right = n;
          if (bx.dr === -1 &amp;&amp; c &lt; bx.bottom) {
            bx.br = true;
            mitigatedBoxes.push(bx);
          }
          if (bx.dr === 1 &amp;&amp; c &gt; bx.top) {
            bx.br = true;
            mitigatedBoxes.push(bx);
          }
        }
      }
    }

    return { barIndex: n, newPivotHigh, newPivotLow, events, mitigatedBoxes };
  }

  snapshot() {
    return {
      barIndex: this.n,
      activePivotsHigh: this.aPivH.length,
      activePivotsLow: this.aPivL.length,
      activeBoxes: this.aBoxBr.filter((b) =&gt; !b.br).length,
      totalBoxes: this.aBoxBr.length,
    };
  }
}

/**
 * Batch helper for object bars: [{ high, low, close, ... }] (or { h, l, c }).
 */
function computeLiquiditySweeps(bars, opts = {}) {
  const eng = new LiquiditySweepsEngine(opts);
  const allEvents = [];
  for (let i = 0; i &lt; bars.length; i++) {
    const b = bars[i];
    const h = b.high !== undefined ? b.high : b.h;
    const l = b.low !== undefined ? b.low : b.l;
    const c = b.close !== undefined ? b.close : b.c;
    const meta = b.ts !== undefined || b.time !== undefined ? { ts: b.ts, time: b.time } : null;
    const res = eng.step(h, l, c, meta);
    if (res.events.length) allEvents.push(...res.events);
  }
  return {
    config: eng.cfg,
    events: allEvents,
    boxes: eng.aBoxBr,
    activePivotsHigh: eng.aPivH,
    activePivotsLow: eng.aPivL,
    snapshot: eng.snapshot(),
  };
}

/**
 * Adapter for market-engine/server.js scaled bar tuples:
 *   bar = [TS, TIME, OPEN, HIGH, LOW, CLOSE, VOL, AMT]
 * Comparisons run directly on integer-scaled prices (zero float drift);
 * optional priceScale divides output levels/boxes back to display prices.
 */
function computeLiquiditySweepsFromServerBars(serverBars, opts = {}) {
  const priceScale = opts.priceScale === undefined ? 10000 : Number(opts.priceScale);
  const eng = new LiquiditySweepsEngine(opts);
  const allEvents = [];
  for (let i = 0; i &lt; serverBars.length; i++) {
    const row = serverBars[i];
    const h = row[SERVER_BAR_IDX.HIGH];
    const l = row[SERVER_BAR_IDX.LOW];
    const c = row[SERVER_BAR_IDX.CLOSE];
    const meta = { ts: row[SERVER_BAR_IDX.TS], time: row[SERVER_BAR_IDX.TIME] };
    const res = eng.step(h, l, c, meta);
    for (const ev of res.events) {
      allEvents.push(
        priceScale &gt; 1
          ? {
              ...ev,
              level: ev.level / priceScale,
              wickExtreme: ev.wickExtreme / priceScale,
              sweepArea: { top: ev.sweepArea.top / priceScale, bottom: ev.sweepArea.bottom / priceScale },
              guidePrice: ev.guidePrice / priceScale,
            }
          : ev
      );
    }
  }
  return {
    config: eng.cfg,
    priceScale,
    events: allEvents,
    snapshot: eng.snapshot(),
  };
}

module.exports = {
  MODES,
  SERVER_BAR_IDX,
  LiquiditySweepsEngine,
  computeLiquiditySweeps,
  computeLiquiditySweepsFromServerBars,
};
</code></pre>
  </div>

  <h2>四、自動化單元測試與實跑結果（Node.js v20.20.2）</h2>
  <div class="card">
    <h3>4.1 實跑輸出（Actual stdout，Exit Code 0）</h3>
    <pre><code>PASS [1] Mode 1 (Only Wicks): catches bear wick sweep, retires on close breakout, mitigates box
PASS [2] Mode 2 (Only Outbreaks &amp; Retest): skips wick sweep, catches bull retest sweep
PASS [3] Mode 3 (Wicks + Outbreaks &amp; Retest): catches both wick sweep and subsequent retest sweep
PASS [4] Symmetric aPivL: catches bull wick sweep + bear retest sweep and mitigates bull box
PASS [5] Boundary equality: close === P does NOT trigger sweep or breakout
PASS [6] One-shot wic flag: same pivot triggers wick sweep only once
PASS [7] Pivot tie mode: pine selects rightmost equal peak; strict rejects flat equal top
PASS [8] maxB caps box right edge and maxPivotAge expires old pivots
PASS [9] Streaming LiquiditySweepsEngine.step() matches batch computeLiquiditySweeps() 100%
PASS [10] market-engine server.js tuple adapter ([TS, TIME, O, H, L, C, VOL, AMT], PRICE_SCALE=10000)
  BENCH_5000_BARS: 39.80ms, events=848, activePivH=23, activePivL=11
PASS [11] Performance benchmark: 5,000 bars completes in &lt; 100ms
ALL_TESTS_PASSED: 11/11
</code></pre>
    <h3>4.2 測試套件源碼（<code>test_v2_liquidity_sweeps.js</code>）</h3>
    <pre><code>&quot;use strict&quot;;

const assert = require(&quot;assert&quot;);
const { performance } = require(&quot;perf_hooks&quot;);
const {
  MODES,
  LiquiditySweepsEngine,
  computeLiquiditySweeps,
  computeLiquiditySweepsFromServerBars,
} = require(&quot;./v2_liquidity_sweeps.js&quot;);

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

// 1. Bearish Wick Sweep + Close Breakout + Bullish Outbreak &amp; Retest across all 3 modes
const barsHigh = [
  { h: 100, l: 98, c: 99 },
  { h: 102, l: 99, c: 101 },
  { h: 105, l: 100, c: 103 }, // Pivot High @ idx=2 (prc=105)
  { h: 103, l: 99, c: 100 },
  { h: 102, l: 98, c: 101 },  // confirms PH @ idx=4
  { h: 107, l: 101, c: 104 }, // idx=5: Bear Wick Sweep (high 107 &gt; 105 &amp;&amp; close 104 &lt; 105)
  { h: 109, l: 104, c: 108 }, // idx=6: close 108 &gt; 105 (mit in Only Wicks; brk in Outbreaks) &amp; &gt; box top 107 (mitigates box)
  { h: 107, l: 104, c: 106 }, // idx=7: Bull Outbreak &amp; Retest (low 104 &lt; 105 &amp;&amp; close 106 &gt; 105)
];

test(&quot;Mode 1 (Only Wicks): catches bear wick sweep, retires on close breakout, mitigates box&quot;, () =&gt; {
  const r = computeLiquiditySweeps(barsHigh, { len: 2, opt: MODES.ONLY_WICKS });
  assert.strictEqual(r.events.length, 1);
  assert.strictEqual(r.events[0].side, &quot;BEAR&quot;);
  assert.strictEqual(r.events[0].kind, &quot;WICK_SWEEP&quot;);
  assert.strictEqual(r.events[0].barIndex, 5);
  assert.strictEqual(r.events[0].pivotBix, 2);
  assert.strictEqual(r.events[0].level, 105);
  assert.strictEqual(r.events[0].wickExtreme, 107);
  assert.strictEqual(r.events[0].guidePrice, 101);
  assert.strictEqual(r.boxes[0].br, true); // mitigated at idx=6 (close 108 &gt; top 107)
  assert.strictEqual(r.activePivotsHigh.length, 0); // retired at idx=6
});

test(&quot;Mode 2 (Only Outbreaks &amp; Retest): skips wick sweep, catches bull retest sweep&quot;, () =&gt; {
  const r = computeLiquiditySweeps(barsHigh, { len: 2, opt: MODES.ONLY_OUTBREAKS });
  assert.strictEqual(r.events.length, 1);
  assert.strictEqual(r.events[0].side, &quot;BULL&quot;);
  assert.strictEqual(r.events[0].kind, &quot;OUTBREAK_RETEST_SWEEP&quot;);
  assert.strictEqual(r.events[0].lineStyle, &quot;dashed&quot;);
  assert.strictEqual(r.events[0].barIndex, 7);
  assert.strictEqual(r.events[0].level, 105);
  assert.strictEqual(r.events[0].wickExtreme, 104);
  assert.strictEqual(r.activePivotsHigh.length, 0); // tak=true removed pivot
});

test(&quot;Mode 3 (Wicks + Outbreaks &amp; Retest): catches both wick sweep and subsequent retest sweep&quot;, () =&gt; {
  const r = computeLiquiditySweeps(barsHigh, { len: 2, opt: MODES.WICKS_AND_OUTBREAKS });
  assert.deepStrictEqual(
    r.events.map((e) =&gt; [e.barIndex, e.side, e.kind]),
    [
      [5, &quot;BEAR&quot;, &quot;WICK_SWEEP&quot;],
      [7, &quot;BULL&quot;, &quot;OUTBREAK_RETEST_SWEEP&quot;],
    ]
  );
});

// 2. Symmetric Low Pivot: Bullish Wick Sweep + Breakdown + Bearish Outbreak &amp; Retest
const barsLow = [
  { h: 110, l: 106, c: 108 },
  { h: 108, l: 104, c: 105 },
  { h: 106, l: 100, c: 102 }, // Pivot Low @ idx=2 (prc=100)
  { h: 107, l: 103, c: 105 },
  { h: 108, l: 104, c: 106 }, // confirms PL @ idx=4
  { h: 105, l: 98, c: 101 },  // idx=5: Bull Wick Sweep (low 98 &lt; 100 &amp;&amp; close 101 &gt; 100)
  { h: 101, l: 95, c: 96 },   // idx=6: close 96 &lt; 100 (brk) &amp; &lt; box bottom 98 (mitigates box)
  { h: 101, l: 97, c: 98 },   // idx=7: Bear Outbreak &amp; Retest (high 101 &gt; 100 &amp;&amp; close 98 &lt; 100)
];

test(&quot;Symmetric aPivL: catches bull wick sweep + bear retest sweep and mitigates bull box&quot;, () =&gt; {
  const r = computeLiquiditySweeps(barsLow, { len: 2, opt: MODES.WICKS_AND_OUTBREAKS });
  assert.deepStrictEqual(
    r.events.map((e) =&gt; [e.barIndex, e.side, e.kind, e.wickExtreme]),
    [
      [5, &quot;BULL&quot;, &quot;WICK_SWEEP&quot;, 98],
      [7, &quot;BEAR&quot;, &quot;OUTBREAK_RETEST_SWEEP&quot;, 101],
    ]
  );
  // boxes[1] is the earlier bull box created at idx=5, mitigated at idx=6 (close 96 &lt; 98)
  assert.strictEqual(r.boxes[1].br, true);
  assert.strictEqual(r.boxes[0].br, false);
});

// 3. Strict equality boundary: close === P neither breaks nor triggers sweep
test(&quot;Boundary equality: close === P does NOT trigger sweep or breakout&quot;, () =&gt; {
  const b = [
    { h: 100, l: 98, c: 99 },
    { h: 102, l: 99, c: 101 },
    { h: 105, l: 100, c: 103 }, // PH=105 @ idx=2
    { h: 103, l: 99, c: 100 },
    { h: 102, l: 98, c: 101 },  // confirmed @ idx=4
    { h: 107, l: 101, c: 105 }, // close === 105: neither sweep nor breakout!
  ];
  const r = computeLiquiditySweeps(b, { len: 2, opt: MODES.ONLY_WICKS });
  assert.strictEqual(r.events.length, 0);
  assert.strictEqual(r.activePivotsHigh.length, 1);
  assert.strictEqual(r.activePivotsHigh[0].wic, false);
});

// 4. Duplicate wick suppression (get.wic === true prevents second wick sweep on same pivot)
test(&quot;One-shot wic flag: same pivot triggers wick sweep only once&quot;, () =&gt; {
  const b = [
    { h: 100, l: 98, c: 99 },
    { h: 102, l: 99, c: 101 },
    { h: 105, l: 100, c: 103 },
    { h: 103, l: 99, c: 100 },
    { h: 102, l: 98, c: 101 },
    { h: 106, l: 101, c: 104 }, // 1st wick sweep -&gt; triggers
    { h: 106.5, l: 101, c: 104 }, // 2nd wick on same pivot -&gt; suppressed
  ];
  const r = computeLiquiditySweeps(b, { len: 2, opt: MODES.ONLY_WICKS });
  assert.strictEqual(r.events.length, 1);
  assert.strictEqual(r.events[0].barIndex, 5);
});

// 5. Pivot tie-breaking: &quot;pine&quot; (rightmost wins flat top) vs &quot;strict&quot; (rejects flat top)
test(&quot;Pivot tie mode: pine selects rightmost equal peak; strict rejects flat equal top&quot;, () =&gt; {
  const flatTop = [
    { h: 100, l: 98, c: 99 },
    { h: 105, l: 99, c: 104 }, // equal peak 1
    { h: 105, l: 99, c: 104 }, // equal peak 2 @ idx=2
    { h: 102, l: 98, c: 100 },
    { h: 101, l: 98, c: 100 },
  ];
  const rPine = computeLiquiditySweeps(flatTop, { len: 2, pivotTieMode: &quot;pine&quot; });
  const rStrict = computeLiquiditySweeps(flatTop, { len: 2, pivotTieMode: &quot;strict&quot; });
  assert.strictEqual(rPine.activePivotsHigh.length, 1);
  assert.strictEqual(rPine.activePivotsHigh[0].bix, 2);
  assert.strictEqual(rStrict.activePivotsHigh.length, 0);
});

// 6. maxB box extension cap &amp; 2000-bar pivot expiry GC
test(&quot;maxB caps box right edge and maxPivotAge expires old pivots&quot;, () =&gt; {
  const b = [
    { h: 100, l: 98, c: 99 },
    { h: 105, l: 99, c: 102 }, // PH @ idx=1 (len=1)
    { h: 102, l: 99, c: 100 }, // confirmed @ idx=2
    { h: 106, l: 101, c: 104 }, // sweep @ idx=3 (box left=2)
  ];
  for (let i = 0; i &lt; 12; i++) {
    b.push({ h: 103, l: 101, c: 102 });
  }
  const r = computeLiquiditySweeps(b, { len: 1, maxB: 5, maxPivotAge: 10 });
  // Box created at triggerBar=3, left=2. Condition n - left - 1 &lt;= 5 =&gt; n &lt;= 8
  assert.strictEqual(r.boxes[0].right, 8);
  assert.strictEqual(r.boxes[0].br, false);
  // Pivot at bix=1 expired once n - 1 &gt; 10 (at n=12)
  assert.strictEqual(r.activePivotsHigh.length, 0);
});

// 7. Streaming vs Batch 100% parity
test(&quot;Streaming LiquiditySweepsEngine.step() matches batch computeLiquiditySweeps() 100%&quot;, () =&gt; {
  const eng = new LiquiditySweepsEngine({ len: 2, opt: MODES.WICKS_AND_OUTBREAKS });
  const streamEv = [];
  for (const bar of barsHigh) {
    streamEv.push(...eng.step(bar.h, bar.l, bar.c).events);
  }
  const batch = computeLiquiditySweeps(barsHigh, { len: 2, opt: MODES.WICKS_AND_OUTBREAKS });
  assert.deepStrictEqual(streamEv, batch.events);
});

// 8. market-engine server.js IDX tuple adapter (PRICE_SCALE=10000 integer-exact)
test(&quot;market-engine server.js tuple adapter ([TS, TIME, O, H, L, C, VOL, AMT], PRICE_SCALE=10000)&quot;, () =&gt; {
  const S = 10000;
  const serverBars = barsLow.map((b, i) =&gt; [
    1795107600 + i * 60,
    `09:${String(30 + i).padStart(2, &quot;0&quot;)}`,
    b.c * S,
    b.h * S,
    b.l * S,
    b.c * S,
    1000,
    100000,
  ]);
  const r = computeLiquiditySweepsFromServerBars(serverBars, {
    len: 2,
    opt: MODES.ONLY_WICKS,
    priceScale: S,
  });
  assert.strictEqual(r.events.length, 1);
  assert.strictEqual(r.events[0].side, &quot;BULL&quot;);
  assert.strictEqual(r.events[0].level, 100);
  assert.strictEqual(r.events[0].wickExtreme, 98);
  assert.strictEqual(r.events[0].meta.time, &quot;09:35&quot;);
});

// 9. Performance benchmark on 5,000 synthetic bars (deterministic PRNG)
test(&quot;Performance benchmark: 5,000 bars completes in &lt; 100ms&quot;, () =&gt; {
  let seed = 42;
  const rand = () =&gt; {
    seed = (seed * 1664525 + 1013904223) &gt;&gt;&gt; 0;
    return seed / 0x100000000;
  };
  let px = 100.0;
  const big = [];
  for (let i = 0; i &lt; 5000; i++) {
    const step = (rand() - 0.5) * 2.0;
    const o = px;
    const c = px + step;
    const h = Math.max(o, c) + rand() * 1.2;
    const l = Math.min(o, c) - rand() * 1.2;
    px = c;
    big.push({ h, l, c });
  }
  const t0 = performance.now();
  const res = computeLiquiditySweeps(big, { len: 5, opt: MODES.WICKS_AND_OUTBREAKS });
  const dt = performance.now() - t0;
  assert(res.events.length &gt; 0, &quot;expected sweeps in 5000-bar random walk&quot;);
  assert(dt &lt; 100, `too slow: ${dt.toFixed(2)}ms`);
  console.log(`  BENCH_5000_BARS: ${dt.toFixed