Auto Anchored VWAP Zones - Liquidity Sweeps [AFD]

AuctionFoundry · study · 654 行 · 点赞 10 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Source Code Form is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Auction Foundry
//@version=6
 
indicator("Auto Anchored VWAP Zones - Liquidity Sweeps [AFD]", "AAVZ [AFD]", overlay = true,
     max_bars_back = 2000, max_labels_count = 30, max_polylines_count = 20)
 
const string GRP_ANCHORS = "Session & week"
const string GRP_PIVOTS  = "Pivot VWAPs"
const string GRP_SWEEPS  = "Sweep VWAPs"
const string GRP_ZONES   = "Zones"
const string GRP_AXIS    = "Price axis labels"
const string GRP_LABELS  = "Labels"
 
const string SRC_OPEN  = "open"
const string SRC_HIGH  = "high"
const string SRC_LOW   = "low"
const string SRC_HL2   = "hl2"
const string SRC_CLOSE = "close"
const string SRC_HLC3  = "Typical price (HLC3 — default)"
const string SRC_OHLC4 = "ohlc4"
 
const string SWEPT_GRAY = "Gray"
const string SWEPT_SAME = "Unchanged"
const string SWEPT_HIDE = "Hide"
 
const string PAIR_PERIODS = "Daily / Weekly"
const string PAIR_PIVOTS = "Pivots"
const string PAIR_SWEEPS = "Sweeps"
 
const string CLOUD_OFF = "Off"
const string CLOUD_DIRECTION = "Directional colour"
 
const int SESSION_HIDDEN_FROM_SECONDS = 86400    // 1D
const int WEEK_HIDDEN_FROM_SECONDS    = 604800   // 1W
 
const int ATR_LENGTH = 14
 
const int PIVOT_SLOTS = 5
const int SWEEP_SLOTS = 3
 
const color SWEPT_COLOR = #787B86
 
const int RANK_PH = 0
const int RANK_PL = 5
const int RANK_S  = 10
const int RANK_SH = 11
const int RANK_SL = 14
const int RANK_W  = 17
 
const string SEP                = " · "
const string MSG_NO_VOLUME      = "No volume in loaded history — nothing drawn"
const string MSG_VOLUME_GAP     = "No recent volume — current VWAPs hidden"
const string MSG_SESSION_HIDDEN = "Session VWAP hidden on 1D and higher"
const string MSG_WEEK_HIDDEN    = "Week VWAP hidden on 1W and higher"
 
string sourceInput       = input.string(SRC_HLC3, "Source price", options = [SRC_OPEN, SRC_HIGH, SRC_LOW, SRC_CLOSE, SRC_HL2, SRC_HLC3, SRC_OHLC4],
     group = GRP_ANCHORS,
     tooltip = "• Selects the price for each candle.\n• Typical price is (high + low + close) ÷ 3.\n• VWAP weights price by volume.\n• Each average starts at its own anchor.",
     display = display.data_window)
bool   sessionOnInput    = input.bool(true, "Session VWAP", inline = "session", group = GRP_ANCHORS,
     display = display.none)
color  sessionColorInput = input.color(#FFD54F, "", inline = "session", group = GRP_ANCHORS,
     tooltip = "• Resets at the chart session open.\n• Includes extended hours when selected.\n• Shown below the daily chart interval.",
     active = sessionOnInput, display = display.none)
bool   weekOnInput       = input.bool(true, "Week VWAP", inline = "week", group = GRP_ANCHORS,
     display = display.none)
color  weekColorInput    = input.color(#26C6DA, "", inline = "week", group = GRP_ANCHORS,
     tooltip = "• Resets at the start of the exchange week.\n• Shown below the weekly chart interval.",
     active = weekOnInput, display = display.none)
 
bool   pivotsOnInput       = input.bool(true, "Pivot VWAPs", group = GRP_PIVOTS,
     tooltip = "• Anchors at swing highs and lows.\n• Confirms after Swing length bars close\n  to the right of the swing.\n• Draws back to the original swing bar.\n• Updates with price and volume.", display = display.none)
int    pivotLengthInput    = input.int(10, "Swing length (bars each side)", minval = 2, maxval = 50,
     group = GRP_PIVOTS, tooltip = "• Bars on both sides of a swing.\n• Equal highs or lows do not qualify.\n• More bars delay confirmation.\n• Also sets the swings used for sweeps.", display = display.none)
int    keepPivotHighsInput = input.int(2, "Keep swing highs", minval = 0, maxval = 5,
     group = GRP_PIVOTS, tooltip = "• Keeps this many recent swing-high VWAPs.\n• 0 hides them. Max age still applies.",
     active = pivotsOnInput, display = display.none)
int    keepPivotLowsInput  = input.int(2, "Keep swing lows", minval = 0, maxval = 5, group = GRP_PIVOTS,
     tooltip = "• Keeps this many recent swing-low VWAPs.\n• 0 hides them. Max age still applies.",
     active = pivotsOnInput, display = display.none)
color  pivotHighColorInput = input.color(#FF8A65, "Pivot high", inline = "pivotHigh", group = GRP_PIVOTS,
     tooltip = "• Sets the color of swing-high VWAPs.",
     active = pivotsOnInput, display = display.none)
color  pivotLowColorInput  = input.color(#B388FF, "Pivot low", inline = "pivotLow", group = GRP_PIVOTS,
     tooltip = "• Sets the color of swing-low VWAPs.",
     active = pivotsOnInput, display = display.none)
string sweptDisplayInput   = input.string(SWEPT_GRAY, "Swept pivot", options = [SWEPT_GRAY, SWEPT_SAME, SWEPT_HIDE],
     group = GRP_PIVOTS,
     tooltip = "• Gray recolors the entire swept VWAP.\n• Unchanged keeps its original color.\n• Hide removes the line and its labels.\n• Hidden swings cannot form a value zone.",
     active = pivotsOnInput, display = display.none)
int    maxAgeInput         = input.int(300, "Max age (bars)", minval = 20, maxval = 2000, group = GRP_PIVOTS,
     tooltip = "• Removes swings and sweeps past this age.\n• Longer volume gaps hide current VWAPs.\n• D and W reset at their period starts.", display = display.none)
 
bool   sweepsOnInput       = input.bool(true, "Sweep VWAPs", group = GRP_SWEEPS,
     tooltip = "• Watches the newest unswept swing.\n• A sweep trades past it and closes inside.\n• VWAP starts on that sweep candle.\n• Swept-pivot styling works independently.", display = display.none)
int    keepSweepHighsInput = input.int(1, "Keep high sweeps", minval = 0, maxval = 3,
     group = GRP_SWEEPS, tooltip = "• Keeps this many recent high-sweep VWAPs.\n• 0 hides them. Max age still applies.",
     active = sweepsOnInput, display = display.none)
int    keepSweepLowsInput  = input.int(1, "Keep low sweeps", minval = 0, maxval = 3,
     group = GRP_SWEEPS,
     tooltip = "• Keeps this many recent low-sweep VWAPs.\n• 0 hides them. Max age still applies.",
     active = sweepsOnInput, display = display.none)
float  penetrationInput    = input.float(0.0, "Minimum penetration (× ATR 14)", minval = 0.0, maxval = 5.0,
     step = 0.05, group = GRP_SWEEPS, tooltip = "• Extra wick distance in ATR(14) units.\n• At 0, the wick still crosses the swing.\n• The candle must close back inside.\n• Requires ATR and defines swept pivots.",
     active = sweepsOnInput or (pivotsOnInput and (sweptDisplayInput == SWEPT_HIDE or sweptDisplayInput == SWEPT_GRAY)), display = display.none)
color  sweepHighColorInput = input.color(#EF5350, "High sweep", inline = "sweepHigh", group = GRP_SWEEPS,
     tooltip = "• Sets the color of high-sweep VWAPs.",
     active = sweepsOnInput, display = display.none)
color  sweepLowColorInput  = input.color(#26A69A, "Low sweep", inline = "sweepLow", group = GRP_SWEEPS,
     tooltip = "• Sets the color of low-sweep VWAPs.",
     active = sweepsOnInput, display = display.none)
 
bool tagsOnInput = input.bool(true, "Line labels", group = GRP_LABELS,
     tooltip = "• Shows names beside the VWAP lines.\n• 1 marks the newest anchor in each family.\n• Partial-history notes remain visible.",
     display = display.none)
int labelOffsetInput = input.int(2, "Label offset (bars)", minval = 0, maxval = 20, group = GRP_LABELS,
     tooltip = "• Base gap in bars from the VWAP endpoint.\n• Swing and sweep names add their indents.",
     active = tagsOnInput, display = display.none)
 
bool dailyAxisInput = input.bool(true, "Daily", group = GRP_AXIS,
     tooltip = "• Shows session VWAP on the price axis.",
     active = sessionOnInput, display = display.none)
bool weeklyAxisInput = input.bool(true, "Weekly", group = GRP_AXIS,
     tooltip = "• Shows weekly VWAP on the price axis.",
     active = weekOnInput, display = display.none)
bool swingsAxisInput = input.bool(true, "Swings", group = GRP_AXIS,
     tooltip = "• Price-axis values for visible swings.\n• Each value matches its line color.",
     active = pivotsOnInput and (keepPivotHighsInput > 0 or keepPivotLowsInput > 0), display = display.none)
bool sweepsAxisInput = input.bool(true, "Sweeps", group = GRP_AXIS,
     tooltip = "• Price-axis values for visible sweeps.\n• Each value matches its line color.",
     active = sweepsOnInput and (keepSweepHighsInput > 0 or keepSweepLowsInput > 0), display = display.none)
 
bool   zone2OnInput         = input.bool(true, "Value zone", inline = "zone2", group = GRP_ZONES,
     display = display.none)
string zone2PairInput       = input.string(PAIR_PIVOTS, "", options = [PAIR_PERIODS, PAIR_PIVOTS, PAIR_SWEEPS], inline = "zone2",
     group = GRP_ZONES, active = zone2OnInput, display = display.none)
color  zone2ColorInput      = input.color(#B388FF26, "", inline = "zone2", group = GRP_ZONES,
     tooltip = "• Shades D/W, the latest swing pair, or the\n  latest sweep pair.\n• Both lines must be visible. Swing and\n  sweep pairs need two shared points.\n• D/W replaces the directional cloud.",
     active = zone2OnInput, display = display.none)
bool periodValueZoneInput = zone2OnInput and zone2PairInput == PAIR_PERIODS
string cloudModeInput = input.string(CLOUD_DIRECTION, "Daily / Weekly cloud",
     options = [CLOUD_OFF, CLOUD_DIRECTION], group = GRP_ZONES,
     tooltip = "• Shades the space between D and W.\n• Color shows which VWAP is higher.\n• Breaks at session or week resets.\n• The Daily / Weekly zone replaces it.",
     active = not periodValueZoneInput and sessionOnInput and weekOnInput, display = display.none)
bool cloudActiveInput = cloudModeInput != CLOUD_OFF and not periodValueZoneInput and sessionOnInput and weekOnInput
color  zone1AboveColorInput = input.color(#26A69A, "Daily above / below Weekly", inline = "zone1Hue", group = GRP_ZONES,
     active = cloudActiveInput, display = display.none)
color  zone1BelowColorInput = input.color(#EF5350, "", inline = "zone1Hue", group = GRP_ZONES,
     tooltip = "• Sets cloud colors for D above or below W.",
     active = cloudActiveInput, display = display.none)
int    cloudTransparencyInput = input.int(85, "Cloud transparency", minval = 0, maxval = 100, group = GRP_ZONES,
     tooltip = "• 0 is solid. 100 is invisible.",
     active = cloudActiveInput, display = display.none)
 
// Keep the earlier input order for existing chart instances.
int swingLabelIndentInput = input.int(4, "Swing label indent (bars)", minval = 0, maxval = 30, group = GRP_LABELS,
     tooltip = "• Extra bars after the base label gap.\n• 0 aligns swing names with D and W.",
     active = tagsOnInput and pivotsOnInput and (keepPivotHighsInput > 0 or keepPivotLowsInput > 0), display = display.none)
int sweepLabelIndentInput = input.int(11, "Sweep label indent (bars)", minval = 0, maxval = 30, group = GRP_LABELS,
     tooltip = "• Extra bars after the base label gap.\n• 0 aligns sweep names with D and W.",
     active = tagsOnInput and sweepsOnInput and (keepSweepHighsInput > 0 or keepSweepLowsInput > 0), display = display.none)
 
string labelFontSizeInput = input.string("Small", "Label font size", options = ["Tiny", "Small", "Normal", "Large", "Huge"],
     group = GRP_LABELS, tooltip = "• Sizes the names beside VWAP lines.\n• Small is the default.",
     active = tagsOnInput, display = display.none)
bool labelGuidesInput = input.bool(false, "Dotted label guides", group = GRP_LABELS,
     tooltip = "• Thin dotted line from VWAP to its name.\n• Uses the VWAP line color.\n• Appears when the name is offset.",
     active = tagsOnInput, display = display.none)
 
string labelTextSize = switch labelFontSizeInput
    "Tiny" => size.tiny
    "Normal" => size.normal
    "Large" => size.large
    "Huge" => size.huge
    => size.small
 
sourcePriceOf(string mode) =>
    switch mode
        SRC_OPEN => open
        SRC_HIGH => high
        SRC_LOW => low
        SRC_HL2 => hl2
        SRC_CLOSE => close
        SRC_OHLC4 => ohlc4
        => hlc3
 
windowMeanOf(float windowWeight, float windowPrice) =>
    bool usable = not na(windowWeight) and not na(windowPrice) and windowWeight > 0.0
    usable ? windowPrice / windowWeight : na
 
// Rebase each window at its first weighted price to avoid subtracting large running totals.
avwapOf(float windowWeight, float windowPrice, float reference) =>
    float mean = windowMeanOf(windowWeight, windowPrice)
    na(mean) or na(reference) ? na : reference + mean
 
pushRecord(array<int> anchors, array<int> sweptAt, int anchor, int slots) =>
    array.push(anchors, anchor)
    array.push(sweptAt, int(na))
    if array.size(anchors) > slots
        array.remove(anchors, 0)
        array.remove(sweptAt, 0)
 
markSwept(array<int> anchors, array<int> sweptAt, int anchor, int atBar) =>
    int count = array.size(anchors)
    if count > 0
        for i = 0 to count - 1
            if array.get(anchors, i) == anchor
                array.set(sweptAt, i, atBar)
 
int  chartSeconds    = timeframe.in_seconds()
bool sessionTfHidden = chartSeconds >= SESSION_HIDDEN_FROM_SECONDS
bool weekTfHidden    = chartSeconds >= WEEK_HIDDEN_FROM_SECONDS
 
float atrValue = ta.atr(ATR_LENGTH)
 
float barWeight = nz(volume)
 
var int lastVolumeBar = na
if barWeight > 0.0
    lastVolumeBar := bar_index
bool hasVolume = not na(lastVolumeBar) and bar_index - lastVolumeBar <= maxAgeInput
 
float barPrice = sourcePriceOf(sourceInput)
float barW  = na(barPrice) ? 0.0 : barWeight
 
// The ring holds every bar a retained anchor can reach, including the developing bar.
int ringSize = maxAgeInput + 1
 
var array<float> ringWeight = array.new_float(ringSize, 0.0)
var array<float> ringPrice  = array.new_float(ringSize, 0.0)
array.set(ringWeight, bar_index % ringSize, barW)
array.set(ringPrice, bar_index % ringSize, barPrice)
 
vwapBetween(int anchor, int toBar) =>
    float windowWeight = 0.0
    float windowPrice  = 0.0
    float reference    = na
    int span = toBar - anchor
    if span >= 0
        for k = 0 to span
            int slot = (anchor + k) % ringSize
            float weight = array.get(ringWeight, slot)
            float price  = array.get(ringPrice, slot)
            if weight > 0.0
                if na(reference)
                    reference := price
                windowWeight += weight
                windowPrice  += (price - reference) * weight
    avwapOf(windowWeight, windowPrice, reference)
 
vwapSince(int anchor) =>
    vwapBetween(anchor, bar_index)
 
// Bar zero may start mid-period even when session.isfirstbar is true.
bool weekChanged  = timeframe.change("1W")
 
bool sessionStarts = bar_index > 0 and session.isfirstbar
bool weekStarts    = bar_index > 0 and weekChanged
 
var float sessionWeight  = 0.0
var float sessionPrice   = 0.0
var float sessionReference = na
var bool  sessionPartial = true
if sessionStarts
    sessionWeight  := 0.0
    sessionPrice   := 0.0
    sessionReference := na
    sessionPartial := false
if barW > 0.0
    if na(sessionReference)
        sessionReference := barPrice
    sessionWeight += barW
    sessionPrice  += (barPrice - sessionReference) * barW
 
var float weekWeight  = 0.0
var float weekPrice   = 0.0
var float weekReference = na
var bool  weekPartial = true
if weekStarts
    weekWeight  := 0.0
    weekPrice   := 0.0
    weekReference := na
    weekPartial := false
if barW > 0.0
    if na(weekReference)
        weekReference := barPrice
    weekWeight += barW
    weekPrice  += (barPrice - weekReference) * barW
 
bool  sessionShown = sessionOnInput and not sessionTfHidden and hasVolume
bool  weekShown    = weekOnInput and not weekTfHidden and hasVolume
float sessionVwap  = sessionShown ? avwapOf(sessionWeight, sessionPrice, sessionReference) : na
float weekVwap     = weekShown ? avwapOf(weekWeight, weekPrice, weekReference) : na
 
// Confirm only on bar close, then draw back to the swing bar.
// Sweep references keep their own stack, independent of the display keep counts.
var array<int>   unsweptHighBars   = array.new_int()
var array<float> unsweptHighPrices = array.new_float()
var array<int>   unsweptLowBars    = array.new_int()
var array<float> unsweptLowPrices  = array.new_float()
 
var array<int> pivotHighAnchors = array.new_int()
var array<int> pivotHighSweptAt = array.new_int()
var array<int> pivotLowAnchors  = array.new_int()
var array<int> pivotLowSweptAt  = array.new_int()
var array<int> sweepHighAnchors = array.new_int()
var array<int> sweepHighSweptAt = array.new_int()
var array<int> sweepLowAnchors  = array.new_int()
var array<int> sweepLowSweptAt  = array.new_int()
 
int swingLength = pivotLengthInput
 
if barstate.isconfirmed and bar_index >= 2 * swingLength
    float candidateHigh = high[swingLength]
    float candidateLow  = low[swingLength]
    bool  isSwingHigh   = true
    bool  isSwingLow    = true
    for i = 0 to 2 * swingLength
        if i != swingLength
            if high[i] >= candidateHigh
                isSwingHigh := false
            if low[i] <= candidateLow
                isSwingLow := false
    int pivotBar = bar_index - swingLength
    if isSwingHigh
        array.push(unsweptHighBars, pivotBar)
        array.push(unsweptHighPrices, candidateHigh)
        pushRecord(pivotHighAnchors, pivotHighSweptAt, pivotBar, PIVOT_SLOTS)
    if isSwingLow
        array.push(unsweptLowBars, pivotBar)
        array.push(unsweptLowPrices, candidateLow)
        pushRecord(pivotLowAnchors, pivotLowSweptAt, pivotBar, PIVOT_SLOTS)
 
// Evaluate sweeps after pivot detection so this close can establish the reference.
if barstate.isconfirmed and not na(atrValue)
    float penetration = penetrationInput * atrValue
    int highCount = array.size(unsweptHighPrices)
    if highCount > 0
        float swingHigh = array.get(unsweptHighPrices, highCount - 1)
        if high > swingHigh + penetration and close < swingHigh
            int sweptBar = array.pop(unsweptHighBars)
            array.pop(unsweptHighPrices)
            markSwept(pivotHighAnchors, pivotHighSweptAt, sweptBar, bar_index)
            pushRecord(sweepHighAnchors, sweepHighSweptAt, bar_index, SWEEP_SLOTS)
    int lowCount = array.size(unsweptLowPrices)
    if lowCount > 0
        float swingLow = array.get(unsweptLowPrices, lowCount - 1)
        if low < swingLow - penetration and close > swingLow
            int sweptBar = array.pop(unsweptLowBars)
            array.pop(unsweptLowPrices)
            markSwept(pivotLowAnchors, pivotLowSweptAt, sweptBar, bar_index)
            pushRecord(sweepLowAnchors, sweepLowSweptAt, bar_index, SWEEP_SLOTS)
 
var int hueSign = 0
if not na(sessionVwap) and not na(weekVwap)
    if sessionVwap > weekVwap
        hueSign := 1
    else if sessionVwap < weekVwap
        hueSign := -1
 
bool periodZoneReady = not na(sessionVwap) and not na(weekVwap) and not sessionStarts and not weekStarts
bool zone1Shown = periodZoneReady and cloudActiveInput and hueSign != 0
color zone1Color = zone1Shown ? color.new(hueSign > 0 ? zone1AboveColorInput : zone1BelowColorInput,
     cloudTransparencyInput) : na
color periodZoneColor = periodZoneReady and periodValueZoneInput ? zone2ColorInput : na
 
// Hide the joining segment and fill at period resets.
sessionPlot = plot(sessionVwap, "Session VWAP", sessionStarts ? na : sessionColorInput,
     3, linestyle = plot.linestyle_dotted,
     display = dailyAxisInput ? display.all - display.status_line : display.all - display.status_line - display.price_scale)
weekPlot    = plot(weekVwap, "Week VWAP", weekStarts ? na : weekColorInput,
     3, linestyle = plot.linestyle_dotted,
     display = weeklyAxisInput ? display.all - display.status_line : display.all - display.status_line - display.price_scale)
fill(sessionPlot, weekPlot, zone1Color, "Session vs week cloud")
fill(sessionPlot, weekPlot, periodZoneColor, "Daily / Weekly value zone")
 
var array<polyline> drawnPolylines = array.new<polyline>()
var array<label>    drawnLabels    = array.new_label()
var array<line>     labelGuides    = array.new_line()
 
var array<int>    streamAnchor  = array.new_int()
var array<float>  streamValue   = array.new_float()
var array<string> streamTag     = array.new_string()
var array<int>    streamRank    = array.new_int()
var array<color>  streamColor   = array.new_color()
var array<string> streamStyle   = array.new_string()
var array<int>    streamWidth   = array.new_int()
var array<bool>   streamVisible = array.new_bool()
 
// Preserve stable axis slots even when a retained stream is hidden.
var array<float> axisValueArray = array.new_float(RANK_W + 1, na)
var array<color> axisColorArray = array.new_color(RANK_W + 1, na)
 
var array<float>  tagValue   = array.new_float()
var array<int>    tagRank    = array.new_int()
var array<string> tagBase    = array.new_string()
var array<color>  tagColor   = array.new_color()
var array<bool>   tagPartial = array.new_bool()
 
var array<chart.point> curvePoints  = array.new<chart.point>()
var array<chart.point> curveScratch = array.new<chart.point>()
 
collectFamily(array<int> anchors, array<int> sweptAt, int keep, string prefix, int rankBase,
     color familyColor, string familyStyle, int familyWidth) =>
    int stored = array.size(anchors)
    int kept   = 0
    if keep > 0 and stored > 0
        for k = 0 to math.min(keep, stored) - 1
            int anchor = array.get(anchors, stored - 1 - k)
            if bar_index - anchor <= maxAgeInput
                kept += 1
                bool swept  = not na(array.get(sweptAt, stored - 1 - k))
                bool hidden = swept and sweptDisplayInput == SWEPT_HIDE
                bool gray   = swept and sweptDisplayInput == SWEPT_GRAY
                array.push(streamAnchor, anchor)
                array.push(streamValue, vwapSince(anchor))
                array.push(streamTag, prefix + str.tostring(kept))
                array.push(streamRank, rankBase + kept - 1)
                array.push(streamColor, gray ? SWEPT_COLOR : familyColor)
                array.push(streamStyle, gray ? line.style_dotted : familyStyle)
                array.push(streamWidth, gray ? 1 : familyWidth)
                array.push(streamVisible, not hidden)
    kept
 
visibleStreamOf(string tag) =>
    int found = -1
    int count = array.size(streamTag)
    if count > 0
        for i = 0 to count - 1
            if array.get(streamTag, i) == tag and array.get(streamVisible, i)
                found := i
    found
 
// Sum forward for both sides; reverse only the points that close a zone.
pushCurve(array<chart.point> points, int anchor, int fromBar, bool reversed) =>
    float windowWeight = 0.0
    float windowPrice  = 0.0
    float reference    = na
    int span = bar_index - anchor
    if span >= 0
        for k = 0 to span
            int x    = anchor + k
            int slot = x % ringSize
            float weight = array.get(ringWeight, slot)
            float price  = array.get(ringPrice, slot)
            if weight > 0.0
                if na(reference)
                    reference := price
                windowWeight += weight
                windowPrice  += (price - reference) * weight
            float value = avwapOf(windowWeight, windowPrice, reference)
            if x >= fromBar and not na(value)
                chart.point point = chart.point.from_index(x, value)
                if reversed
                    array.push(curveScratch, point)
                else
                    array.push(points, point)
    int scratchCount = array.size(curveScratch)
    if scratchCount > 0
        for k = scratchCount - 1 to 0
            array.push(points, array.get(curveScratch, k))
        array.clear(curveScratch)
 
emitCurve(array<chart.point> points, color curveColor, string curveStyle, int curveWidth) =>
    if array.size(points) > 1
        array.push(drawnPolylines, polyline.new(points, xloc = xloc.bar_index, line_color = curveColor,
             line_style = curveStyle, line_width = curveWidth))
    array.clear(points)
 
anchorName(string tag) =>
    switch
        tag == "S" => "D"
        str.startswith(tag, "PH") => "Swing H" + str.substring(tag, 2, 3)
        str.startswith(tag, "PL") => "Swing L" + str.substring(tag, 2, 3)
        str.startswith(tag, "SH") => "Sweep H" + str.substring(tag, 2, 3)
        str.startswith(tag, "SL") => "Sweep L" + str.substring(tag, 2, 3)
        => tag
 
addTag(int x, float price, string tagText, color lineColor, string hover) =>
    array.push(drawnLabels, label.new(x, price, tagText, xloc = xloc.bar_index, color = na,
         style = label.style_label_left, textcolor = lineColor, size = labelTextSize, tooltip = hover,
         text_formatting = text.format_bold))
 
placeLabelGuide(int slot, int x, float price, color lineColor) =>
    if slot < array.size(labelGuides)
        line guide = array.get(labelGuides, slot)
        line.set_xy1(guide, bar_index, price)
        line.set_xy2(guide, x, price)
        line.set_color(guide, lineColor)
    else
        array.push(labelGuides, line.new(bar_index, price, x, price, xloc = xloc.bar_index,
             extend = extend.none, color = lineColor, style = line.style_dotted, width = 1))
 
addTagCandidate(float value, int rank, string base, color baseColor, bool partial) =>
    int count = array.size(tagValue)
    int pos   = count
    if count > 0
        for i = 0 to count - 1
            float other     = array.get(tagValue, i)
            int   otherRank = array.get(tagRank, i)
            if other > value or (other == value and otherRank > rank)
                pos := i
                break
    array.insert(tagValue, pos, value)
    array.insert(tagRank, pos, rank)
    array.insert(tagBase, pos, base)
    array.insert(tagColor, pos, baseColor)
    array.insert(tagPartial, pos, partial)
 
// Clear each execution so an absent stream cannot leave a stale axis value.
array.fill(axisValueArray, na)
array.fill(axisColorArray, na)
 
if barstate.islast
    int guidesUsed = 0
    if array.size(drawnPolylines) > 0
        for i = 0 to array.size(drawnPolylines) - 1
            polyline.delete(array.get(drawnPolylines, i))
        array.clear(drawnPolylines)
    if array.size(drawnLabels) > 0
        for i = 0 to array.size(drawnLabels) - 1
            label.delete(array.get(drawnLabels, i))
        array.clear(drawnLabels)
    array.clear(streamAnchor)
    array.clear(streamValue)
    array.clear(streamTag)
    array.clear(streamRank)
    array.clear(streamColor)
    array.clear(streamStyle)
    array.clear(streamWidth)
    array.clear(streamVisible)
    array.clear(tagValue)
    array.clear(tagRank)
    array.clear(tagBase)
    array.clear(tagColor)
    array.clear(tagPartial)
 
    if hasVolume
        collectFamily(pivotHighAnchors, pivotHighSweptAt, pivotsOnInput ? keepPivotHighsInput : 0, "PH", RANK_PH,
             pivotHighColorInput, line.style_dotted, 1)
        collectFamily(pivotLowAnchors, pivotLowSweptAt, pivotsOnInput ? keepPivotLowsInput : 0, "PL", RANK_PL,
             pivotLowColorInput, line.style_dotted, 1)
        collectFamily(sweepHighAnchors, sweepHighSweptAt, sweepsOnInput ? keepSweepHighsInput : 0, "SH", RANK_SH,
             sweepHighColorInput, line.style_dotted, 2)
        collectFamily(sweepLowAnchors, sweepLowSweptAt, sweepsOnInput ? keepSweepLowsInput : 0, "SL", RANK_SL,
             sweepLowColorInput, line.style_dotted, 2)
        int streamCount = array.size(streamAnchor)
 
        if zone2OnInput and not periodValueZoneInput
            int upper = visibleStreamOf(zone2PairInput == PAIR_PIVOTS ? "PH1" : "SH1")
            int lower = visibleStreamOf(zone2PairInput == PAIR_PIVOTS ? "PL1" : "SL1")
            if upper >= 0 and lower >= 0
                int upperAnchor = array.get(streamAnchor, upper)
                int lowerAnchor = array.get(streamAnchor, lower)
                int zoneStart   = math.max(upperAnchor, lowerAnchor)
                // Two shared points are required before the zone can be filled.
                int firstShared = na
                for k = 0 to bar_index - zoneStart
                    if array.get(ringWeight, (zoneStart + k) % ringSize) > 0.0
                        firstShared := zoneStart + k
                        break
                if not na(firstShared) and firstShared < bar_index
                    pushCurve(curvePoints, upperAnchor, firstShared, false)
                    pushCurve(curvePoints, lowerAnchor, firstShared, true)
                    array.push(drawnPolylines, polyline.new(curvePoints, closed = true, xloc = xloc.bar_index,
                         line_color = color.new(zone2ColorInput, 100), fill_color = zone2ColorInput))
                array.clear(curvePoints)
        if streamCount > 0
            for i = 0 to streamCount - 1
                if array.get(streamVisible, i)
                    int anchor = array.get(streamAnchor, i)
                    pushCurve(curvePoints, anchor, anchor, false)
                    emitCurve(curvePoints, array.get(streamColor, i), array.get(streamStyle, i),
                         array.get(streamWidth, i))
                    float value = array.get(streamValue, i)
                    int rank = array.get(streamRank, i)
                    array.set(axisValueArray, rank, value)
                    array.set(axisColorArray, rank, array.get(streamColor, i))
                    if tagsOnInput and not na(value)
                        addTagCandidate(value, array.get(streamRank, i), array.get(streamTag, i),
                             array.get(streamColor, i), false)
        if tagsOnInput and not na(sessionVwap)
            addTagCandidate(sessionVwap, RANK_S, "S", sessionColorInput, sessionPartial)
        if tagsOnInput and not na(weekVwap)
            addTagCandidate(weekVwap, RANK_W, "W", weekColorInput, weekPartial)
        int tagCount = array.size(tagValue)
        if tagCount > 0
            for i = 0 to tagCount - 1
                float value = array.get(tagValue, i)
                string base = anchorName(array.get(tagBase, i))
                string hover = (base == "D" ? "Daily session" : base == "W" ? "Week" : base) + " VWAP" + (array.get(tagPartial, i) ? " · first loaded period may be incomplete" : "")
                int rank = array.get(tagRank, i)
                int indent = rank < RANK_S ? swingLabelIndentInput :
                     rank >= RANK_SH and rank < RANK_W ? sweepLabelIndentInput : 0
                int labelX = bar_index + labelOffsetInput + indent
                color lineColor = array.get(tagColor, i)
                if labelGuidesInput and labelX > bar_index
                    placeLabelGuide(guidesUsed, labelX, value, lineColor)
                    guidesUsed += 1
                addTag(labelX, value, array.get(tagPartial, i) ? base + SEP + "partial" : base, lineColor, hover)
 
    while array.size(labelGuides) > guidesUsed
        line.delete(array.pop(labelGuides))
 
    string status = ""
    if not hasVolume
        status := na(lastVolumeBar) ? MSG_NO_VOLUME : MSG_VOLUME_GAP
    else
        if sessionOnInput and sessionTfHidden
            status := MSG_SESSION_HIDDEN
        if weekOnInput and weekTfHidden
            status := status == "" ? MSG_WEEK_HIDDEN : status + SEP + MSG_WEEK_HIDDEN
        if not tagsOnInput
            if not na(sessionVwap) and sessionPartial
                status := status == "" ? "D · partial history" : status + SEP + "D · partial history"
            if not na(weekVwap) and weekPartial
                status := status == "" ? "W · partial history" : status + SEP + "W · partial history"
    if status != ""
        array.push(drawnLabels, label.new(bar_index, high, status, xloc = xloc.bar_index, yloc = yloc.abovebar,
             color = color.new(#787B86, 0), style = label.style_label_down, textcolor = color.white, size = size.small))
 
plot(array.get(axisValueArray, RANK_PH), "Swing H1 VWAP", array.get(axisColorArray, RANK_PH),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PH + 1), "Swing H2 VWAP", array.get(axisColorArray, RANK_PH + 1),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PH + 2), "Swing H3 VWAP", array.get(axisColorArray, RANK_PH + 2),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PH + 3), "Swing H4 VWAP", array.get(axisColorArray, RANK_PH + 3),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PH + 4), "Swing H5 VWAP", array.get(axisColorArray, RANK_PH + 4),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PL), "Swing L1 VWAP", array.get(axisColorArray, RANK_PL),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PL + 1), "Swing L2 VWAP", array.get(axisColorArray, RANK_PL + 1),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PL + 2), "Swing L3 VWAP", array.get(axisColorArray, RANK_PL + 2),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PL + 3), "Swing L4 VWAP", array.get(axisColorArray, RANK_PL + 3),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_PL + 4), "Swing L5 VWAP", array.get(axisColorArray, RANK_PL + 4),
     editable = false, show_last = 1, display = swingsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_SH), "Sweep H1 VWAP", array.get(axisColorArray, RANK_SH),
     editable = false, show_last = 1, display = sweepsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_SH + 1), "Sweep H2 VWAP", array.get(axisColorArray, RANK_SH + 1),
     editable = false, show_last = 1, display = sweepsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_SH + 2), "Sweep H3 VWAP", array.get(axisColorArray, RANK_SH + 2),
     editable = false, show_last = 1, display = sweepsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_SL), "Sweep L1 VWAP", array.get(axisColorArray, RANK_SL),
     editable = false, show_last = 1, display = sweepsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_SL + 1), "Sweep L2 VWAP", array.get(axisColorArray, RANK_SL + 1),
     editable = false, show_last = 1, display = sweepsAxisInput ? display.price_scale : display.none)
plot(array.get(axisValueArray, RANK_SL + 2), "Sweep L3 VWAP", array.get(axisColorArray, RANK_SL + 2),
     editable = false, show_last = 1, display = sweepsAxisInput ? display.price_scale : display.none)

← 返回列表