本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jabez4jc
//
// Based on "Rolling VWAP": https://www.tradingview.com/script/ZU2UUu9T-Rolling-VWAP/
//@version=6
indicator('Rolling VWAP with Signals', 'RVWAP Signals', overlay = true)
// Requires the GatedStats library (Library.pine in this repo), published as jabez4jc/GatedStats/1.
// If you publish a new version, bump the number here.
import jabez4jc/GatedStats/1 as gs
// ───────────────────────────── Inputs ─────────────────────────────
tfrvwap = input.timeframe("", 'RVWAP Timeframe')
int hoursInput = input.int(1, 'RVWAP Time Period — Hours', minval = 0, maxval = 23, inline = 'period')
int minsInput = input.int(0, 'Minutes', minval = 0, maxval = 59, inline = 'period')
float stdDevMult = input.float(1.0, 'Standard Deviation Multiplier', minval = 0.146, maxval = 5.0, step = 0.5)
bool showBands = input.bool(true, 'Show Standard Deviation Bands')
bool showFill = input.bool(true, 'Show Fill Between Bands')
// Smoothing
bool useSmoothing = input.bool(true, 'Smooth VWAP/StdDev (uncheck for tighter, less-lagged line)', group = 'Smoothing')
gs.MaType smoothType = input.enum(gs.MaType.swma, 'Smoothing Type', group = 'Smoothing')
// SWMA always uses 4 samples, so the length input is disabled when it is selected.
int smoothLen = input.int(6, 'Smoothing Length', minval = 2, group = 'Smoothing', active = smoothType != gs.MaType.swma)
// Signal filters
bool useATRFilter = input.bool(true, 'Require Rising ATR for Signals', inline = 'atr', group = 'Signal Filters')
int atrLength = input.int(14, 'Length', minval = 1, inline = 'atr', group = 'Signal Filters')
bool useTrendFilter = input.bool(true, 'Require RVWAP Trend Alignment for Signals', group = 'Signal Filters')
bool useVolFilter = input.bool(true, 'Require Relative Volume', inline = 'rvol', group = 'Signal Filters')
float rvolMult = input.float(1.2, 'Min ×', minval = 0.5, step = 0.1, inline = 'rvol', group = 'Signal Filters', active = useVolFilter)
bool useFlowFilter = input.bool(true, 'Require Directional Volume Dominance', inline = 'flow', group = 'Signal Filters')
int flowLen = input.int(34, 'Bars', minval = 5, inline = 'flow', group = 'Signal Filters', active = useFlowFilter)
// Colors
color upperBandColor = input.color(color.new(color.blue, 50), 'Upper Band', inline = 'colors')
color lowerBandColor = input.color(color.new(color.red, 50), 'Lower Band', inline = 'colors')
color fillColor = input.color(color.new(color.gray, 80), 'Fill', inline = 'colors')
// ───────────────────────────── Constants ─────────────────────────────
int MS_IN_MIN = 60 * 1000
int MS_IN_HOUR = MS_IN_MIN * 60
int periodMs = hoursInput * MS_IN_HOUR + minsInput * MS_IN_MIN
int MIN_BARS = 10
// ───────────────────────────── Safety check ─────────────────────────────
if ta.cum(nz(volume)) == 0 and barstate.islast
runtime.error("No volume is provided by the data vendor.")
// ───────────────────────────── Calculation ─────────────────────────────
// gs.gatedVwapTime() returns the rolling VWAP and its weighted standard deviation
// in one call (one window, one request.security). The deviation is measured against
// the CURRENT window VWAP for every sample, i.e. the true weighted std dev.
//
// Smoothing uses gs.gatedMa() with a selectable type and length, toggled by
// useSmoothing — uncheck it for a tighter, less-lagged line suited to faster
// execution timing. The smoothing calls run on every bar regardless of the toggle
// so their history stays consistent.
calcRVWAP(src, simple int windowMs) =>
[vwap, stdDev] = gs.gatedVwapTime(src, volume, windowMs, true, MIN_BARS)
float smoothVWAP = gs.gatedMa(vwap, true, smoothLen, smoothType)
float smoothStdDev = gs.gatedMa(stdDev, true, smoothLen, smoothType)
[useSmoothing ? smoothVWAP : vwap, useSmoothing ? smoothStdDev : stdDev]
[rollingVWAP, stdDev] = request.security(syminfo.tickerid, tfrvwap, calcRVWAP(hlc3, periodMs), barmerge.gaps_off, lookahead = barmerge.lookahead_off)
// Calculate standard deviation bands
float upperBand = rollingVWAP + (stdDevMult * stdDev)
float lowerBand = rollingVWAP - (stdDevMult * stdDev)
// ───────────────────────────── Trend detection ─────────────────────────────
// ratio is clamped to >= 1. When the RVWAP timeframe is lower than the chart
// timeframe, round(htf/ltf) is 0, so rollingVWAP[0] would compare the value to
// itself and the trend condition could never be true.
htf_secs = timeframe.in_seconds(tfrvwap)
ltf_secs = timeframe.in_seconds()
int ratio = math.max(1, math.round(htf_secs / ltf_secs))
// Trend conditions
rvwapUp = rollingVWAP > rollingVWAP[ratio] and close > upperBand
rvwapDn = rollingVWAP < rollingVWAP[ratio] and close < lowerBand
// ───────────────────────────── ATR rising filter ─────────────────────────────
// Smoothed ATR via SWMA must be rising (not falling) for a signal to fire —
// filters out breakouts happening while volatility is contracting.
smoothedATR = ta.swma(ta.atr(atrLength))
atrRising = not useATRFilter or smoothedATR > smoothedATR[1]
// ───────────────────────────── Volume filters ─────────────────────────────
// Relative volume: the breakout bar must trade above its rolling 24h average.
float avgVol = gs.gatedMeanTime(volume, 24 * MS_IN_HOUR, true, MIN_BARS)
bool volOk = not useVolFilter or volume > avgVol * rvolMult
// Directional dominance: up-bar volume must have exceeded down-bar volume (buys), or the
// reverse (sells), over the last flowLen bars. Up/down bar (close vs open) is only a rough
// proxy for buying/selling pressure because `volume` is unsigned.
// [1]: judge the pressure BEFORE the breakout bar so its own volume can't confirm itself.
bool upBar = close > open
bool downBar = close < open
float upVol = gs.gatedMeanInBars(volume, upBar, flowLen, 3)
float downVol = gs.gatedMeanInBars(volume, downBar, flowLen, 3)
bool flowOkBuy = not useFlowFilter or upVol[1] > downVol[1]
bool flowOkSell = not useFlowFilter or downVol[1] > upVol[1]
// ───────────────────────────── Buy/Sell band-break signals ─────────────────────────────
// Signals fire on the bar that crosses a band and on later bars that stay beyond it while closing in the same
// direction. The crossovers are computed on every bar (CW10002) before being combined.
// Signals do not depend on showBands — hiding the bands is a display choice and
// must not silently disable signals and alerts.
bool crossUp = ta.crossover(close, upperBand) or (close > upperBand and close > close[1])
bool crossDn = ta.crossunder(close, lowerBand) or (close < lowerBand and close < close[1])
trendOkBuy = not useTrendFilter or rvwapUp
trendOkSell = not useTrendFilter or rvwapDn
buySignal = crossUp and atrRising and trendOkBuy and volOk and flowOkBuy
sellSignal = crossDn and atrRising and trendOkSell and volOk and flowOkSell
// ───────────────────────────── Plotting ─────────────────────────────
plot(rollingVWAP, 'Rolling VWAP', color = rvwapUp ? color.new(color.green, 0) : rvwapDn ? color.new(color.red, 0) : color.new(color.white, 0), linewidth = 3)
upperBandPlot = plot(showBands ? upperBand : na, 'Upper Band', color = upperBandColor, linewidth = 1, style = plot.style_line)
lowerBandPlot = plot(showBands ? lowerBand : na, 'Lower Band', color = lowerBandColor, linewidth = 1, style = plot.style_line)
fill(upperBandPlot, lowerBandPlot, color = showFill and showBands ? fillColor : na, title = 'Band Fill')
plotshape(buySignal, title = 'Buy Signal', style = shape.triangleup, location = location.belowbar, color = color.new(color.green, 0), size = size.small, text = 'BUY')
plotshape(sellSignal, title = 'Sell Signal', style = shape.triangledown, location = location.abovebar, color = color.new(color.red, 0), size = size.small, text = 'SELL')
// Alerts
alertcondition(close > upperBand, title = "Price Above Upper Band", message = "Price has moved above the upper standard deviation band")
alertcondition(close < lowerBand, title = "Price Below Lower Band", message = "Price has moved below the lower standard deviation band")
alertcondition(buySignal, title = "RVWAP Buy Signal", message = "Price broke above the upper RVWAP band — buy signal")
alertcondition(sellSignal, title = "RVWAP Sell Signal", message = "Price broke below the lower RVWAP band — sell signal")