A85 — V2 指標算法設計與可執行編碼(Liquidity Sweeps [LuxAlgo])

對應 Relay 決議:COMMONS seq=65053(接 65024 / 65033,定調為 V2 指標;僅保存算法+編碼,不改動現行 Line ② market-engine-server.js)。

座席:A85 (A854611) | 日期:2026-11-20 | 運行環境:Node.js v20.20.2

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

一、文件與產物清單(Manifest)

檔名BytesSHA-256
liquidity_sweeps_luxalgo_JRqryeJ5.pine579618be09f34ebf371e4cc8997ba77c29cc1ada4612a5529a79994694ec9b6ba12d
v2_liquidity_sweeps.js7698054e5b96f344a348237964f16fd20226ad97da91fb69d89ea8fe0aed55d25884
test_v2_liquidity_sweeps.js5294f64ef4cfe49879b090097738dacc538bc549fa7654069ea466eec09d879693ca

二、V2 指標算法規格(嚴格對齊 TradingView JRqryeJ5)

  1. 唯一市場數據輸入:單一圖表 K 線序列之 high、low、close 與 bar_index(零讀取 open、volume、盤口 DOM 或跨週期資料)。
  2. Pivot 流動性池(LqL)建立:
  3. 三種模式旗標:Only Wicks(oW,預設)、Only Outbreaks & Retest(oO)、Wicks + Outbreaks & Retest(WO)。
  4. 掃蕩偵測狀態機(對 aPivH/aPivL 逐一由舊至新掃描未失效項目):
  5. Sweep Area 延伸與失效:當 extend = true 且 n - box.left - 1 ≤ maxB(預設 300)時持續延伸右界;多頭框(dr = -1)遇 close < bottom 停止延伸,空頭框(dr = 1)遇 close > top 停止延伸。
  6. 備註(整合進 V2 Server 時的實作邊界):原 Pine 指標用於圖表實時標記(無內建 alertcondition 與下單邏輯);日後若接駁進 market-engine-server.js 作為 V2 策略/訊號模組,應綁定 closed-bar(已收盤 K 線)才呼叫 LiquiditySweepsEngine.step(bar),以配合原帖作者「等實體收回確定、止損置於掃蕩極值外」之執行規則。

三、Node.js v20 實測結果(node test_v2_liquidity_sweeps.js,rc=0)

PASS 1: Pivot confirmation lag (len=2) & Bearish Wick Sweep + Sweep Area mitigation
PASS 2: Bullish Wick Sweep & close-through retires LqL in Only Wicks
PASS 3: Only Outbreaks & 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

四、可執行 Node.js 模組(v2_liquidity_sweeps.js)

'use strict';

/**
 * 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([
  'Only Wicks',
  'Only Outbreaks & Retest',
  'Wicks + Outbreaks & Retest',
]);

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 < 1) {
      throw new RangeError(`len must be integer >= 1, got ${opts.len}`);
    }
    const mode = opts.mode || 'Only Wicks';
    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 < 1 || maxB > 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 === 'Only Wicks';
    this.oO = mode === 'Only Outbreaks & Retest';
    this.WO = mode === 'Wicks + Outbreaks & Retest';
    this.extend = extend;
    this.maxB = maxB;
    this.maxPivotAge = maxPivotAge;

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

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

  _pivotLowAtConfirm(n) {
    const L = this.len;
    if (n < 2 * L) return null;
    const midIdx = n - L;
    const midVal = this.bars[midIdx].l;
    for (let k = midIdx - L; k <= n; k++) {
      if (k === midIdx) continue;
      if (!(midVal < 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 >= 0; i--) {
      const get = this.aPivH[i];
      if (!get.mit) {
        if (!get.brk) {
          if (c > get.prc) {
            if (!this.oW) get.brk = true;
            else get.mit = true;
          }
          if (!this.oO && !get.wic) {
            if (h > get.prc && c < get.prc) {
              const box = {
                left: n - 1,
                right: n + 1,
                top: h,
                bottom: get.prc,
                br: false,
                dr: 1,
                kind: 'BEAR_WICK_SWEEP',
                lqlPrice: get.prc,
                lqlBar: get.bix,
                triggerBar: n,
                dotGuideY: l,
                lineStyle: 'dotted',
              };
              this.aBoxBr.unshift(box);
              get.wic = true;
              stepEvents.push(box);
            }
          }
        } else {
          if (c < get.prc) {
            get.mit = true;
          }
          if (!this.oW && l < get.prc && c > get.prc) {
            const box = {
              left: n - 1,
              right: n + 1,
              top: get.prc,
              bottom: l,
              br: false,
              dr: -1,
              kind: 'BULL_RETEST_SWEEP',
              lqlPrice: get.prc,
              lqlBar: get.bix,
              triggerBar: n,
              dotGuideY: h,
              lineStyle: 'dashed',
            };
            this.aBoxBr.unshift(box);
            get.tak = true;
            stepEvents.push(box);
          }
        }
      }
      if (n - get.bix > 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 >= 0; i--) {
      const get = this.aPivL[i];
      if (!get.mit) {
        if (!get.brk) {
          if (c < get.prc) {
            if (!this.oW) get.brk = true;
            else get.mit = true;
          }
          if (!this.oO && !get.wic) {
            if (l < get.prc && c > get.prc) {
              const box = {
                left: n - 1,
                right: n + 1,
                top: get.prc,
                bottom: l,
                br: false,
                dr: -1,
                kind: 'BULL_WICK_SWEEP',
                lqlPrice: get.prc,
                lqlBar: get.bix,
                triggerBar: n,
                dotGuideY: h,
                lineStyle: 'dotted',
              };
              this.aBoxBr.unshift(box);
              get.wic = true;
              stepEvents.push(box);
            }
          }
        } else {
          if (c > get.prc) {
            get.mit = true;
          }
          if (!this.oW && h > get.prc && c < get.prc) {
            const box = {
              left: n - 1,
              right: n + 1,
              top: h,
              bottom: get.prc,
              br: false,
              dr: 1,
              kind: 'BEAR_RETEST_SWEEP',
              lqlPrice: get.prc,
              lqlBar: get.bix,
              triggerBar: n,
              dotGuideY: l,
              lineStyle: 'dashed',
            };
            this.aBoxBr.unshift(box);
            get.tak = true;
            stepEvents.push(box);
          }
        }
      }
      if (n - get.bix > this.maxPivotAge || get.mit || get.tak) {
        this.aPivL.splice(i, 1);
      }
    }

    // Extend & mitigate Sweep Area boxes
    if (this.extend) {
      for (const bx of this.aBoxBr) {
        if (!bx.br && n - bx.left - 1 <= this.maxB) {
          bx.right = n;
          if (bx.dr === -1 && c < bx.bottom) bx.br = true;
          if (bx.dr === 1 && c > 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,
};

五、單元測試腳本(test_v2_liquidity_sweeps.js)

'use strict';

const assert = require('assert');
const { LiquiditySweepsEngine, computeLiquiditySweeps } = require('./v2_liquidity_sweeps');

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

// 2. Bullish Wick Sweep & close-below mitigation in Only Wicks
runTest('Bullish Wick Sweep & close-through retires LqL in Only Wicks', () => {
  const bars = [
    bar(105, 100, 102),  // 0
    bar(103, 96, 98),    // 1
    bar(100, 90, 95),    // 2 <- pivot low = 90
    bar(99, 93, 97),     // 3
    bar(101, 95, 99),    // 4 <- pl=90 confirmed (bix=2)
    bar(98, 87, 92),     // 5 <- low=87 < 90, close=92 > 90 => BULL_WICK_SWEEP
    bar(94, 88, 89),     // 6 <- close=89 < 90 (mitigates aPivL in Only Wicks), not < 87 yet
    bar(91, 85, 86),     // 7 <- close=86 < bottom(87) => box mitigated (br=true)
  ];
  const res = computeLiquiditySweeps(bars, { len: 2, mode: 'Only Wicks' });
  assert.strictEqual(res.events.length, 1);
  const ev = res.events[0];
  assert.strictEqual(ev.kind, 'BULL_WICK_SWEEP');
  assert.strictEqual(ev.lqlBar, 2);
  assert.strictEqual(ev.lqlPrice, 90);
  assert.strictEqual(ev.triggerBar, 5);
  assert.strictEqual(ev.top, 90);
  assert.strictEqual(ev.bottom, 87);
  assert.strictEqual(ev.br, true);
  assert.strictEqual(ev.right, 7);
  assert.strictEqual(res.activePivL.length, 0);
});

// 3. Only Outbreaks & Retest mode
runTest('Only Outbreaks & Retest mode ignores wick-only and triggers dashed retest', () => {
  const bars = [
    bar(101, 99, 100),   // 0
    bar(105, 100, 104),  // 1
    bar(110, 103, 108),  // 2 <- pivot high = 110
    bar(106, 102, 103),  // 3
    bar(104, 100, 102),  // 4 <- ph=110 confirmed
    bar(112, 105, 109),  // 5 <- wick only (must NOT trigger in Only Outbreaks & Retest)
    bar(115, 108, 114),  // 6 <- close=114 > 110 => get.brk=true
    bar(113, 109, 111),  // 7 <- low=109 < 110 && close=111 > 110 => BULL_RETEST_SWEEP (dashed)
  ];
  const res = computeLiquiditySweeps(bars, { len: 2, mode: 'Only Outbreaks & Retest' });
  assert.strictEqual(res.events.length, 1);
  const ev = res.events[0];
  assert.strictEqual(ev.kind, 'BULL_RETEST_SWEEP');
  assert.strictEqual(ev.lineStyle, 'dashed');
  assert.strictEqual(ev.triggerBar, 7);
  assert.strictEqual(ev.top, 110);
  assert.strictEqual(ev.bottom, 109);
  assert.strictEqual(res.activePivH.length, 0);
});

// 4. Strict pivot tie-breaking
runTest('Strict pivot detection rejects plateau/equal highs', () => {
  const bars = [
    bar(101, 99, 100),
    bar(110, 100, 105),
    bar(110, 101, 104),
    bar(105, 100, 102),
    bar(102, 98, 100),
    bar(112, 100, 105),
  ];
  const res = computeLiquiditySweeps(bars, { len: 2, mode: 'Only Wicks' });
  assert.strictEqual(res.events.length, 0);
  assert.strictEqual(res.activePivH.length, 0);
});

// 5. maxB extension cap & pivot age expiry
runTest('maxB box extension cap and pivot age expiry', () => {
  const eng = new LiquiditySweepsEngine({ len: 1, mode: 'Only Wicks', maxB: 3, maxPivotAge: 10 });
  const seq = [
    bar(100, 99, 100),   // 0
    bar(110, 100, 105),  // 1 <- pivot high at bix=1
    bar(104, 100, 102),  // 2 <- bix=1 confirmed
    bar(112, 101, 108),  // 3 <- sweep of bix=1 (box.left=2), also strict peak for bix=3
    bar(109, 102, 106),  // 4: n - left - 1 = 1 <= 3 -> right=4 (bix=3 confirmed)
    bar(109, 102, 106),  // 5: n - left - 1 = 2 <= 3 -> right=5
    bar(109, 102, 106),  // 6: n - left - 1 = 3 <= 3 -> right=6
    bar(109, 102, 106),  // 7: n - left - 1 = 4 > 3  -> stops at 6
  ];
  for (const b of seq) eng.step(b);
  assert.strictEqual(eng.aBoxBr[0].right, 6);
  for (let k = 8; k <= 12; k++) eng.step(bar(105, 100, 102));
  assert.strictEqual(eng.aPivH.some((p) => p.bix === 1), false); // bix=1 expired (12 - 1 = 11 > 10)
  for (let k = 13; k <= 14; k++) eng.step(bar(105, 100, 102));
  assert.strictEqual(eng.aPivH.length, 0); // bix=3 expired (14 - 3 = 11 > 10)
});

console.log(`ALL_TESTS_PASSED=${passed}/5`);

六、TradingView 官方原始 Pine Script v5 源碼(PUB;26391b932d3145879b67deca62305c9a v1.0,CC BY-NC-SA 4.0)

// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo

//@version=5
indicator( 'Liquidity Sweeps [LuxAlgo]'
         , 'LuxAlgo - Liquidity Sweeps'
         ,  max_lines_count=500
         ,  max_boxes_count=500
         ,  overlay=true
         )

//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
len    = input.int(5, 'Swings', minval=1, group='Liquidity Sweeps')
opt    = input.string('Only Wicks', 'options'
       , options=['Only Wicks', 'Only Outbreaks & Retest', 'Wicks + Outbreaks & Retest'], group='Liquidity Sweeps')

colBl  = input.color(#089981, 'Bull ', group='Liquidity Sweeps', inline='c1')
colBr  = input.color(#f23645, 'Bear' , group='Liquidity Sweeps', inline='c2')
colBl2 = input.color(#08998180,  ''  , group='Liquidity Sweeps', inline='c1')
colBr2 = input.color(#f2364580,  ''  , group='Liquidity Sweeps', inline='c2')

extend = input.bool(true, 'Extend', group='Sweep Area') 
maxB   = input.int(300, 'Max bars', minval=1, maxval=5000, group='Sweep Area')
colBl3 = input.color(#08998141, 'Bull ', group='Sweep Area')
colBr3 = input.color(#f2364541, 'Bear' , group='Sweep Area')

oW = opt == 'Only Wicks'
oO = opt == 'Only Outbreaks & Retest'
WO = opt == 'Wicks + Outbreaks & Retest'

n = bar_index 

//-----------------------------------------------------------------------------}      
//UDT's
//-----------------------------------------------------------------------------{
type piv
    float prc // price
    int   bix // bar_index
    bool  brk // broken
    bool  mit // mitigated
    bool  tak // taken
    bool  wic // wick
    line  lin 

type boxBr 
    box  bx 
    line ln
    bool br
    int  dr

//-----------------------------------------------------------------------------}      
//Variables
//-----------------------------------------------------------------------------{
var array< piv >aPivH  = array.new< piv >(1, piv.new  ())
var array< piv >aPivL  = array.new< piv >(1, piv.new  ())
var array<boxBr>aBoxBr = array.new<boxBr>(1, boxBr.new())

//-----------------------------------------------------------------------------}      
//Methods - functions
//-----------------------------------------------------------------------------{
method n(float piv) => bool out = not na(piv)

method p(piv piv, float val) => float out = (100 / piv.prc * val) - 100

method l(piv get, color c, string s='sd') => 
    style = switch s 
        'dt' => line.style_dotted
        'ds' => line.style_dashed
        =>      line.style_solid 
    line.new(get.bix, get.prc, n, get.prc, color=c, style = style)

method br(piv get, color c3, color c, int d) =>
    y1 = d == 1 ? high : get.prc
    y2 = d == 1 ? get.prc : low
    boxBr.new( 
     box.new(n -1, y1, n +1, y2
     , border_color
     = color.new(
       na, na   )
     , bgcolor=c3)
     , line.new(n , y1, n, y2, color=c, width=3)
     , false
     , d)

lnDot(y, c) => line.new(n, y, n+3, y, color=c, style=line.style_dotted)

//-----------------------------------------------------------------------------}      
//Execution
//-----------------------------------------------------------------------------{
ph = ta.pivothigh(len, len)
pl = ta.pivotlow (len, len)

if ph.n() 
    aPivH.unshift(piv.new(ph, n -len, false, false, false, false))

if pl.n() 
    aPivL.unshift(piv.new(pl, n -len, false, false, false, false)) 

for i = aPivH.size() -1 to 0
    get = aPivH.get(i)
    if not get.mit
        if not get.brk
            if close > get.prc 
                if not oW
                    get.brk := true
                else 
                    get.mit := true
            if not oO and not get.wic 
                if high > get.prc and close < get.prc                   
                    aBoxBr.unshift(get.br(colBr3, colBr, 1))       
                    get.l(colBr2, 'dt'), lnDot(low, colBr)
                    get.wic := true  
        else 
            if close < get.prc 
                get.mit := true
            if not oW and low < get.prc and close > get.prc                    
                aBoxBr.unshift(get.br(colBl3, colBl, -1))    
                get.l(colBl2, 'ds'), lnDot(high, colBl)
                get.tak := true 

    if n - get.bix > 2000 or get.mit or get.tak 
        aPivH.remove(i).lin.delete()

for i = aPivL.size() -1 to 0
    get = aPivL.get(i)
    if not get.mit
        if not get.brk
            if close < get.prc 
                if not oW
                    get.brk := true
                else 
                    get.mit := true
            if not oO and not get.wic 
                if low < get.prc and close > get.prc                              
                    aBoxBr.unshift(get.br(colBl3, colBl, -1))     
                    get.l(colBl2, 'dt'), lnDot(high, colBl)
                    get.wic := true 
        else 
            if close > get.prc 
                get.mit := true
            if not oW and high > get.prc and close < get.prc                     
                aBoxBr.unshift(get.br(colBr3, colBr, 1))    
                get.l(colBr2, 'ds'), lnDot(low, colBr)
                get.tak := true  

    if n - get.bix > 2000 or get.mit or get.tak 
        aPivL.remove(i).lin.delete()

if extend
    for bx in aBoxBr 
        if not bx.br and n - bx.bx.get_left() -1 <= maxB 
            bx.bx.set_right(bar_index)
            if bx.dr == -1 and close < bx.bx.get_bottom() 
                bx.br := true 
            if bx.dr ==  1 and close > bx.bx.get_top   () 
                bx.br := true 

//-----------------------------------------------------------------------------}