本页源码来自 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/
// © Holtermorter99
//
// Anchored VWAP Auto — volume-weighted average prices anchored automatically to the start of the week and to
// the last confirmed swing low and swing high, plus statistics of the chart itself: average distance of price to
// each VWAP (in ATR) and, for swing anchors, how often price came back to the VWAP within N bars and whether it
// held there. Swing VWAPs are drawn from the bar after the confirmation bar (the line is cut there).
//@version=6
indicator("Anchored VWAP Auto [Holtermorter99]", "AVWAP", overlay = true)
// ─────────────────────────────── Inputs ───────────────────────────────
const string G_ANC = "Anchors"
const string G_STAT = "Statistics"
const string G_DISP = "Display"
const string G_COL = "Colors"
bool showWeek = input.bool(true, "Week VWAP", group = G_ANC, tooltip = "Anchored at the first bar of each week.")
bool showLow = input.bool(true, "Swing Low VWAP", group = G_ANC)
bool showHigh = input.bool(true, "Swing High VWAP", group = G_ANC)
int pivLeft = input.int(10, "Swing Left Bars", minval = 1, maxval = 100, group = G_ANC, tooltip = "A swing low (high) is the lowest low (highest high) with this many bars on its left...")
int pivRight = input.int(5, "Swing Right Bars (confirmation)", minval = 1, maxval = 100, group = G_ANC, tooltip = "...and this many bars on its right. The swing is confirmed this many bars later; the VWAP includes the volume from the swing bar but is drawn from the bar after confirmation.")
int fwdBars = input.int(20, "Test Window (bars)", minval = 2, maxval = 300, group = G_STAT, tooltip = "For every swing anchor: did price come back to its VWAP within this many bars after confirmation, and did it hold at the first touch? Each anchor is counted once its window has elapsed.")
int atrLength = input.int(14, "ATR Length", minval = 1, maxval = 200, group = G_STAT, tooltip = "Distances are measured in ATR of the chart's timeframe.")
bool showDashboard = input.bool(true, "Show Dashboard", group = G_DISP)
string dashPosInput = input.string("Top Right", "Dashboard Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], inline = "dash", group = G_DISP)
string dashSizeInput = input.string("Small", "", options = ["Tiny", "Small", "Normal"], inline = "dash", group = G_DISP)
color weekColor = input.color(#787B86, "Week VWAP", group = G_COL)
color lowColor = input.color(#26A69A, "Swing Low VWAP", group = G_COL)
color highColor = input.color(#EF5350, "Swing High VWAP", group = G_COL)
// ─────────────────────────────── Data ───────────────────────────────
bool okChart = chart.is_standard and (timeframe.isintraday or (timeframe.isdaily and timeframe.multiplier == 1))
float vol = nz(volume) // missing volume counts as zero
var float cumVol = 0.0
cumVol += vol
bool hasVol = cumVol > 0
float px = hlc3
float atr = ta.atr(atrLength)
// Week VWAP: built-in anchored VWAP, reset on the first bar of each week.
float wVwapRaw = ta.vwap(px, timeframe.change("W"))
float wVwap = okChart and hasVol ? wVwapRaw : na
// Swings, confirmed pivRight bars after the swing bar (on closed bars only).
float pLow = ta.pivotlow(low, pivLeft, pivRight)
float pHigh = ta.pivothigh(high, pivLeft, pivRight)
bool newLow = barstate.isconfirmed and not na(pLow)
bool newHigh = barstate.isconfirmed and not na(pHigh)
// Sums of price×volume and volume from the swing bar to the current bar.
sumPV(int n) =>
float s = 0.0
for i = 0 to n
s += px[i] * vol[i]
s
sumV(int n) =>
float s = 0.0
for i = 0 to n
s += vol[i]
s
float swPV = sumPV(pivRight)
float swV = sumV(pivRight)
// One anchor under test: its own running sums, age since confirmation, and touch/hold results.
type Anchor
int dir // 1 swing low (support), -1 swing high (resistance)
float pv
float v
int age // bars after the confirmation bar
bool touched
bool held
var array<Anchor> tests = array.new<Anchor>()
// Displayed swing VWAPs (latest anchors).
var float lowPV = na
var float lowV = na
var float highPV = na
var float highV = na
// Statistics: index 0 swing lows, 1 swing highs.
var array<int> nTest = array.new<int>(2, 0)
var array<int> nTouch = array.new<int>(2, 0)
var array<int> nHeld = array.new<int>(2, 0)
// Distance statistics: index 0 week, 1 swing low, 2 swing high.
var array<float> distSum = array.new<float>(3, 0.0)
var array<int> distN = array.new<int>(3, 0)
var array<int> aboveN = array.new<int>(3, 0)
if okChart and hasVol and barstate.isconfirmed
// 1. Existing anchors take in the current bar, then are checked (bars after confirmation only): "reached" means
// the low reached or went below a swing-low VWAP (high at or above a swing-high VWAP), gaps included.
for a in tests
a.pv += px * vol
a.v += vol
a.age += 1
float vw = a.v > 0 ? a.pv / a.v : na
if not a.touched and not na(vw)
if (a.dir == 1 and low <= vw) or (a.dir == -1 and high >= vw)
a.touched := true
a.held := a.dir == 1 ? close >= vw : close <= vw
// 2. Anchors whose window has elapsed are counted and dropped.
if tests.size() > 0
for i = tests.size() - 1 to 0
Anchor a = tests.get(i)
if a.age >= fwdBars
int k = a.dir == 1 ? 0 : 1
// Anchors whose VWAP never became valid (no volume from the swing bar to the end of the window) are not counted.
if a.v > 0
nTest.set(k, nTest.get(k) + 1)
nTouch.set(k, nTouch.get(k) + (a.touched ? 1 : 0))
nHeld.set(k, nHeld.get(k) + (a.touched and a.held ? 1 : 0))
tests.remove(i)
// 3. Displayed VWAPs: continue, or restart on a new confirmed swing (sums from the swing bar to now).
if not na(lowV)
lowPV += px * vol
lowV += vol
if not na(highV)
highPV += px * vol
highV += vol
if newLow
lowPV := swPV
lowV := swV
tests.push(Anchor.new(1, lowPV, lowV, 0, false, false))
if newHigh
highPV := swPV
highV := swV
tests.push(Anchor.new(-1, highPV, highV, 0, false, false))
// Values on closed bars use the committed sums; on the real-time bar the current bar is added provisionally.
float addPV = barstate.isconfirmed ? 0.0 : px * vol
float addV = barstate.isconfirmed ? 0.0 : vol
float lVwap = okChart and hasVol and not na(lowV) and lowV + addV > 0 ? (lowPV + addPV) / (lowV + addV) : na
float hVwap = okChart and hasVol and not na(highV) and highV + addV > 0 ? (highPV + addPV) / (highV + addV) : na
if okChart and hasVol and barstate.isconfirmed and not na(atr) and atr > 0
array<float> vals = array.from(wVwap, lVwap, hVwap)
for k = 0 to 2
float v = vals.get(k)
if not na(v)
distSum.set(k, distSum.get(k) + math.abs(close - v) / atr)
distN.set(k, distN.get(k) + 1)
aboveN.set(k, aboveN.get(k) + (close > v ? 1 : 0))
// ─────────────────────────────── Plots and alerts ───────────────────────────────
// Lines break on the bar where a swing VWAP restarts.
plot(showWeek ? wVwap : na, "Week VWAP", color = weekColor, style = plot.style_linebr, linewidth = 2)
plot(showLow and not newLow ? lVwap : na, "Swing Low VWAP", color = lowColor, style = plot.style_linebr, linewidth = 2)
plot(showHigh and not newHigh ? hVwap : na, "Swing High VWAP", color = highColor, style = plot.style_linebr, linewidth = 2)
bool crossDownLow = barstate.isconfirmed and not na(lVwap) and not newLow and close < lVwap and close[1] >= lVwap[1]
bool crossUpHigh = barstate.isconfirmed and not na(hVwap) and not newHigh and close > hVwap and close[1] <= hVwap[1]
alertcondition(crossDownLow, "Close below swing-low VWAP", "AVWAP: close below the swing-low VWAP on {{ticker}}")
alertcondition(crossUpHigh, "Close above swing-high VWAP", "AVWAP: close above the swing-high VWAP on {{ticker}}")
if crossDownLow or crossUpHigh
alert("AVWAP: close " + (crossDownLow ? "below the swing-low VWAP" : "above the swing-high VWAP") + " on " + syminfo.ticker, alert.freq_once_per_bar_close)
// ─────────────────────────────── Dashboard ───────────────────────────────
dashPosition(string p) =>
switch p
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
=> position.top_right
pct(int a, int n) =>
n > 0 ? str.tostring(100.0 * a / n, "#") + "%" : "—"
var table dash = na
string dashSize = dashSizeInput == "Tiny" ? size.tiny : dashSizeInput == "Normal" ? size.normal : size.small
if barstate.islast
table.delete(dash)
dash := na
if showDashboard
dash := table.new(dashPosition(dashPosInput), 4, 7, bgcolor = color.new(chart.bg_color, 10), frame_color = color.new(chart.fg_color, 80), frame_width = 1, border_color = color.new(chart.fg_color, 90), border_width = 1)
color dim = color.new(chart.fg_color, 30)
if not okChart
table.cell(dash, 0, 0, "AVWAP: use an intraday or daily chart with standard candles", text_color = highColor, text_size = dashSize)
else if not hasVol
table.cell(dash, 0, 0, "AVWAP: this symbol has no volume data", text_color = highColor, text_size = dashSize)
else
table.cell(dash, 0, 0, "AVWAP", text_color = chart.fg_color, text_size = dashSize, text_halign = text.align_left)
table.cell(dash, 1, 0, "Price", text_color = dim, text_size = dashSize)
table.cell(dash, 2, 0, "Avg dist", text_color = dim, text_size = dashSize, tooltip = "Average |close − VWAP| in ATR, over closed bars where the VWAP exists")
table.cell(dash, 3, 0, "Closes above", text_color = dim, text_size = dashSize)
array<string> nm = array.from("Week", "Swing low", "Swing high")
array<color> cl = array.from(weekColor, lowColor, highColor)
array<float> now = array.from(wVwap, lVwap, hVwap)
for k = 0 to 2
float v = now.get(k)
int n = distN.get(k)
table.cell(dash, 0, k + 1, nm.get(k), text_color = cl.get(k), text_size = dashSize, text_halign = text.align_left)
table.cell(dash, 1, k + 1, na(v) ? "—" : close >= v ? "above" : "below", text_color = chart.fg_color, text_size = dashSize)
table.cell(dash, 2, k + 1, n > 0 ? str.tostring(distSum.get(k) / n, "0.00") + " ATR" : "—", text_color = chart.fg_color, text_size = dashSize)
table.cell(dash, 3, k + 1, pct(aboveN.get(k), n), text_color = chart.fg_color, text_size = dashSize)
table.cell(dash, 0, 4, "Swing anchors, " + str.tostring(fwdBars) + " bars after confirmation", text_color = chart.fg_color, text_size = dashSize, text_halign = text.align_left)
table.merge_cells(dash, 0, 4, 3, 4)
table.cell(dash, 0, 5, "Swing low", text_color = lowColor, text_size = dashSize, text_halign = text.align_left)
table.cell(dash, 1, 5, "reached " + pct(nTouch.get(0), nTest.get(0)), text_color = chart.fg_color, text_size = dashSize, tooltip = "Share of swing-low anchors whose VWAP was reached or passed by a low within the window (gaps through it included)")
table.cell(dash, 2, 5, "held " + pct(nHeld.get(0), nTouch.get(0)), text_color = chart.fg_color, text_size = dashSize, tooltip = "Of those reached: share whose first reaching bar closed at or above the VWAP")
table.cell(dash, 3, 5, "n=" + str.tostring(nTest.get(0)), text_color = dim, text_size = dashSize)
table.cell(dash, 0, 6, "Swing high", text_color = highColor, text_size = dashSize, text_halign = text.align_left)
table.cell(dash, 1, 6, "reached " + pct(nTouch.get(1), nTest.get(1)), text_color = chart.fg_color, text_size = dashSize)
table.cell(dash, 2, 6, "held " + pct(nHeld.get(1), nTouch.get(1)), text_color = chart.fg_color, text_size = dashSize, tooltip = "Of those reached: share whose first reaching bar closed at or below the VWAP")
table.cell(dash, 3, 6, "n=" + str.tostring(nTest.get(1)), text_color = dim, text_size = dashSize)