A38 — V2 指標定案規格與參考實作:Liquidity Sweeps [LuxAlgo]

席位 A382497依據 65024 / 65033 / 65053狀態:已封存待整合至 Server

1. 定調與純 K 線輸入契約(65033 / 65053)

本指標正式定為 V2 指標。經對 TradingView 官方開源 Pine Script v5 原碼(PUB;26391b932d3145879b67deca62305c9a,5,793 B)逐字掃描驗證,計算 100% 僅依賴單一週期普通歷史 K 線序列:

欄位原碼次數用途
high5 次 + ta.pivothigh(len,len)搵 Swing High、測 Bear Sweep 刺穿同上沿
low5 次 + ta.pivotlow(len,len)搵 Swing Low、測 Bull Sweep 刺穿同下沿
close10 次區分影線掃蕩(Wick)定實體突破(Outbreak),及判定 Sweep Box 失效
bar_index3 次Pivot 時間座標、Sweep 座標與方框延伸
open / volume / time / request.* / L2 / Tick全部 0 次完全無需;現成圖表 Dump 嘅 K 線 H/L/C 序列已足夠

2. V2 算法狀態機(供日後 Server / 程式接駁)

  1. Pivot 偵測(延遲 len 根確認):預設 len=5。當到達第 i 支 K 線時,檢查 p = i - len 是否滿足:
    • Pivot High:high[p] 嚴格大於左側 len 支(p-len .. p-1)且大於等於右側 len 支(p+1 .. i);成立則把 {idx: p, prc: high[p], broken: false} 插入現役 Pivot High 序列。
    • Pivot Low:low[p] 嚴格小於左側 len 支且小於等於右側 len 支;成立則插入現役 Pivot Low 序列。
  2. Sweep / Outbreak 判定(每個新收盤 K 線 i):
    • 對每個未完結嘅 Pivot High P:
      • 若 close[i] > P.prc:屬於 Bear Outbreak(實體向上突破),標記 P.broken = true;若模式為 Only Outbreaks 或 All,建立 bear 方框 [P.prc, high[i]]。
      • 否則若 high[i] > P.prc 且 close[i] <= P.prc:屬於 Bear Wick Sweep(假突破上影掃蕩),標記 P.broken = true;若模式為 Only Wicks(預設)或 All,建立 bear 方框 [P.prc, high[i]]。
    • 對每個未完結嘅 Pivot Low P:對稱判定——close[i] < P.prc 為 Bull Outbreak;low[i] < P.prc 且 close[i] >= P.prc 為 Bull Wick Sweep,建立 bull 方框 [low[i], P.prc]。
  3. 方框延伸與失效(Extend & Max Boxes):若開啟 extend=true,對未失效方框逐支更新右邊界至 i,直到某支 K 線 close[i] 徹底貫穿針尖(Bear 方框 close[i] > wick_extreme;Bull 方框 close[i] < wick_extreme)即停止延伸。總方框數量上限預設 max_boxes = 300。

3. Python 3 參考實作(純標準庫・已通過自測)

from dataclasses import dataclass
from typing import List, Optional, Literal

ModeType = Literal["Only Wicks", "Only Outbreaks", "All"]

@dataclass
class SweepBox:
    side: Literal["bull", "bear"]
    pivot_idx: int
    pivot_price: float
    sweep_idx: int
    wick_extreme: float
    broken: bool = False
    end_idx: int = 0
    invalidated: bool = False

def _is_pivothigh(highs: List[float], idx: int, length: int) -> Optional[float]:
    if idx < 2 * length:
        return None
    p = idx - length
    cand = highs[p]
    left = highs[p - length : p]
    right = highs[p + 1 : idx + 1]
    if all(cand > x for x in left) and all(cand >= x for x in right):
        return cand
    return None

def _is_pivotlow(lows: List[float], idx: int, length: int) -> Optional[float]:
    if idx < 2 * length:
        return None
    p = idx - length
    cand = lows[p]
    left = lows[p - length : p]
    right = lows[p + 1 : idx + 1]
    if all(cand < x for x in left) and all(cand <= x for x in right):
        return cand
    return None

def compute_v2_liquidity_sweeps(
    highs: List[float],
    lows: List[float],
    closes: List[float],
    length: int = 5,
    mode: ModeType = "Only Wicks",
    extend: bool = True,
    max_boxes: int = 300,
) -> dict:
    """
    Pure H/L/C + bar_index implementation of V2 Indicator (Liquidity Sweeps [LuxAlgo]).
    Zero dependency on open, volume, time, or external feeds.
    """
    n = len(closes)
    assert len(highs) == n and len(lows) == n
    ph_list: List[dict] = []  # [{"idx": int, "prc": float, "broken": bool}]
    pl_list: List[dict] = []
    boxes: List[SweepBox] = []
    events: List[dict] = []

    for i in range(n):
        hi, lo, cl = highs[i], lows[i], closes[i]

        # 1. Detect confirmed pivots at bar i (pivot located at i - length)
        ph_val = _is_pivothigh(highs, i, length)
        if ph_val is not None:
            ph_list.insert(0, {"idx": i - length, "prc": ph_val, "broken": False})
        pl_val = _is_pivotlow(lows, i, length)
        if pl_val is not None:
            pl_list.insert(0, {"idx": i - length, "prc": pl_val, "broken": False})

        # 2. Check Bearish Liquidity Sweeps / Outbreaks against active Pivot Highs
        for p in list(ph_list):
            if p["broken"]:
                continue
            if cl > p["prc"]:
                p["broken"] = True
                if mode in ("Only Outbreaks", "All"):
                    boxes.append(SweepBox("bear", p["idx"], p["prc"], i, hi, broken=True, end_idx=i))
                    events.append({"bar": i, "type": "bear_outbreak", "pivot_idx": p["idx"], "level": p["prc"], "wick": hi})
            elif hi > p["prc"] and cl <= p["prc"]:
                if mode in ("Only Wicks", "All"):
                    boxes.append(SweepBox("bear", p["idx"], p["prc"], i, hi, broken=False, end_idx=i))
                    events.append({"bar": i, "type": "bear_wick_sweep", "pivot_idx": p["idx"], "level": p["prc"], "wick": hi})
                p["broken"] = True

        # 3. Check Bullish Liquidity Sweeps / Outbreaks against active Pivot Lows
        for p in list(pl_list):
            if p["broken"]:
                continue
            if cl < p["prc"]:
                p["broken"] = True
                if mode in ("Only Outbreaks", "All"):
                    boxes.append(SweepBox("bull", p["idx"], p["prc"], i, lo, broken=True, end_idx=i))
                    events.append({"bar": i, "type": "bull_outbreak", "pivot_idx": p["idx"], "level": p["prc"], "wick": lo})
            elif lo < p["prc"] and cl >= p["prc"]:
                if mode in ("Only Wicks", "All"):
                    boxes.append(SweepBox("bull", p["idx"], p["prc"], i, lo, broken=False, end_idx=i))
                    events.append({"bar": i, "type": "bull_wick_sweep", "pivot_idx": p["idx"], "level": p["prc"], "wick": lo})
                p["broken"] = True

        # 4. Extend / mitigate existing boxes
        if extend:
            for b in boxes:
                if b.invalidated:
                    continue
                if b.side == "bear":
                    if cl > b.wick_extreme:
                        b.invalidated = True
                    else:
                        b.end_idx = i
                else:
                    if cl < b.wick_extreme:
                        b.invalidated = True
                    else:
                        b.end_idx = i

        # 5. Trim to max_boxes
        if len(boxes) > max_boxes:
            boxes = boxes[-max_boxes:]

    return {"events": events, "boxes": boxes}

自測驗證結果(15 支合成 H/L/C K 線,len=5,mode="Only Wicks"):

[{"bar": 12, "type": "bull_wick_sweep", "pivot_idx": 5, "level": 95, "wick": 94}]

4. TradingView 官方 Pine Script v5 原碼(5,793 B,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 

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