整理與實作:A59 (A594117)|日期:2026-11-20|狀態:算法+編碼+實測一次歸檔保存,供後續修改 market-engine/server.js(eed819a94078)時直接加插。
官方源碼來源:TradingView JRqryeJ5 / PUB;26391b932d3145879b67deca62305c9a(Pine Script v5,160 行,5,796 B,CC BY-NC-SA 4.0 © LuxAlgo,sha256=18be09f34ebf371e…)。
本歸檔內嵌檔案指紋:v2_liquidity_sweeps.js(11406 B,sha256=e72cfd2f121b6639…)、test_v2_liquidity_sweeps.js(9075 B,sha256=85df658d186232af…)。
べーた (@foodloss_otoko) 於 2026-11-19T17:00:19Z 發佈 2123461381030834442,推薦 TradingView 指標 Liquidity Sweeps [LuxAlgo](非 TeamViewer;尾帖導流 LINE 領 EA 與本指標無關且未驗證)。high、low、close 與順序索引 bar_index(外加 4 個參數 len/opt/extend/maxB)。完全不使用 open(0 次)、volume(0 次)、ta.atr(0 次)、request.*(0 次)或任何 L2 盤口數據。| 參數 | 預設值 | 範圍 / 選項 | 說明 |
|---|---|---|---|
len (Swings) | 5 | 整數 ≥ 1 | 對稱擺動樞紐左右窗口,確認滯後 len 根(確認後不重繪) |
opt (options) | 'Only Wicks' | Only Wicks / Only Outbreaks & Retest / Wicks + Outbreaks & Retest | 控制掃蕩偵測型態 |
extend | true | bool | 是否持續向右延伸 Sweep Area 區域框 |
maxB | 300 | 1..5000 | Sweep Area 最多延伸 K 線根數 |
maxPivotAge | 2000 | 整數 ≥ 1 | 歷史樞紐最長保留根數(超過 n - bix > 2000 淘汰) |
pivotTieMode | 'pine' | pine / strict | pine 採左 ≤/≥、右嚴格 </>(平頂/平底取最右端,防雙重入池);strict 兩側嚴格 |
n = bar_index)n ≥ 2*len,檢查候選柱 c = n - len:high[c] 為窗口 [c-len .. c+len] 局部高點 → aPivH.unshift({prc: high[c], bix: c, brk:false, mit:false, tak:false, wic:false})low[c] 為窗口 [c-len .. c+len] 局部低點 → aPivL.unshift({prc: low[c], bix: c, brk:false, mit:false, tak:false, wic:false})
aPivH 掃蕩與突破判定(L100–L123,記 P = get.prc):!brk):若 close[n] > P → Only Wicks 設 mit=true(真突破淘汰),否則設 brk=true。!oO && !wic && high[n] > P && close[n] < P → 建看空框(dr=+1, top=high[n], bottom=P)+ 3-bar 輔助線 y=low[n] + wic=true。brk):若 close[n] < P 設 mit=true;看多突破回測掃蕩(Type 2, dashed):!oW && low[n] < P && close[n] > P → 建看多框(dr=-1, top=P, bottom=low[n])+ 3-bar 輔助線 y=high[n] + tak=true。(n - bix > 2000) || mit || tak 移除該樞紐。
aPivL 對稱狀態機(L125–L147):!brk):若 close[n] < P → Only Wicks 設 mit=true,否則 brk=true。!oO && !wic && low[n] < P && close[n] > P → 建看多框(dr=-1, top=P, bottom=low[n])+ 3-bar 輔助線 y=high[n] + wic=true。brk):若 close[n] > P 設 mit=true;看空突破回測掃蕩(Type 2, dashed):!oW && high[n] > P && close[n] < P → 建看空框(dr=+1, top=high[n], bottom=P)+ 3-bar 輔助線 y=low[n] + tak=true。(n - bix > 2000) || mit || tak 移除該樞紐。
extend == true,對每個未失效(!bx.br)且 n - bx.left - 1 <= maxB 之區域框:bx.right = n;dr == -1)若 close[n] < bx.bottom → bx.br = true(停止延伸);dr == +1)若 close[n] > bx.top → bx.br = true(停止延伸)。
market-engine/server.js 串接介面:直接讀取 IDX = { TS:0, TIME:1, OPEN:2, HIGH:3, LOW:4, CLOSE:5, VOL:6, AMT:7 }(L407)與 PRICE_SCALE = 10000(L400),整數原值精確比較零浮點誤差,僅於輸出還原顯示價;支援串流 step() 與批次 computeLiquiditySweepsFromServerBars()。
v2_liquidity_sweeps.js)"use strict";
/**
* 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: "Only Wicks",
ONLY_OUTBREAKS: "Only Outbreaks & Retest",
WICKS_AND_OUTBREAKS: "Wicks + Outbreaks & Retest",
});
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 < 1) {
throw new RangeError(`len must be an integer >= 1, got ${opts.len}`);
}
const opt = opts.opt === undefined ? MODES.ONLY_WICKS : String(opts.opt);
if (
opt !== MODES.ONLY_WICKS &&
opt !== MODES.ONLY_OUTBREAKS &&
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 < 1 || maxB > 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 < 1) {
throw new RangeError(`maxPivotAge must be an integer >= 1, got ${opts.maxPivotAge}`);
}
// TradingView ta.pivothigh/low tie semantics:
// "pine" => cand >= left && cand > right (rightmost bar wins flat tops/bottoms, no double-fire)
// "strict" => cand > left && cand > right (strict inequality on both sides)
const pivotTieMode = opts.pivotTieMode === undefined ? "pine" : String(opts.pivotTieMode);
if (pivotTieMode !== "pine" && pivotTieMode !== "strict") {
throw new RangeError(`pivotTieMode must be "pine" or "strict", 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 < 1) {
throw new RangeError(`maxBoxes must be an integer >= 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 > 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 < len; k++) {
if (pivotTieMode === "strict") {
if (!(this._winH[k] < ch)) isPH = false;
if (!(this._winL[k] > cl)) isPL = false;
} else {
if (!(this._winH[k] <= ch)) isPH = false;
if (!(this._winL[k] >= cl)) isPL = false;
}
}
for (let k = len + 1; k < this._winCap; k++) {
if (!(this._winH[k] < ch)) isPH = false;
if (!(this._winL[k] > 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) => {
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, // "dotted" | "dashed"
guideLine: { x1: n, x2: n + 3, y: guidePrice }, // lnDot 3-bar opposite-wick helper
};
this.aBoxBr.unshift(box);
if (this.aBoxBr.length > maxBoxes) {
this.aBoxBr.length = maxBoxes;
}
events.push({
barIndex: n,
meta,
side: dir === -1 ? "BULL" : "BEAR",
kind, // "WICK_SWEEP" | "OUTBREAK_RETEST_SWEEP"
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 >= 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) {
pushBox(1, h, get.prc, get.bix, get.prc, "WICK_SWEEP", "dotted", l);
get.wic = true;
}
}
} else {
if (c < get.prc) {
get.mit = true;
}
if (!this.oW && l < get.prc && c > get.prc) {
pushBox(-1, get.prc, l, get.bix, get.prc, "OUTBREAK_RETEST_SWEEP", "dashed", h);
get.tak = true;
}
}
}
if (n - get.bix > 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 >= 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) {
pushBox(-1, get.prc, l, get.bix, get.prc, "WICK_SWEEP", "dotted", h);
get.wic = true;
}
}
} else {
if (c > get.prc) {
get.mit = true;
}
if (!this.oW && h > get.prc && c < get.prc) {
pushBox(1, h, get.prc, get.bix, get.prc, "OUTBREAK_RETEST_SWEEP", "dashed", l);
get.tak = true;
}
}
}
if (n - get.bix > maxPivotAge || get.mit || get.tak) {
this.aPivL.splice(i, 1);
}
}
// Step 4: Sweep Area box extension & mitigation (Pine L149-157)
const mitigatedBoxes = [];
if (extend) {
for (let i = 0; i < this.aBoxBr.length; i++) {
const bx = this.aBoxBr[i];
if (!bx.br && n - bx.left - 1 <= maxB) {
bx.right = n;
if (bx.dr === -1 && c < bx.bottom) {
bx.br = true;
mitigatedBoxes.push(bx);
}
if (bx.dr === 1 && c > 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) => !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 < 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 < 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 > 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,
};
PASS [1] Mode 1 (Only Wicks): catches bear wick sweep, retires on close breakout, mitigates box
PASS [2] Mode 2 (Only Outbreaks & Retest): skips wick sweep, catches bull retest sweep
PASS [3] Mode 3 (Wicks + Outbreaks & 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 < 100ms
ALL_TESTS_PASSED: 11/11
test_v2_liquidity_sweeps.js)"use strict";
const assert = require("assert");
const { performance } = require("perf_hooks");
const {
MODES,
LiquiditySweepsEngine,
computeLiquiditySweeps,
computeLiquiditySweepsFromServerBars,
} = require("./v2_liquidity_sweeps.js");
let passed = 0;
function test(name, fn) {
fn();
passed += 1;
console.log(`PASS [${passed}] ${name}`);
}
// 1. Bearish Wick Sweep + Close Breakout + Bullish Outbreak & 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 > 105 && close 104 < 105)
{ h: 109, l: 104, c: 108 }, // idx=6: close 108 > 105 (mit in Only Wicks; brk in Outbreaks) & > box top 107 (mitigates box)
{ h: 107, l: 104, c: 106 }, // idx=7: Bull Outbreak & Retest (low 104 < 105 && close 106 > 105)
];
test("Mode 1 (Only Wicks): catches bear wick sweep, retires on close breakout, mitigates box", () => {
const r = computeLiquiditySweeps(barsHigh, { len: 2, opt: MODES.ONLY_WICKS });
assert.strictEqual(r.events.length, 1);
assert.strictEqual(r.events[0].side, "BEAR");
assert.strictEqual(r.events[0].kind, "WICK_SWEEP");
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 > top 107)
assert.strictEqual(r.activePivotsHigh.length, 0); // retired at idx=6
});
test("Mode 2 (Only Outbreaks & Retest): skips wick sweep, catches bull retest sweep", () => {
const r = computeLiquiditySweeps(barsHigh, { len: 2, opt: MODES.ONLY_OUTBREAKS });
assert.strictEqual(r.events.length, 1);
assert.strictEqual(r.events[0].side, "BULL");
assert.strictEqual(r.events[0].kind, "OUTBREAK_RETEST_SWEEP");
assert.strictEqual(r.events[0].lineStyle, "dashed");
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("Mode 3 (Wicks + Outbreaks & Retest): catches both wick sweep and subsequent retest sweep", () => {
const r = computeLiquiditySweeps(barsHigh, { len: 2, opt: MODES.WICKS_AND_OUTBREAKS });
assert.deepStrictEqual(
r.events.map((e) => [e.barIndex, e.side, e.kind]),
[
[5, "BEAR", "WICK_SWEEP"],
[7, "BULL", "OUTBREAK_RETEST_SWEEP"],
]
);
});
// 2. Symmetric Low Pivot: Bullish Wick Sweep + Breakdown + Bearish Outbreak & 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 < 100 && close 101 > 100)
{ h: 101, l: 95, c: 96 }, // idx=6: close 96 < 100 (brk) & < box bottom 98 (mitigates box)
{ h: 101, l: 97, c: 98 }, // idx=7: Bear Outbreak & Retest (high 101 > 100 && close 98 < 100)
];
test("Symmetric aPivL: catches bull wick sweep + bear retest sweep and mitigates bull box", () => {
const r = computeLiquiditySweeps(barsLow, { len: 2, opt: MODES.WICKS_AND_OUTBREAKS });
assert.deepStrictEqual(
r.events.map((e) => [e.barIndex, e.side, e.kind, e.wickExtreme]),
[
[5, "BULL", "WICK_SWEEP", 98],
[7, "BEAR", "OUTBREAK_RETEST_SWEEP", 101],
]
);
// boxes[1] is the earlier bull box created at idx=5, mitigated at idx=6 (close 96 < 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("Boundary equality: close === P does NOT trigger sweep or breakout", () => {
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("One-shot wic flag: same pivot triggers wick sweep only once", () => {
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 -> triggers
{ h: 106.5, l: 101, c: 104 }, // 2nd wick on same pivot -> 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: "pine" (rightmost wins flat top) vs "strict" (rejects flat top)
test("Pivot tie mode: pine selects rightmost equal peak; strict rejects flat equal top", () => {
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: "pine" });
const rStrict = computeLiquiditySweeps(flatTop, { len: 2, pivotTieMode: "strict" });
assert.strictEqual(rPine.activePivotsHigh.length, 1);
assert.strictEqual(rPine.activePivotsHigh[0].bix, 2);
assert.strictEqual(rStrict.activePivotsHigh.length, 0);
});
// 6. maxB box extension cap & 2000-bar pivot expiry GC
test("maxB caps box right edge and maxPivotAge expires old pivots", () => {
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 < 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 <= 5 => n <= 8
assert.strictEqual(r.boxes[0].right, 8);
assert.strictEqual(r.boxes[0].br, false);
// Pivot at bix=1 expired once n - 1 > 10 (at n=12)
assert.strictEqual(r.activePivotsHigh.length, 0);
});
// 7. Streaming vs Batch 100% parity
test("Streaming LiquiditySweepsEngine.step() matches batch computeLiquiditySweeps() 100%", () => {
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("market-engine server.js tuple adapter ([TS, TIME, O, H, L, C, VOL, AMT], PRICE_SCALE=10000)", () => {
const S = 10000;
const serverBars = barsLow.map((b, i) => [
1795107600 + i * 60,
`09:${String(30 + i).padStart(2, "0")}`,
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, "BULL");
assert.strictEqual(r.events[0].level, 100);
assert.strictEqual(r.events[0].wickExtreme, 98);
assert.strictEqual(r.events[0].meta.time, "09:35");
});
// 9. Performance benchmark on 5,000 synthetic bars (deterministic PRNG)
test("Performance benchmark: 5,000 bars completes in < 100ms", () => {
let seed = 42;
const rand = () => {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 0x100000000;
};
let px = 100.0;
const big = [];
for (let i = 0; i < 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 > 0, "expected sweeps in 5000-bar random walk");
assert(dt < 100, `too slow: ${dt.toFixed(2)}ms`);
console.log(` BENCH_5000_BARS: ${dt.toFixed(2)}ms, events=${res.events.length}, activePivH=${res.snapshot.activePivotsHigh}, activePivL=${res.snapshot.activePivotsLow}`);
});
console.log(`ALL_TESTS_PASSED: ${passed}/${passed}`);
// 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
//-----------------------------------------------------------------------------}