本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// =============================================================================
// WVPO Spring-AVWAP-Slope
//
// Purpose : Classifies the anchored VWAP of a Spring low into three profiles -
// rising, flat, falling - and pairs that reading with where price
// sits relative to the line. Together those two axes are the fifth
// of the five hallmarks of a genuine Spring (the table row calls it
// characteristic 5).
// Reference : The Composite-Man Code, Volume II, chapter 20 (Setup 1a/1b, the
// Spring), hallmark 5 in 20.7; anchor mechanics from Volume I,
// chapter 12.
// License : Mozilla Public License 2.0 - WVPO
//
// It gives no entries, no exits, no targets and no win rates.
//
// -----------------------------------------------------------------------------
// WHAT IT READS
// Chapter 20.7 lists five hallmarks that separate a genuine Spring from a
// Spring trap. The fifth is this: the Spring AVWAP rises from the low, and
// price stays above its zone. The trap shows the mirror image - the line
// falls or stays flat, and price breaks below it or oscillates around it for
// a long time. That hallmark is the only one this script reads. It reads
// price against the line itself; the zone of +/- 0.3 x ATR(20) of the test
// timeframe (Volume I, chapter 12.5) is not drawn here.
//
// The other four are not in here and cannot be:
// 1. Phases A and B of the trading range are documented on the range
// timeframe, and the Spring is its phase C event.
// 2. Supply dries up at the low: little volume at the low, or, after a
// shakeout on heavy volume, a quiet test with a higher low.
// 3. The four-window consensus at the low is A or A+ (for 1a) or at least
// B (for 1b).
// 4. Price returns quickly above the edge and forms higher lows on the
// trigger timeframe.
// They need order flow, a volume profile and a judgment call. A tool that
// scored all five would be pretending to make that judgment for you. Volume
// enters this script only as the weight of the VWAP; it tests no volume
// threshold.
//
// WHAT THIS DOES THAT AN ANCHORED VWAP DOES NOT
// 1. It classifies the slope instead of drawing it. The rise is measured in
// ATR units over a lookback window, so the reading is comparable across
// instruments and timeframes rather than being a number of points that
// means something different on every chart.
// 2. It reads the second axis at the same time - above, below, or oscillating
// - and counts how the line has been treated since the anchor: the share
// of closes above it, and the current run of closes below it. A line that
// price crosses every third bar is not support, whatever its slope.
// 3. It states the verdict for one named hallmark and says out loud that it
// is one of five. The AND between the two axes is the point: a rising line
// that price keeps falling through is a trap symptom, not a Spring, and
// either axis on its own would call it wrong.
//
// -----------------------------------------------------------------------------
// ON THE THRESHOLD
// The default is a quarter of one average bar range over ten bars. Below that
// the line is flat for practical purposes: the participants who entered at
// the anchor are neither gaining nor losing ground fast enough for their cost
// basis to mean anything. The number is an input and a starting value,
// because the right value depends on the instrument and the timeframe.
// Calibrate it on your own documented Springs, the way chapter 20.5
// calibrates its thresholds over the first thirty per instrument.
//
// -----------------------------------------------------------------------------
// WORKED EXAMPLE - a mechanics check you can repeat
// Symbol NASDAQ:NDX, daily, source HLC3, manual anchor on 22 Nov 2021 (the
// UTAD of the master case in Volume I, chapter 12.3), rest default. This is
// an inverted case, and it is deliberately not a Spring:
// a) Through 2022 the verdict reads NOT MET on every bar. The price row
// reads BELOW for most of the year; the false reclaims of Volume I,
// 12.3 show as ABOVE on 29 and 30 Mar 2022 (on 29 Mar the line stands
// near 15,004 and the close at 15,239, about 235 points above it) and
// as OSCILLATING in early January and in April 2022. The profile reads
// FALLING from mid-January 2022, wavers between FALLING and FLAT near
// the threshold later in the year, and reads FLAT from February 2023.
// That drift is correct behavior, not an error - see the note on anchor
// age below.
// b) Price flips to ABOVE at the end of March 2023: on 30 Mar the line
// stands near 12,904 and the close at 12,963, clearly above on 31 Mar.
// The verdict still reads NOT MET at that moment, because the slope axis
// reads FLAT. If the verdict flipped with the price alone, the AND would
// be broken.
// c) Switch to automatic anchoring. The anchor appears exactly "right legs"
// bars after the low it marks, never earlier.
// The line levels can differ from yours by a few points, because the volume
// of the data feed weights the line.
//
// ON ANCHOR AGE
// An anchored VWAP is a cumulative average, so every additional bar carries
// less weight than the one before it. A line anchored five bars ago can move
// a full ATR in a session; a line anchored four hundred bars ago moves by a
// fraction of a point, because each new bar shifts it by roughly its distance
// from price divided by the bar count. The slope axis therefore flattens as
// the anchor ages, and it must. This tool reads the weeks after a Spring,
// when the cost basis of that event is still being formed and can still be
// defended or lost. On an anchor that is a year old the slope row will say
// FLAT and mean it: the question it answers has expired, not failed.
//
// Why the example is not the gold Spring of 14 Feb 2024 from chapter 20.4:
// that case runs on real daily and hourly bars of the April 2024 contract,
// but its five-minute and one-minute bars, the entry minute and the order
// flow are modeled in the book. A check of the code should rest on bars
// anyone can load, so the example uses NDX.
// =============================================================================
indicator(title = "WVPO Spring-AVWAP-Slope", shorttitle = "WVPO Slope",
overlay = true, max_bars_back = 1000)
// ---------------------------------------------------------------- the anchor
gA = "Anchor"
anchorMode = input.string("Manual", "Anchor mode", group = gA,
options = ["Manual", "Latest confirmed pivot low"],
tooltip = "Manual asks for a click when the script is added. Automatic re-anchors to the most recent confirmed pivot low, which by construction appears a few bars after the low itself.")
anchorTs = input.time(timestamp("2021-11-22T00:00:00"), "Manual anchor", confirm = true, group = gA)
pvLeft = input.int(10, "Pivot low - left legs", minval = 1, maxval = 100, group = gA)
pvRight = input.int(3, "Pivot low - right legs", minval = 1, maxval = 50, group = gA,
tooltip = "The confirmation delay. A pivot low is only a pivot once this many bars have closed above it, so the anchor always arrives this many bars late. That is the honest cost of automatic anchoring, not a defect.")
// ----------------------------------------------------------------- measurement
gM = "Measurement"
src = input.source(hlc3, "Source", group = gM,
tooltip = "HLC3 is the default because the figures in Volume I, chapter 12 were calculated on it. Switching to close shifts the line.")
atrLen = input.int(14, "ATR length", minval = 1, group = gM)
slopeLen = input.int(10, "Slope lookback (bars)", minval = 2, group = gM,
tooltip = "The slope is the rise of the line over this many bars, divided by ATR.")
slopeThr = input.float(0.25, "Rising / falling threshold (ATR)", minval = 0.01, step = 0.05, group = gM,
tooltip = "Above this the profile reads rising, below its negative it reads falling, in between it reads flat. A starting value: calibrate it per symbol on your own documented Springs, as Volume II, chapter 20.5 does for its thresholds (thirty per instrument).")
// ---------------------------------------------------------------- second axis
gP = "Price axis"
oscWin = input.int(20, "Oscillation window (bars)", minval = 5, group = gP)
oscMin = input.int(3, "Crossings that count as oscillating", minval = 2, group = gP,
tooltip = "Volume II, chapter 20.7 names oscillation around the line as a trap symptom. A line crossed this often inside the window is not being defended.")
breakRun = input.int(2, "Closes below that count as a break", minval = 1, group = gP,
tooltip = "Counts consecutive closes below the line itself. The setup card for 1b in Volume II, chapter 20.2 (field 9) uses two closes below the Spring AVWAP zone, +/- 0.3 x ATR(20) of the test timeframe; this script does not draw the zone.")
// -------------------------------------------------------------------- display
gD = "Display"
showTable = input.bool(true, "Show table", group = gD)
tblPos = input.string("top_right", "Table position", group = gD,
options = ["top_right", "top_left", "bottom_right", "bottom_left"])
markAnchor = input.bool(true, "Mark the anchor bar", group = gD)
// -------------------------------------------------- journal webhook, optional
// Optional: alerts as a JSON payload for a trading journal webhook. Empty by
// default, so alerts stay plain text; an alert that quietly posts an incomplete
// plan is worse than a plain one. Entry, stop and target are yours to fill -
// this script does not produce them, and the human sets the plan.
gJ = "Journal webhook (optional)"
whSecret = input.string("", "Webhook secret", group = gJ,
tooltip = "Leave empty to keep alerts as plain text. Filled in, the alert message becomes the JSON payload of the WVPO journal.")
whSetup = input.string("1a", "Setup type", group = gJ, options = ["1a", "1b"])
whEntry = input.price(0.0, "Entry (your plan)", group = gJ)
whStop = input.price(0.0, "Stop (your plan)", group = gJ)
whTarget = input.price(0.0, "Target (your plan)", group = gJ)
// =============================================================================
// Anchored VWAP. Accumulated by hand rather than with ta.vwap so that a symbol
// without a volume series degrades to an empty line and an n/a row instead of
// answering a different question in silence.
// =============================================================================
var int anchorBar = na
var int anchorTime = na
var float pv = 0.0
var float vv = 0.0
var int barsSince = 0
var int barsAbove = 0
var int belowRun = 0
manual = anchorMode == "Manual"
// First bar at or after the manual anchor.
manualStart = manual and time >= anchorTs and (na(time[1]) or time[1] < anchorTs)
// A pivot low confirms pvRight bars after the low itself.
pivotLow = ta.pivotlow(low, pvLeft, pvRight)
autoStart = not manual and not na(pivotLow)
reset = false
if manualStart
anchorBar := bar_index
anchorTime := time
pv := 0.0
vv := 0.0
barsSince := 0
barsAbove := 0
belowRun := 0
reset := true
v = nz(volume)
pv += src * v
vv += v
barsSince += 1
line0 = vv > 0 ? pv / vv : na
if not na(line0) and close > line0
barsAbove += 1
if not na(line0) and close < line0
belowRun += 1
else if autoStart
anchorBar := bar_index - pvRight
anchorTime := time[pvRight]
pv := 0.0
vv := 0.0
barsSince := 0
barsAbove := 0
belowRun := 0
reset := true
// Replay the bars from the pivot low up to the current one, oldest first.
// Pine counts the loop down when the start is greater than the end, so
// index pvRight is the anchor bar and index 0 is the current one.
for i = pvRight to 0
v = nz(volume[i])
pv += src[i] * v
vv += v
barsSince += 1
running = vv > 0 ? pv / vv : na
if not na(running)
if close[i] > running
barsAbove += 1
belowRun := close[i] < running ? belowRun + 1 : 0
if not reset and not na(anchorBar)
v = nz(volume)
pv += src * v
vv += v
barsSince += 1
running = vv > 0 ? pv / vv : na
if not na(running)
if close > running
barsAbove += 1
belowRun := close < running ? belowRun + 1 : 0
avw = vv > 0 ? pv / vv : na
atr = ta.atr(atrLen)
// =============================================================================
// Axis one: the slope, in ATR units over the lookback window.
// =============================================================================
measurable = not na(avw) and not na(avw[slopeLen]) and not na(atr) and atr > 0 and barsSince > slopeLen
slope = measurable ? (avw - avw[slopeLen]) / atr : na
rising = measurable and slope >= slopeThr
falling = measurable and slope <= -slopeThr
profile = not measurable ? "too early" : rising ? "RISING" : falling ? "FALLING" : "FLAT"
colRise = color.rgb(27, 94, 32) // Spring green
colFlat = color.rgb(120, 120, 120)
colFall = color.rgb(183, 28, 28) // distribution red
profileCol = rising ? colRise : falling ? colFall : colFlat
// =============================================================================
// Axis two: where price sits, and how the line has been treated since the anchor.
// =============================================================================
// barsSince > 1 keeps a re-anchor from registering as a crossing: right after a
// reset the previous bar's value still belongs to the old line.
crossedNow = not na(avw) and not na(avw[1]) and barsSince > 1 and
((close > avw and close[1] < avw[1]) or (close < avw and close[1] > avw[1])) ? 1 : 0
crosses = math.sum(crossedNow, oscWin)
oscillating = not na(avw) and crosses >= oscMin
above = not na(avw) and close > avw
distAtr = na(avw) or na(atr) or atr == 0 ? na : (close - avw) / atr
shareAbove = barsSince > 0 ? 100.0 * barsAbove / barsSince : na
broken = belowRun >= breakRun
priceState = na(avw) ? "n/a" : oscillating ? "OSCILLATING" : above ? "ABOVE" : "BELOW"
priceCol = na(avw) ? colFlat : oscillating ? colFlat : above ? colRise : colFall
// =============================================================================
// The verdict for characteristic 5, and for that one only.
// =============================================================================
met = rising and above and not oscillating
verdict = not measurable ? "too early" : met ? "MET" : "NOT MET"
verdictCol = not measurable ? colFlat : met ? colRise : colFall
// =============================================================================
// Plot. The line carries its own classification, which is the whole point of
// the tool: the profile is readable without opening the table.
// =============================================================================
plot(avw, "Spring AVWAP", color = profileCol, linewidth = 2)
// The marker has to be a label, not a shape. In automatic mode the anchor sits
// pvRight bars in the past by the time the pivot confirms, and a plot cannot
// reach backwards - only a drawing can.
var label anchorLbl = na
if markAnchor and reset and not na(anchorBar)
label.delete(anchorLbl)
anchorLbl := label.new(x = anchorBar, y = low, text = "anchor",
xloc = xloc.bar_index, yloc = yloc.belowbar, style = label.style_label_up,
color = colRise, textcolor = color.white, size = size.tiny)
// =============================================================================
// Table
// =============================================================================
f_pos() =>
tblPos == "top_left" ? position.top_left : tblPos == "bottom_right" ? position.bottom_right :
tblPos == "bottom_left" ? position.bottom_left : position.top_right
var table t = table.new(f_pos(), 2, 10, border_width = 1)
// "label" would shadow the built-in type of the same name, hence "caption".
f_row(int r, string caption, string value, color vc) =>
bg = color.new(color.gray, 90)
table.cell(t, 0, r, caption, text_size = size.small, text_halign = text.align_left, bgcolor = bg, text_color = color.new(color.gray, 0))
table.cell(t, 1, r, value, text_size = size.small, text_halign = text.align_right, bgcolor = bg, text_color = vc)
if showTable and barstate.islast
txt = color.new(color.gray, 0)
hdr = color.new(color.gray, 80)
table.cell(t, 0, 0, "Spring AVWAP", text_size = size.small, text_halign = text.align_left, bgcolor = hdr, text_color = txt)
table.cell(t, 1, 0, manual ? "manual" : "auto", text_size = size.small, text_halign = text.align_right, bgcolor = hdr, text_color = txt)
anchorTxt = na(anchorTime) ? (manual ? "not reached" : "waiting for pivot") :
str.format_time(anchorTime, "yyyy-MM-dd", syminfo.timezone)
f_row(1, "Anchor", anchorTxt, txt)
f_row(2, "Bars since", na(anchorBar) ? "n/a" : str.tostring(barsSince), txt)
f_row(3, "Line", na(avw) ? "n/a" : str.tostring(avw, format.mintick), txt)
f_row(4, "Slope / " + str.tostring(slopeLen) + " bars",
na(slope) ? "n/a" : (slope >= 0 ? "+" : "") + str.tostring(slope, "#.00") + " ATR", profileCol)
f_row(5, "Profile", profile, profileCol)
f_row(6, "Price", na(distAtr) ? priceState :
priceState + " " + (distAtr >= 0 ? "+" : "") + str.tostring(distAtr, "#.00") + " ATR", priceCol)
f_row(7, "Closes above", na(shareAbove) ? "n/a" : str.tostring(shareAbove, "#") + " % · " +
str.tostring(crosses, "#") + " crossings", broken ? colFall : txt)
f_row(8, "Characteristic 5", verdict, verdictCol)
f_row(9, "of five - see 20.7", "the other four are not in here", color.new(color.gray, 30))
// =============================================================================
// Alerts. The alert() calls at the end fire once per bar close. For the three
// alertcondition() entries choose "Once Per Bar Close" when you create the
// alert, otherwise they can fire inside a bar that has not closed yet. Values
// on closed bars do not change afterwards: in automatic mode the anchor is a
// confirmed pivot that no longer moves.
// =============================================================================
profileChanged = measurable and measurable[1] and profile != profile[1]
verdictLost = measurable and measurable[1] and met[1] and not met
brokeNow = broken and not broken[1]
alertcondition(profileChanged, "Slope profile changed", "WVPO: the spring AVWAP profile changed")
alertcondition(verdictLost, "Characteristic 5 lost", "WVPO: characteristic 5 is no longer met")
alertcondition(brokeNow, "Line broken", "WVPO: consecutive closes below the spring AVWAP")
f_plain(string what) =>
what + " | " + syminfo.ticker + " | profile " + profile + " | price " + priceState +
(na(distAtr) ? "" : " " + (distAtr >= 0 ? "+" : "") + str.tostring(distAtr, "#.00") + " ATR")
// The journal payload: secret, instrument, direction, entry, stop, target,
// setup type and timestamp.
f_json() =>
e = na(whEntry) ? 0.0 : whEntry
s = na(whStop) ? 0.0 : whStop
tg = na(whTarget) ? 0.0 : whTarget
'{"secret":"' + whSecret +
'","instrument":"' + syminfo.ticker +
'","richtung":"long","entry":' + str.tostring(e) +
',"stop":' + str.tostring(s) +
',"target":' + str.tostring(tg) +
',"setup_typ":"' + whSetup +
'","ts":"' + str.format_time(time, "yyyy-MM-dd'T'HH:mm:ss'Z'", "UTC") + '"}'
useJson = str.length(whSecret) > 0
if barstate.isconfirmed and profileChanged
alert(useJson ? f_json() : f_plain("WVPO spring AVWAP profile changed"), alert.freq_once_per_bar_close)
if barstate.isconfirmed and verdictLost
alert(useJson ? f_json() : f_plain("WVPO characteristic 5 lost"), alert.freq_once_per_bar_close)
if barstate.isconfirmed and brokeNow
alert(useJson ? f_json() : f_plain("WVPO spring AVWAP broken"), alert.freq_once_per_bar_close)