3. 可獨立運行 V2 Python 參考編碼(liquidity_sweeps_v2.py,零第三方依賴)
已通過 py_compile 及 4 組測試(Bullish Wick Sweep+方框失效、Bearish Wick Sweep、Outbreak & Retest、Only Wicks 實體穿透去重);日後只需將 detect_liquidity_sweeps(bars) 接入 K 線序列即可。
"""V2 Indicator: Liquidity Sweeps [LuxAlgo] — Pure-Python Bar-for-Bar Reference Module.
Derived strictly from TradingView open-source Pine Script v5:
Script ID : PUB;26391b932d3145879b67deca62305c9a (5,793 B, CC BY-NC-SA 4.0, (c) LuxAlgo)
Inputs : ONLY single-timeframe OHLCV candle fields `high`, `low`, `close`, and 0-based `bar_index`.
`open`, `volume`, `time`, `request.security`, L2 orderbook, and tick data are NOT used.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable, List, Literal, Optional, Sequence
SweepOption = Literal["Only Wicks", "Only Outbreaks & Retest", "Wicks + Outbreaks & Retest"]
@dataclass(frozen=True)
class Bar:
"""Single OHLC candle input (only high, low, close are read by the V2 algorithm)."""
high: float
low: float
close: float
bar_index: Optional[int] = None
@dataclass
class Pivot:
prc: float
bix: int
brk: bool = False
mit: bool = False
tak: bool = False
wic: bool = False
@dataclass
class SweepBox:
left: int # n - 1 at creation
right: int # n + 1 at creation, updated to n while extended
y1: float # top (d == 1 -> bar.high; d == -1 -> piv.prc)
y2: float # bottom (d == 1 -> piv.prc; d == -1 -> bar.low)
dr: int # 1 = Bearish sweep (swept high), -1 = Bullish sweep (swept low)
br: bool = False # True once invalidated by close beyond box boundary
@dataclass(frozen=True)
class SweepEvent:
bar_index: int
direction: Literal["BULLISH", "BEARISH"]
kind: Literal["WICK_SWEEP", "OUTBREAK_RETEST"]
pivot_type: Literal["PIVOT_LOW", "PIVOT_HIGH"]
pivot_index: int
pivot_price: float
sweep_extreme: float # bar.low for BULLISH, bar.high for BEARISH
close: float
box_y1: float
box_y2: float
@dataclass
class DetectorResult:
events: List[SweepEvent]
boxes: List[SweepBox]
pivots_high_confirmed: List[Pivot]
pivots_low_confirmed: List[Pivot]
def _is_pivot_high(highs: Sequence[float], idx: int, length: int, strict_equal: bool = True) -> Optional[float]:
if idx < 2 * length:
return None
c = idx - length
val = highs[c]
for k in range(c - length, c):
if strict_equal:
if not (val > highs[k]):
return None
else:
if not (val >= highs[k]):
return None
for k in range(c + 1, c + length + 1):
if not (val > highs[k]):
return None
return val
def _is_pivot_low(lows: Sequence[float], idx: int, length: int, strict_equal: bool = True) -> Optional[float]:
if idx < 2 * length:
return None
c = idx - length
val = lows[c]
for k in range(c - length, c):
if strict_equal:
if not (val < lows[k]):
return None
else:
if not (val <= lows[k]):
return None
for k in range(c + 1, c + length + 1):
if not (val < lows[k]):
return None
return val
def detect_liquidity_sweeps(
bars: Iterable[Bar],
*,
length: int = 5,
opt: SweepOption = "Only Wicks",
extend: bool = True,
max_bars: int = 300,
strict_equal: bool = True,
) -> DetectorResult:
"""Run LuxAlgo Liquidity Sweeps bar-by-bar over a chronological sequence of Bars."""
if length < 1:
raise ValueError("length must be >= 1")
if max_bars < 1 or max_bars > 5000:
raise ValueError("max_bars must be in [1, 5000]")
if opt not in ("Only Wicks", "Only Outbreaks & Retest", "Wicks + Outbreaks & Retest"):
raise ValueError(f"unsupported opt: {opt}")
oW = opt == "Only Wicks"
oO = opt == "Only Outbreaks & Retest"
bar_list = list(bars)
highs = [float(b.high) for b in bar_list]
lows = [float(b.low) for b in bar_list]
a_piv_h: List[Pivot] = [] # unshift => index 0 is newest
a_piv_l: List[Pivot] = []
a_box_br: List[SweepBox] = []
events: List[SweepEvent] = []
ph_all: List[Pivot] = []
pl_all: List[Pivot] = []
for i, bar in enumerate(bar_list):
n = bar.bar_index if bar.bar_index is not None else i
h = highs[i]
l = lows[i]
c = float(bar.close)
ph = _is_pivot_high(highs, i, length, strict_equal=strict_equal)
pl = _is_pivot_low(lows, i, length, strict_equal=strict_equal)
if ph is not None:
p = Pivot(prc=ph, bix=n - length)
a_piv_h.insert(0, p)
ph_all.append(p)
if pl is not None:
p = Pivot(prc=pl, bix=n - length)
a_piv_l.insert(0, p)
pl_all.append(p)
# Iterate backwards (oldest to newest, matching Pine `for i = size - 1 to 0`)
for idx in range(len(a_piv_h) - 1, -1, -1):
get = a_piv_h[idx]
if not get.mit:
if not get.brk:
if c > get.prc:
if not oW:
get.brk = True
else:
get.mit = True
if not oO and not get.wic:
if h > get.prc and c < get.prc:
bx = SweepBox(left=n - 1, right=n + 1, y1=h, y2=get.prc, dr=1)
a_box_br.insert(0, bx)
events.append(SweepEvent(
bar_index=n, direction="BEARISH", kind="WICK_SWEEP",
pivot_type="PIVOT_HIGH", pivot_index=get.bix, pivot_price=get.prc,
sweep_extreme=h, close=c, box_y1=bx.y1, box_y2=bx.y2,
))
get.wic = True
else:
if c < get.prc:
get.mit = True
if not oW and l < get.prc and c > get.prc:
bx = SweepBox(left=n - 1, right=n + 1, y1=get.prc, y2=l, dr=-1)
a_box_br.insert(0, bx)
events.append(SweepEvent(
bar_index=n, direction="BULLISH", kind="OUTBREAK_RETEST",
pivot_type="PIVOT_HIGH", pivot_index=get.bix, pivot_price=get.prc,
sweep_extreme=l, close=c, box_y1=bx.y1, box_y2=bx.y2,
))
get.tak = True
if (n - get.bix > 2000) or get.mit or get.tak:
a_piv_h.pop(idx)
for idx in range(len(a_piv_l) - 1, -1, -1):
get = a_piv_l[idx]
if not get.mit:
if not get.brk:
if c < get.prc:
if not oW:
get.brk = True
else:
get.mit = True
if not oO and not get.wic:
if l < get.prc and c > get.prc:
bx = SweepBox(left=n - 1, right=n + 1, y1=get.prc, y2=l, dr=-1)
a_box_br.insert(0, bx)
events.append(SweepEvent(
bar_index=n, direction="BULLISH", kind="WICK_SWEEP",
pivot_type="PIVOT_LOW", pivot_index=get.bix, pivot_price=get.prc,
sweep_extreme=l, close=c, box_y1=bx.y1, box_y2=bx.y2,
))
get.wic = True
else:
if c > get.prc:
get.mit = True
if not oW and h > get.prc and c < get.prc:
bx = SweepBox(left=n - 1, right=n + 1, y1=h, y2=get.prc, dr=1)
a_box_br.insert(0, bx)
events.append(SweepEvent(
bar_index=n, direction="BEARISH", kind="OUTBREAK_RETEST",
pivot_type="PIVOT_LOW", pivot_index=get.bix, pivot_price=get.prc,
sweep_extreme=h, close=c, box_y1=bx.y1, box_y2=bx.y2,
))
get.tak = True
if (n - get.bix > 2000) or get.mit or get.tak:
a_piv_l.pop(idx)
if extend:
for bx in a_box_br:
if not bx.br and (n - bx.left - 1 <= max_bars):
bx.right = n
if bx.dr == -1 and c < bx.y2: # get_bottom() == y2
bx.br = True
if bx.dr == 1 and c > bx.y1: # get_top() == y1
bx.br = True
return DetectorResult(
events=events,
boxes=a_box_br,
pivots_high_confirmed=ph_all,
pivots_low_confirmed=pl_all,
)
def _self_test() -> None:
# Fixture 1: Bullish wick sweep of pivot low (len=2) + box extension + invalidation
bars1 = [
Bar(105, 100, 102), # 0
Bar(103, 98, 99), # 1
Bar(101, 90, 95), # 2 -> pivot low = 90 (confirmed at bar 4)
Bar(102, 94, 98), # 3
Bar(104, 95, 100), # 4 -> pl confirmed at bix=2, prc=90
Bar(101, 88, 92), # 5 -> wick sweep low=88 < 90 & close=92 > 90 -> BULLISH WICK_SWEEP
Bar(103, 91, 99), # 6 -> box right extends to 6, still active (close 99 >= 88)
Bar(95, 85, 86), # 7 -> close 86 < bottom 88 -> box invalidated (br=True)
]
r1 = detect_liquidity_sweeps(bars1, length=2, opt="Only Wicks", extend=True, max_bars=300)
assert len(r1.events) == 1, f"expected 1 event, got {r1.events}"
e1 = r1.events[0]
assert e1.direction == "BULLISH" and e1.kind == "WICK_SWEEP"
assert e1.pivot_index == 2 and e1.pivot_price == 90.0 and e1.sweep_extreme == 88.0
assert r1.boxes[0].br is True and r1.boxes[0].right == 7
# Fixture 2: Bearish wick sweep of pivot high (len=2)
bars2 = [
Bar(100, 95, 97), # 0
Bar(104, 98, 102), # 1
Bar(115, 103, 110), # 2 -> pivot high = 115
Bar(109, 102, 105), # 3
Bar(107, 101, 104), # 4 -> ph confirmed at bix=2, prc=115
Bar(118, 106, 112), # 5 -> high=118 > 115 & close=112 < 115 -> BEARISH WICK_SWEEP
]
r2 = detect_liquidity_sweeps(bars2, length=2, opt="Only Wicks")
assert len(r2.events) == 1
assert r2.events[0].direction == "BEARISH" and r2.events[0].pivot_price == 115.0
# Fixture 3: Outbreak & Retest on pivot high
bars3 = [
Bar(100, 95, 97), # 0
Bar(104, 98, 102), # 1
Bar(115, 103, 110), # 2 -> ph=115
Bar(109, 102, 105), # 3
Bar(107, 101, 104), # 4 -> ph confirmed
Bar(119, 110, 117), # 5 -> close=117 > 115 -> brk=True
Bar(118, 113, 116), # 6 -> low=113 < 115 and close=116 > 115 -> BULLISH OUTBREAK_RETEST
]
r3 = detect_liquidity_sweeps(bars3, length=2, opt="Only Outbreaks & Retest")
assert len(r3.events) == 1
assert r3.events[0].kind == "OUTBREAK_RETEST" and r3.events[0].direction == "BULLISH"
# Fixture 4: Body close beyond pivot in Only Wicks mitigates pivot without sweep
bars4 = [
Bar(100, 95, 97),
Bar(104, 98, 102),
Bar(115, 103, 110), # ph=115
Bar(109, 102, 105),
Bar(107, 101, 104),
Bar(120, 112, 118), # close > 115 => mit=True in Only Wicks
Bar(117, 108, 113), # cannot fire anymore
]
r4 = detect_liquidity_sweeps(bars4, length=2, opt="Only Wicks")
assert len(r4.events) == 0
if __name__ == "__main__":
_self_test()
print("SELF_TEST_OK")
4. TradingView 官方 Pine Script v5 源碼全文(PUB;26391b932d3145879b67deca62305c9a,5,793 B)
// 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
//-----------------------------------------------------------------------------}