本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © The Veiled Sage
//@version=6
// The Veiled Sage - Range Sweep (vs_range_sweep_v1_c5)
// Marks closed-bar sweeps of the previous day's high or low that close back inside the range, with disclosed filter tags.
// Concepts used: previous-day range sweep and reclaim, VWAP, volume versus its 14-bar average, engulfing candles, EMA/WMA smoother, wick rejection, ATR depth, higher-timeframe EMA bias.
// All are common public techniques; no third-party Pine source is reused in this file.
// Lineage: Veiled Sage work (owner capture hfGEh79q "SulLaLuna Liquidity Sweep Entry Signals", corrected in internal v0.1;
// external provenance not independently verified). The capture's "ZLSMA" label was inaccurate (EMA then WMA) and is named correctly here.
// Previous-day high/low are read inside the daily request (high[1]/low[1], lookahead_on), so they are confirmed prior-day levels.
// Entry labels and alerts are confirmed-bar only and the indicator is disabled on non-standard or 1440m+ charts.
// c2 (9 Nov 2026): from c1 sha256 3c988738a862b1dad591b5c8d2a91ddffb76d3d6fb32dcdaf3a00822c74d58c2. Default minVotes = 2; LONG/SHORT labels kept.
// c3 (CANDIDATE, unvalidated, 9 Nov 2026): from c2 sha256 06d74e58f88588c5d5303f723cd05cbf89d3971ee531ebd67473a9e4f9f11215.
// Tuned for a healthier signal rate: added a wick-rejection (REJ) vote and a 4x higher-timeframe (HTF) bias vote, a minimum sweep depth,
// a same-direction cooldown, an optional today's-developing-high/low sweep level, selectable volume vote mode, and optional past-day box history.
// minVotes default stays 2; LONG/SHORT labels kept; signals remain closed-bar only.
// c4 (9 Nov 2026): from c3 sha256 c5eced9a33b6f6b1ec9634c1359bec4028518927a724466de25abbaef8c2292c.
// Only change: "Also sweep today's developing high/low" (DAY levels) now defaults ON (Pete decision). SCRIPT_VER/header aligned to c4.
// c5 (CANDIDATE, unvalidated, 9 Nov 2026): from c4 sha256 a11353c285a645b4a97773f96032bb7d6edc09aba1d16b58ea0af9e1a5e1c5ac.
// Labels show only LONG/SHORT (vote tags DAY/VOL/REJ/HTF/VWAP/SMOOTH/ENG moved to tooltip); cream/parchment defaults
// (#D8C79A, #F5ECD0) swapped to palette gold/yellow (#D4AF37, #F2C94C); black text kept on gold long labels. Signal logic unchanged.
indicator("The Veiled Sage - Range Sweep", shorttitle="VS Sweep", overlay=true, max_labels_count=500, max_boxes_count=40, max_lines_count=40)
string SCRIPT_VER = "vs_range_sweep_v1_c5"
string SCHEMA = "vs_alert/3"
// ── Labels / history ──
grpL = "Labels"
keepSignalLabels = input.int(200, "Keep last N entry labels", minval=10, maxval=480, group=grpL)
showSignals = input.bool(true, "Show entry labels", group=grpL)
var array<label> signalLabels = array.new_label()
f_keepLabel(label l) =>
signalLabels.push(l)
if signalLabels.size() > keepSignalLabels
label.delete(signalLabels.shift())
// ── Range box ──
grpB = "Previous-day range"
boxColor = input.color(color.new(#7B2CBF, 85), "Main box fill", group=grpB)
borderColor = input.color(#7B2CBF, "Box border", group=grpB)
opacity = input.int(25, "Box opacity", minval=0, maxval=100, group=grpB)
extendBars = input.int(100, "Extend box forward (bars)", minval=1, maxval=500, group=grpB)
topZoneColor = input.color(color.new(#FF8C1A, 80), "Upper quarter zone", group=grpB)
bottomZoneColor = input.color(color.new(#D4A017, 80), "Lower quarter zone", group=grpB)
midLineColor = input.color(#D4AF37, "Midpoint line (gold)", group=grpB)
heightLabelBg = input.color(#16121D, "Height label background", group=grpB)
heightLabelText = input.color(#D4A017, "Height label text", group=grpB)
keepPastBoxes = input.bool(true, "Keep past days' range boxes", group=grpB, tooltip="Keeps each finished day's previous-day range box (box and midpoint line only) so day-boundary resets stay visible. The current day always shows the full set.")
pastDaysKeep = input.int(5, "Past days to keep", minval=1, maxval=5, group=grpB)
// ── Filters ──
grpF = "Filters"
smoothLength = input.int(55, "EMA/WMA smoother length", minval=1, group=grpF)
useSmoother = input.bool(true, "Use EMA/WMA smoother vote", group=grpF)
useLowVolume = input.bool(true, "Use volume vote (mode below; not divergence)", group=grpF)
volMode = input.string("Below average", "Volume vote mode", options=["Below average", "Above average"], group=grpF, tooltip="Below average: the sweep bar's volume is under its 14-bar average (c2 behaviour). Above average: volume is at or above the average (participation on the sweep bar).")
useVWAPConfirm = input.bool(true, "Use VWAP rejection filter", group=grpF)
useEngulfing = input.bool(true, "Use engulfing candle filter", group=grpF)
useRejection = input.bool(true, "Use wick-rejection vote", group=grpF, tooltip="Long: the close sits in the upper part of the bar's range. Short: the close sits in the lower part. Threshold set below.")
rejPct = input.int(50, "Wick-rejection threshold (% of bar range)", minval=10, maxval=95, group=grpF)
useHTF = input.bool(true, "Use 4x higher-timeframe bias vote", group=grpF, tooltip="Votes with the bias of the last COMPLETED bar of a timeframe 4x the chart timeframe (capped at 1D): its close versus its 21-period EMA. Not repainting.")
htfEmaLen = input.int(21, "HTF EMA length", minval=2, group=grpF)
htfGate = input.bool(false, "Require HTF bias to agree (gate)", group=grpF, tooltip="When on, a tag is only flagged if the 4x higher-timeframe bias agrees with its direction, regardless of the vote count.")
minVotes = input.int(2, "Minimum enabled filter votes", minval=1, maxval=6, group=grpF, tooltip="Default 2 = at least two enabled filter votes must agree. Set to 1 for the loosest rule, or raise for stricter agreement.")
// ── Sweep rules ──
grpS = "Sweep rules"
minDepthAtr = input.float(0.10, "Minimum sweep depth (x ATR14)", minval=0.0, maxval=2.0, step=0.05, group=grpS, tooltip="The wick must pierce the level by at least this fraction of ATR(14); 0 = any tick beyond the level.")
cooldownBars = input.int(8, "Cooldown between same-direction tags (bars)", minval=0, maxval=96, group=grpS, tooltip="Minimum bars between two LONG tags or two SHORT tags. Limits clusters from repeated pokes at the same level. 0 = off.")
useDayLevels = input.bool(true, "Also sweep today's developing high/low", group=grpS, tooltip="Adds today's running high/low (from earlier bars only, after the warm-up) as a second sweep level. On by default (Pete, 9 Nov 2026); switch off for previous-day levels only.")
dayWarmBars = input.int(16, "Developing-level warm-up (bars)", minval=4, maxval=200, group=grpS)
// ── Series colours (regime/bias shifts) ──
grpC = "Series colours"
smootherUpColor = input.color(#D4A017, "Smoother rising (gold)", group=grpC)
smootherDownColor = input.color(#7B2CBF, "Smoother falling (purple)", group=grpC)
vwapColor = input.color(#FF8C1A, "VWAP line (orange)", group=grpC)
longTagColor = input.color(#D4A017, "Long / reclaim label (gold)", group=grpC)
shortTagColor = input.color(#7B2CBF, "Short / reject label (purple)", group=grpC)
longTagText = input.color(#000000, "Long label text", group=grpC)
shortTagText = input.color(#F2C94C, "Short label text (yellow)", group=grpC)
// ── Daily background ──
grpD = "Daily background"
dayColor1 = input.color(color.new(#000000, 90), "Day background colour 1 (black)", group=grpD)
dayColor2 = input.color(color.new(#7B2CBF, 92), "Day background colour 2 (purple)", group=grpD)
// ── Branding ──
grpBr = "Branding"
showBrand = input.bool(true, "Show The Veiled Sage label", group=grpBr)
brandGold = input.color(#D4A017, "Brand colour", group=grpBr)
brandFade = input.int(45, "Brand transparency", minval=0, maxval=100, group=grpBr)
// ── JSON alert ──
grpJ = "JSON alert"
jsonMode = input.string("Event closes only", "State JSON alert() mode", options=["Event closes only", "Every confirmed bar", "Off"], group=grpJ, tooltip="Event closes only: one JSON message on bars where a closed-bar sweep entry is flagged. Every confirmed bar: a state snapshot each closed bar (events list may be empty). Off: no alert() calls. alertcondition() entries are independent.")
// === Alternating Daily Background ===
var int currentDayIndex = 0
isNewDay = ta.change(time("D")) != 0
currentDayIndex := isNewDay ? currentDayIndex + 1 : currentDayIndex
bgcolor(currentDayIndex % 2 == 0 ? dayColor1 : dayColor2, title="Alternating Daily Background")
// === Daily High/Low Logic ===
bool supportedIntraday = chart.is_standard and timeframe.isminutes and timeframe.multiplier < 1440
float prevHigh = na
float prevLow = na
if supportedIntraday
prevHigh := request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
prevLow := request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on)
boxRange = prevHigh - prevLow
top25 = prevHigh - boxRange * 0.25
low25 = prevLow + boxRange * 0.25
midpoint = (prevHigh + prevLow) / 2
// === Calculate box-height in % ===
pctHeight = not na(prevLow) and prevLow != 0 ? boxRange / prevLow * 100 : na
pctText = "H: " + str.tostring(pctHeight, "#.##") + "%"
// === Persistent vars for boxes, line, labels ===
var box dailyBox = na
var box topBox = na
var box bottomBox = na
var line midLine = na
var label heightLabel = na
var array<box> pastBoxes = array.new<box>()
var array<line> pastLines = array.new<line>()
newDay = ta.change(time("1D")) != 0
if (newDay or barstate.isfirst) and supportedIntraday and not na(prevHigh) and not na(prevLow)
if not na(dailyBox)
if keepPastBoxes
box.set_right(dailyBox, math.max(bar_index - 1, box.get_left(dailyBox)))
pastBoxes.push(dailyBox)
else
box.delete(dailyBox)
if not na(topBox)
box.delete(topBox)
if not na(bottomBox)
box.delete(bottomBox)
if not na(midLine)
if keepPastBoxes
line.set_x2(midLine, math.max(bar_index - 1, line.get_x1(midLine)))
pastLines.push(midLine)
else
line.delete(midLine)
if not na(heightLabel)
label.delete(heightLabel)
while pastBoxes.size() > pastDaysKeep
box.delete(pastBoxes.shift())
while pastLines.size() > pastDaysKeep
line.delete(pastLines.shift())
dailyBox := box.new(left=bar_index, right=bar_index + extendBars, top=prevHigh, bottom=prevLow, bgcolor=color.new(boxColor, 100 - opacity), border_color=borderColor)
topBox := box.new(left=bar_index, right=bar_index + extendBars, top=prevHigh, bottom=top25, bgcolor=topZoneColor)
bottomBox := box.new(left=bar_index, right=bar_index + extendBars, top=low25, bottom=prevLow, bgcolor=bottomZoneColor)
midLine := line.new(x1=bar_index, y1=midpoint, x2=bar_index + extendBars, y2=midpoint, color=midLineColor, style=line.style_dashed)
heightLabel := label.new(x=bar_index + extendBars, y=prevHigh, xloc=xloc.bar_index, yloc=yloc.price, text=pctText, style=label.style_label_left, color=heightLabelBg, textcolor=heightLabelText, size=size.small)
// === SMOOTH ===
ema1 = ta.ema(close, smoothLength)
wma1 = ta.wma(ema1, smoothLength)
trendSmoother = wma1
smoothColor = trendSmoother > trendSmoother[1] ? smootherUpColor : smootherDownColor
plot(trendSmoother, "EMA/WMA smoother", color=smoothColor, linewidth=2)
// === Below-average volume (not a divergence model) ===
volAvg = ta.sma(volume, 14)
lowVolumeBull = volume < volAvg
lowVolumeBear = volume < volAvg
// === 4x higher-timeframe bias (last completed HTF bar: close versus its EMA) ===
string htfTf = timeframe.from_seconds(math.min(timeframe.in_seconds() * 4, 86400))
f_htfBias() =>
float e = ta.ema(close, htfEmaLen)
close[1] > e[1] ? 1 : close[1] < e[1] ? -1 : 0
int htfBias = 0
if supportedIntraday
htfBias := request.security(syminfo.tickerid, htfTf, f_htfBias(), lookahead=barmerge.lookahead_on)
// === Sweep Logic ===
atr14 = ta.atr(14)
depth = minDepthAtr * nz(atr14)
// Today's developing high/low from EARLIER bars only (updated after use, so no repaint)
var float dayHi = na
var float dayLo = na
var int dayBarCount = 0
float devHi = na
float devLo = na
if newDay
dayHi := na
dayLo := na
dayBarCount := 0
devHi := dayBarCount >= dayWarmBars ? dayHi : na
devLo := dayBarCount >= dayWarmBars ? dayLo : na
dayHi := na(dayHi) ? high : math.max(dayHi, high)
dayLo := na(dayLo) ? low : math.min(dayLo, low)
dayBarCount += 1
sweepHighPD = high > prevHigh + depth and close < prevHigh
sweepLowPD = low < prevLow - depth and close > prevLow
sweepHighDay = useDayLevels and not na(devHi) and high > devHi + depth and close < devHi
sweepLowDay = useDayLevels and not na(devLo) and low < devLo - depth and close > devLo
sweepHigh = sweepHighPD or sweepHighDay
sweepLow = sweepLowPD or sweepLowDay
// === VWAP ===
vwap = ta.vwap
plot(vwap, "VWAP", color=vwapColor)
// === VWAP Rejection Logic ===
vwapRejectionLong = sweepLow and close > low and close > vwap and close[1] < vwap
vwapRejectionShort = sweepHigh and close < high and close < vwap and close[1] > vwap
// === Engulfing Candle Logic ===
bullishEngulfing = close > open and close > open[1] and open < close[1]
bearishEngulfing = close < open and close < open[1] and open > close[1]
// === Wick rejection (close position inside the bar range) ===
barRange = high - low
rejLongOk = barRange > 0 and (close - low) / barRange >= rejPct / 100.0
rejShortOk = barRange > 0 and (high - close) / barRange >= rejPct / 100.0
// === Entry Condition Flags ===
volVoteBull = volMode == "Below average" ? lowVolumeBull : volume >= volAvg
volVoteBear = volMode == "Below average" ? lowVolumeBear : volume >= volAvg
longSmooth = useSmoother and close > trendSmoother
longVOL = useLowVolume and volVoteBull
longVWAP = useVWAPConfirm and vwapRejectionLong
longENG = useEngulfing and bullishEngulfing
longREJ = useRejection and rejLongOk
longHTF = useHTF and htfBias > 0
shortSmooth = useSmoother and close < trendSmoother
shortVOL = useLowVolume and volVoteBear
shortVWAP = useVWAPConfirm and vwapRejectionShort
shortENG = useEngulfing and bearishEngulfing
shortREJ = useRejection and rejShortOk
shortHTF = useHTF and htfBias < 0
// === Filter Text & Count ===
longFilters = (longSmooth ? "SMOOTH " : "") + (longVOL ? "VOL " : "") + (longVWAP ? "VWAP " : "") + (longENG ? "ENG " : "") + (longREJ ? "REJ " : "") + (longHTF ? "HTF " : "")
shortFilters = (shortSmooth ? "SMOOTH " : "") + (shortVOL ? "VOL " : "") + (shortVWAP ? "VWAP " : "") + (shortENG ? "ENG " : "") + (shortREJ ? "REJ " : "") + (shortHTF ? "HTF " : "")
longFilterCount = (longSmooth ? 1 : 0) + (longVOL ? 1 : 0) + (longVWAP ? 1 : 0) + (longENG ? 1 : 0) + (longREJ ? 1 : 0) + (longHTF ? 1 : 0)
shortFilterCount = (shortSmooth ? 1 : 0) + (shortVOL ? 1 : 0) + (shortVWAP ? 1 : 0) + (shortENG ? 1 : 0) + (shortREJ ? 1 : 0) + (shortHTF ? 1 : 0)
// === Final Entry Conditions (closed bars only; cooldown counts bars since the last emitted tag in the same direction) ===
var int lastLongBar = -100000
var int lastShortBar = -100000
htfGateLong = not (htfGate and useHTF) or htfBias > 0
htfGateShort = not (htfGate and useHTF) or htfBias < 0
longCond = barstate.isconfirmed and supportedIntraday and sweepLow and longFilterCount >= minVotes and htfGateLong and (bar_index - lastLongBar) >= cooldownBars
shortCond = barstate.isconfirmed and supportedIntraday and sweepHigh and shortFilterCount >= minVotes and htfGateShort and (bar_index - lastShortBar) >= cooldownBars
if longCond
lastLongBar := bar_index
if shortCond
lastShortBar := bar_index
levelTagLong = sweepLowPD ? "" : "DAY "
levelTagShort = sweepHighPD ? "" : "DAY "
// === Label Color Intensity (gold long / purple short; opacity by vote count) ===
getLabelColor(isLong, filterCount) =>
baseCol = isLong ? longTagColor : shortTagColor
filterCount >= 3 ? baseCol : filterCount == 2 ? color.new(baseCol, 25) : color.new(baseCol, 60)
longLabelColor = getLabelColor(true, longFilterCount)
shortLabelColor = getLabelColor(false, shortFilterCount)
// === Entry Labels (compact LONG/SHORT; vote tags + level + bar time in tooltip) ===
if showSignals and longCond
string longVotes = str.trim(levelTagLong + longFilters)
float longLevel = sweepLowPD ? prevLow : nz(devLo)
string longTip = "LONG · votes: " + longVotes + " · level " + str.tostring(longLevel, "#.########") + " · bar time " + str.format_time(time, "yyyy-MM-dd HH:mm", "UTC")
f_keepLabel(label.new(bar_index, low, "LONG", style=label.style_label_up, color=longLabelColor, textcolor=longTagText, textalign=text.align_center, yloc=yloc.belowbar, size=size.small, tooltip=longTip))
if showSignals and shortCond
string shortVotes = str.trim(levelTagShort + shortFilters)
float shortLevel = sweepHighPD ? prevHigh : nz(devHi)
string shortTip = "SHORT · votes: " + shortVotes + " · level " + str.tostring(shortLevel, "#.########") + " · bar time " + str.format_time(time, "yyyy-MM-dd HH:mm", "UTC")
f_keepLabel(label.new(bar_index, high, "SHORT", style=label.style_label_down, color=shortLabelColor, textcolor=shortTagText, textalign=text.align_center, yloc=yloc.abovebar, size=size.small, tooltip=shortTip))
// === Alerts (alertcondition: pick "Once Per Bar Close" when creating) ===
alertcondition(longCond, title="VS Sweep LONG reclaim (closed bar)",
message="Closed-bar LONG range sweep: the minimum number of enabled filter votes was met on {{ticker}} at {{close}}; bar {{time}}. See chart tags; this is not confirmation from every filter.")
alertcondition(shortCond, title="VS Sweep SHORT reject (closed bar)",
message="Closed-bar SHORT range sweep: the minimum number of enabled filter votes was met on {{ticker}} at {{close}}; bar {{time}}. See chart tags; this is not confirmation from every filter.")
var table statusTbl = table.new(position.top_right, 1, 1)
if barstate.islast
table.cell(statusTbl, 0, 0, supportedIntraday ? "" : "DISABLED: standard minute chart below 1440m required", text_color=#D4A017, bgcolor=supportedIntraday ? na : color.new(#000000, 20), text_size=size.small)
// ── Branding ──
var table brandTbl = table.new(position.bottom_right, 1, 1)
if barstate.islast
table.cell(brandTbl, 0, 0, showBrand ? "The Veiled Sage · Range Sweep" : "", text_size=size.small, text_color=color.new(brandGold, brandFade), bgcolor=color.new(#16121D, 100))
// ── JSON alert() (vs_alert/3, confirmed bars only). Create ONE alert: condition "Any alert() function call". ──
jnum(float x, string fmt) => na(x) ? "null" : str.tostring(x, fmt)
jbool(bool x) => x ? "true" : "false"
buildPayload(string ev, string eventsJson) =>
string isoT = str.format_time(time, "yyyy-MM-dd'T'HH:mm:ss'Z'", "UTC")
string id = syminfo.ticker + "_" + timeframe.period + "_" + str.tostring(time) + "_" + ev
string s = "{\"schema\":\"" + SCHEMA + "\",\"id\":\"" + id + "\",\"event\":\"" + ev + "\""
s += ",\"version\":\"" + SCRIPT_VER + "\",\"indicator\":\"range_sweep\""
s += ",\"ticker\":\"" + syminfo.ticker + "\",\"exchange\":\"" + syminfo.prefix + "\",\"timeframe\":\"" + timeframe.period + "\""
s += ",\"bar_time\":" + str.tostring(time) + ",\"bar_time_iso\":\"" + isoT + "\",\"confirmed\":true"
s += ",\"open\":" + jnum(open, "#.########") + ",\"high\":" + jnum(high, "#.########") + ",\"low\":" + jnum(low, "#.########") + ",\"close\":" + jnum(close, "#.########") + ",\"volume\":" + jnum(volume, "#.####")
s += ",\"supported_chart\":" + jbool(supportedIntraday)
s += ",\"prev_day_high\":" + jnum(prevHigh, "#.########") + ",\"prev_day_low\":" + jnum(prevLow, "#.########") + ",\"prev_day_mid\":" + jnum(midpoint, "#.########") + ",\"prev_day_range_pct\":" + jnum(pctHeight, "#.##")
s += ",\"smoother\":" + jnum(trendSmoother, "#.########") + ",\"vwap\":" + jnum(vwap, "#.########")
s += ",\"htf_timeframe\":\"" + htfTf + "\",\"htf_bias\":" + str.tostring(htfBias) + ",\"atr14\":" + jnum(atr14, "#.########")
s += ",\"sweep_high\":" + jbool(sweepHigh) + ",\"sweep_low\":" + jbool(sweepLow)
s += ",\"long_votes\":" + str.tostring(longFilterCount) + ",\"short_votes\":" + str.tostring(shortFilterCount) + ",\"min_votes\":" + str.tostring(minVotes) + ",\"cooldown_bars\":" + str.tostring(cooldownBars) + ",\"min_depth_atr\":" + jnum(minDepthAtr, "#.##")
s += ",\"long_filters\":\"" + str.trim(longFilters) + "\",\"short_filters\":\"" + str.trim(shortFilters) + "\""
s += ",\"events\":" + eventsJson + ",\"state_only\":true}"
s
if barstate.isconfirmed and jsonMode != "Off"
string evList = ""
if longCond
evList += "\"sweep_low_reclaim_long\""
if shortCond
evList += (evList == "" ? "" : ",") + "\"sweep_high_reject_short\""
if jsonMode == "Every confirmed bar" or evList != ""
alert(buildPayload("range_sweep_snapshot", "[" + evList + "]"), alert.freq_once_per_bar_close)