Anchored VWAP [PickMyTrade]

PickMyTrade_Official · study · 300 行 · 点赞 22 · TradingView 原页

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

Pine Script

//@version=6
indicator("Anchored VWAP [PickMyTrade]", shorttitle="AVWAP PB", overlay=true, behind_chart=true, max_labels_count=500)
 
// Original anchored-VWAP reclaim and first-pullback reference model.
// Three approach closes, first pullback within three bars, 0.25 ATR structural
// buffer, two signal-close R target, minimum 1.5 opening payoff, twelve held bars.
// Candle-close observations only; no strategy orders or broker fill estimates.
string anchorGroup = "VWAP anchor"
string anchorMode = input.string("Auto", "Anchor", options=["Auto", "Exchange session", "Week", "Month", "Year", "Custom date/time", "Tokyo open", "London open", "New York open"], group=anchorGroup, tooltip="Auto uses session VWAP intraday, weekly on daily charts, monthly on weekly charts and yearly on monthly charts. Regional anchors use their first three local hours. Missing volume invalidates an anchor.")
int customStart = input.time(timestamp("01 Jan 2026 00:00 +0000"), "Custom anchor time", group=anchorGroup, tooltip="Custom VWAP starts at the first loaded bar opening at or after this timestamp. The anchor must be observed in loaded history.")
string mechanism = "Pullback fixed"
int slipTicks = input.int(1, "Assumed market / stop slippage (ticks)", minval=0, maxval=20, group="Reference plan", tooltip="Adverse ticks applied to hypothetical market entries and stop/time exits. Next-open eligibility includes this assumption. Targets use the frozen limit price. This is not a broker fill estimate; the indicator does not calculate fees or net profit.")
bool guideShow = input.bool(true, "Show compact guide", group="Chart style", tooltip="Explains VWAP line colors and chart markers, with the latest completed-bar reference state. Conditional setup arrows may be canceled by next-opening checks. Reference observations are not broker fill alerts.")
bool levelsShow = input.bool(false, "Show active reference stop / target", group="Chart style", tooltip="Frozen structural prices for one hypothetical plan. They are conditional references, not advice or live orders. Active plans can survive an anchor reset.")
bool publicationHeading = input.bool(false, "Show publication heading", group="Chart style", tooltip="Adds a large title and a concise legend for presentation. Only appearance changes: VWAP, setups, alerts and reference-plan rules remain identical. Turn off for a compact working chart.")
bool showPlanCaptions = input.bool(true, "Show plan captions", group="Chart style", tooltip="Plain STOP/TARGET captions mark the frozen reference prices on an entry candle. Exit captions identify the completed-bar reference observation, not a broker fill. Appearance only; events and prices are unchanged. Entry bracket captions also require Show active reference stop / target.")
 
color bull = #4285FF
color bear = #FF983A
color ink = #CFD9E9
bool manualMode = anchorMode == "Custom date/time"
bool regionalMode = anchorMode == "Tokyo open" or anchorMode == "London open" or anchorMode == "New York open"
bool timeChart = timeframe.isseconds or timeframe.isminutes or timeframe.isdaily or timeframe.isweekly or timeframe.ismonthly
string automatic = timeframe.isintraday ? "1D" : timeframe.isdaily ? "1W" : timeframe.isweekly ? "1M" : "12M"
string period = switch anchorMode
    "Week" => "1W"
    "Month" => "1M"
    "Year" => "12M"
    "Auto" => automatic
    => "1D"
int periodOpen = time(period)
bool fits = timeChart and (manualMode or (regionalMode ? timeframe.isintraday and timeframe.in_seconds() < 10800 : timeframe.in_seconds() < timeframe.in_seconds(period)))
bool supported = chart.is_standard and fits
string regionalZone = anchorMode == "Tokyo open" ? "Asia/Tokyo" : anchorMode == "London open" ? "Europe/London" : "America/New_York"
int localOpen = timestamp(regionalZone, year(time, regionalZone), month(time, regionalZone), dayofmonth(time, regionalZone), anchorMode == "London open" ? 8 : 9, anchorMode == "New York open" ? 30 : 0)
int localEnd = localOpen + 3 * 60 * 60 * 1000
int weekday = dayofweek(time, regionalZone)
bool weekdayWindow = weekday >= dayofweek.monday and weekday <= dayofweek.friday
bool inWindow = not regionalMode or (weekdayWindow and time >= localOpen and time_close <= localEnd)
bool anchorBegins = if manualMode
    time == customStart or (not barstate.isfirst and time[1] < customStart and time >= customStart)
else if regionalMode
    weekdayWindow and time == localOpen
else
    barstate.isfirst ? time == periodOpen : periodOpen != periodOpen[1]
 
// Production anchored volume-weighted mean. Zero-volume bars add nothing;
// missing/invalid volume invalidates the anchor until its next observed reset.
var bool anchorSeen = false
var bool incomplete = false
var float totalVolume = 0.0
var float meanPrice = na
if anchorBegins
    anchorSeen := true
    incomplete := false
    totalVolume := 0.0
    meanPrice := na
if regionalMode and (not inWindow or (not barstate.isfirst and localOpen != localOpen[1] and not anchorBegins))
    anchorSeen := false
bool collecting = supported and anchorSeen and inWindow
if collecting and (na(volume) or volume < 0 or (volume > 0 and na(hlc3)))
    incomplete := true
bool usable = collecting and not incomplete and not na(volume) and volume > 0
if usable
    totalVolume += volume
    meanPrice := na(meanPrice) ? hlc3 : meanPrice + (hlc3 - meanPrice) * volume / totalVolume
float activeVWAP = usable ? meanPrice : na
float flowATR = ta.atr(14)
bool confirmed = barstate.isconfirmed
 
// First-touch approach state is independent of plan occupancy.
var int closesAbove = 0
var int closesBelow = 0
if anchorBegins or not usable
    closesAbove := 0
    closesBelow := 0
float touchLevel = activeVWAP[1]
bool touched = usable and not anchorBegins and not na(touchLevel) and low <= touchLevel and high >= touchLevel
bool approachedAbove = closesAbove >= 3
bool approachedBelow = closesBelow >= 3
bool consume = touched and (approachedAbove or approachedBelow)
int reversalSide = consume and confirmed ? (approachedAbove and close < touchLevel and close < activeVWAP ? -1 : approachedBelow and close > touchLevel and close > activeVWAP ? 1 : 0) : 0
if consume
    closesAbove := 0
    closesBelow := 0
else if usable
    closesAbove := close > activeVWAP ? math.min(closesAbove + 1, 3) : 0
    closesBelow := close < activeVWAP ? math.min(closesBelow + 1, 3) : 0
 
f_round(float price, bool up) =>
    (up ? math.ceil(price / syminfo.mintick - 1e-9) : math.floor(price / syminfo.mintick + 1e-9)) * syminfo.mintick
f_payoff(int side, float entry, float stop, float target) =>
    float risk = side * (entry - stop)
    float reward = side * (target - entry)
    risk > 0 and reward > 0 ? reward / risk : na
 
// Reclaim acceptance and pullback setup states run independently of occupied
// plans and of the selected mode. No earlier candle is marked retrospectively.
bool pullbackMode = mechanism == "Pullback fixed" or mechanism == "Pullback value exit"
bool valueExitMode = mechanism == "Reclaim value exit" or mechanism == "Pullback value exit"
var int reclaimSide = 0
var float reclaimValue = na
var float reclaimExtreme = na
var int reclaimIndex = na
var int pullbackSide = 0
var float pullbackValue = na
var float pullbackExtreme = na
var int pullbackIndex = na
int acceptanceSide = 0
float acceptanceExtreme = na
float acceptanceValue = na
int pullbackTrigger = 0
float pullbackTriggerExtreme = na
float pullbackTriggerValue = na
if confirmed
    if reclaimSide != 0
        bool accepted = not anchorBegins and usable and bar_index == reclaimIndex + 1 and (reclaimSide == 1 ? low > math.max(reclaimValue, activeVWAP) : high < math.min(reclaimValue, activeVWAP))
        if accepted
            acceptanceSide := reclaimSide
            acceptanceExtreme := reclaimSide == 1 ? math.min(low, reclaimExtreme) : math.max(high, reclaimExtreme)
            acceptanceValue := reclaimValue
        reclaimSide := 0
    if pullbackSide != 0
        int age = bar_index - pullbackIndex
        if anchorBegins or not usable or age > 3
            pullbackSide := 0
        else
            pullbackExtreme := pullbackSide == 1 ? math.min(pullbackExtreme, low) : math.max(pullbackExtreme, high)
            bool touchFrozenValue = low <= pullbackValue and high >= pullbackValue
            bool holdsValue = pullbackSide == 1 ? close > pullbackValue and close > activeVWAP : close < pullbackValue and close < activeVWAP
            if touchFrozenValue
                if holdsValue
                    pullbackTrigger := pullbackSide
                    pullbackTriggerExtreme := pullbackExtreme
                    pullbackTriggerValue := pullbackValue
                // The first touch consumes the setup even when it fails.
                pullbackSide := 0
            else if not holdsValue or age >= 3
                pullbackSide := 0
    if reversalSide != 0
        reclaimSide := reversalSide
        reclaimValue := activeVWAP
        reclaimExtreme := reversalSide == 1 ? low : high
        reclaimIndex := bar_index
        pullbackSide := reversalSide
        pullbackValue := activeVWAP
        pullbackExtreme := reversalSide == 1 ? low : high
        pullbackIndex := bar_index
 
int rawSetupSide = reversalSide
int triggerSide = pullbackMode ? pullbackTrigger : acceptanceSide
float triggerExtreme = pullbackMode ? pullbackTriggerExtreme : acceptanceExtreme
float triggerOriginValue = pullbackMode ? pullbackTriggerValue : acceptanceValue
float draftStop = na
float draftTarget = na
float signalRR = na
int eligibleSide = 0
if confirmed and triggerSide != 0 and not na(flowATR) and flowATR > 0
    draftStop := f_round(triggerExtreme - triggerSide * 0.25 * flowATR, triggerSide == -1)
    float signalRisk = triggerSide * (close - draftStop)
    draftTarget := f_round(close + triggerSide * 2.0 * signalRisk, triggerSide == -1)
    signalRR := f_payoff(triggerSide, close, draftStop, draftTarget)
    if not na(signalRR) and signalRR >= 1.5
        eligibleSide := triggerSide
 
// Confirmed setups queue conditional next-open reference entries. Opening
// eligibility uses only the opening quote, frozen brackets and known calendar.
var int queuedSide = 0
var float queuedStop = na
var float queuedTarget = na
var float queuedOriginValue = na
var int planSide = 0
var float planEntry = na
var float planStop = na
var float planTarget = na
var float planRisk = na
var float planOriginValue = na
var int planEntryIndex = na
var int planEntryTime = na
// 0 none, 3 hard time exit, 4 frozen-value failure; applied at next open.
var int pendingExitCode = 0
int cancelCode = 0
int filledSide = 0
int setupSide = 0
int exitCode = 0
float exitPrice = na
bool timeNotice = false
bool failureNotice = false
bool ambiguous = false
if confirmed
    if queuedSide != 0
        float openingEntry = open + queuedSide * slipTicks * syminfo.mintick
        float openingRR = f_payoff(queuedSide, openingEntry, queuedStop, queuedTarget)
        cancelCode := anchorBegins ? 1 : regionalMode and not inWindow ? 2 : na(openingRR) ? 3 : openingRR < 1.5 ? 4 : 0
        if cancelCode == 0
            planSide := queuedSide
            filledSide := queuedSide
            planEntry := openingEntry
            planStop := queuedStop
            planTarget := queuedTarget
            planRisk := planSide * (planEntry - planStop)
            planOriginValue := queuedOriginValue
            planEntryIndex := bar_index
            planEntryTime := time
            pendingExitCode := 0
        queuedSide := 0
    if planSide != 0
        bool gapStop = planSide * (open - planStop) <= 0
        bool gapTarget = planSide * (open - planTarget) >= 0
        bool stopHit = planSide == 1 ? low <= planStop : high >= planStop
        bool targetHit = planSide == 1 ? high >= planTarget : low <= planTarget
        if gapStop
            exitCode := 1
            exitPrice := open - planSide * slipTicks * syminfo.mintick
        else if gapTarget
            exitCode := 2
            exitPrice := planTarget
        else if pendingExitCode != 0
            exitCode := pendingExitCode
            exitPrice := open - planSide * slipTicks * syminfo.mintick
        else if stopHit
            exitCode := 1
            exitPrice := planStop - planSide * slipTicks * syminfo.mintick
            ambiguous := targetHit
        else if targetHit
            exitCode := 2
            exitPrice := planTarget
        if exitCode != 0
            planSide := 0
            pendingExitCode := 0
        else if bar_index - planEntryIndex + 1 >= 12
            pendingExitCode := 3
            timeNotice := true
        else if valueExitMode and (planSide == 1 ? close <= planOriginValue : close >= planOriginValue)
            pendingExitCode := 4
            failureNotice := true
    if eligibleSide != 0 and planSide == 0
        queuedSide := eligibleSide
        queuedStop := draftStop
        queuedTarget := draftTarget
        queuedOriginValue := triggerOriginValue
        setupSide := eligibleSide
 
// Actual VWAP line: completed-candle position changes color only.
var int flowSide = 0
if not usable
    flowSide := 0
else if confirmed
    flowSide := low > activeVWAP ? 1 : high < activeVWAP ? -1 : 0
color flowColor = flowSide == 1 ? #246BFF : flowSide == -1 ? #FF8A18 : #CFD9E9
plot(activeVWAP, "VWAP", color=flowColor, linewidth=3, style=plot.style_linebr)
plotshape(setupSide == 1, "Conditional long setup", shape.triangleup, location.belowbar, bull, text="PULLBACK", textcolor=ink, size=size.small, display=display.pane)
plotshape(setupSide == -1, "Conditional short setup", shape.triangledown, location.abovebar, bear, text="PULLBACK", textcolor=ink, size=size.small, display=display.pane)
plotshape(filledSide == 1 ? planEntry : na, "Long reference entry", shape.circle, location.absolute, bull, size=size.tiny, display=display.pane)
plotshape(filledSide == -1 ? planEntry : na, "Short reference entry", shape.circle, location.absolute, bear, size=size.tiny, display=display.pane)
plotshape(cancelCode != 0, "Setup canceled at next open", shape.xcross, location.abovebar, ink, text="CXL", textcolor=ink, size=size.tiny, display=display.pane)
plotshape(timeNotice, "Time exit notice for next open", shape.xcross, location.abovebar, ink, text="TIME", textcolor=ink, size=size.tiny, display=display.pane)
plotshape(exitCode != 0 ? exitPrice : na, "Completed reference exit", shape.xcross, location.absolute, ink, size=size.tiny, display=display.pane)
plot(levelsShow and planSide != 0 ? planStop : na, "Active reference stop", color=color.new(bear, 25), style=plot.style_linebr, display=display.pane)
plot(levelsShow and planSide != 0 ? planTarget : na, "Active reference target", color=color.new(bull, 25), style=plot.style_linebr, display=display.pane)
alertcondition(setupSide == 1, "Conditional long setup", "VWAP Pullback: long setup confirmed. Reference entry is conditional at the next opening quote; frozen geometry, payoff or calendar checks can cancel it. This is not a broker entry or fill.")
alertcondition(setupSide == -1, "Conditional short setup", "VWAP Pullback: short setup confirmed. Reference entry is conditional at the next opening quote; frozen geometry, payoff or calendar checks can cancel it. This is not a broker entry or fill.")
 
alertcondition(timeNotice, "Twelve-bar time notice", "VWAP Pullback: twelve held candles completed. Reference exit is queued for the next available open; this is not a broker fill confirmation.")
 
alertcondition(cancelCode != 0, "Conditional setup canceled", "VWAP Pullback: next-opening checks canceled a pending reference setup. This is a completed-bar model observation, not a broker order cancellation.")
alertcondition(exitCode != 0, "Completed reference exit", "VWAP Pullback: a hypothetical stop, target or time exit was observed during the completed candle. This bar-close observation does not confirm a broker fill or execute an intrabar exit.")
 
// Plain captions explain existing reference events without changing them.
if confirmed and showPlanCaptions
    if filledSide != 0 and levelsShow
        label.new(bar_index, planStop, "STOP", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=bear, size=size.small, textalign=text.align_left)
        label.new(bar_index, planTarget, "TARGET", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=bull, size=size.small, textalign=text.align_left)
    if exitCode != 0
        string exitCaption = exitCode == 1 ? "STOP" : exitCode == 2 ? "TARGET" : exitCode == 3 ? "TIME EXIT" : "EXIT"
        label.new(bar_index, exitPrice + flowATR * 0.85, exitCaption, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=ink, size=size.small, textalign=text.align_left)
 
var string lastState = "Waiting for a closed-bar setup"
if confirmed
    lastState := setupSide != 0 ? (setupSide == 1 ? "Long SETUP" : "Short SETUP") + " · next open is conditional" : cancelCode != 0 ? "CXL · next-open reference entry rejected" : timeNotice ? "TIME · reference exit at next available open" : failureNotice ? "FAIL · frozen reclaim value lost; next-open reference exit" : exitCode != 0 ? "Reference exit observed · no broker fill" : planSide != 0 ? "Reference plan active · stop / target frozen" : "Waiting for a closed-bar setup"
// Viewport-anchored presentation; no dependency flows back into calculation.
var table heading = table.new(position.top_center, 1, 3, bgcolor=color.new(#0B111C, 100), border_width=0)
var table guide = table.new(position.bottom_center, 1, 3, bgcolor=color.new(#101C2D, 8), border_width=0)
if barstate.islast
    if publicationHeading
        table.cell(heading, 0, 0, "", height=3, bgcolor=color.new(#0B111C, 100))
        table.cell(heading, 0, 1, "ANCHORED VWAP", text_color=#E9EEF7, text_size=44, bgcolor=color.new(#0B111C, 100))
        table.cell(heading, 0, 2, "Reclaim · First pullback · Timed exits", text_color=#9CAEC4, text_size=15, bgcolor=color.new(#0B111C, 100))
    else
        table.clear(heading, 0, 0, 0, 2)
    if guideShow
        table.set_bgcolor(guide, color.new(#101C2D, publicationHeading ? 100 : 8))
        table.cell(guide, 0, 0, "BLUE · VWAP below candle    ORANGE · VWAP above candle    WHITE · touch / cross", text_color=ink, text_size=size.small)
        table.cell(guide, 0, 1, publicationHeading ? "PULLBACK · conditional setup   |   STOP / TARGET / TIME EXIT · reference observations" : supported ? lastState : "Unsupported chart or anchor interval", text_color=#9CAEC4, text_size=size.small)
        if publicationHeading
            table.clear(guide, 0, 2, 0, 2)
        else
            table.cell(guide, 0, 2, "Triangle = conditional setup · Dot = reference entry · X = exit / cancellation  |  Anchor: " + anchorMode, text_color=#9CAEC4, text_size=size.tiny)
    else
        table.clear(guide, 0, 0, 0, 2)

← 返回列表