AVWAP Multi-Day Overextension

germanikns · study · 200 行 · 点赞 4 · TradingView 原页

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

Pine Script

//@version=6
// AVWAP-OX v1 — Multi-day overextension from an Anchored VWAP
// Anchor = 9:30 ET regular open of the session N trading sessions back (0 = today).
// Accumulates regular-session bars only (pre/post-market ignored).
// D_AVWAP = (P − AVWAP) / AVWAP × 100
// Z_AVWAP = (P − AVWAP) / σ, σ = volume-weighted std dev of price around AVWAP since the anchor
// Tiers (starting points to test, descriptive only): ±1σ moderate, ±2σ significant, ±3σ extreme
indicator("AVWAP Multi-Day Overextension", shorttitle = "AVWAP-OX", overlay = false)
 
// ───────────────────────── Constants
TZ  = "America/New_York"
DAY = 86400000
 
// ───────────────────────── Inputs
grpA     = "Anchor"
daysBack = input.int(5, "Days back (trading sessions, 0 = today)", minval = 0, maxval = 250, group = grpA,
     tooltip = "Counted back from the session of the last bar on the chart. 0 = today's 9:30 ET open, 1 = yesterday's open, etc. Weekends and NYSE holidays (2024–2027) are skipped. If the last bar is pre-market, 'today' is the previous session.")
src      = input.source(hlc3, "Price source for AVWAP / σ", group = grpA)
 
grpT = "Overextension tiers (σ from AVWAP)"
t1   = input.float(1.0, "Moderate ±",    minval = 0.1, step = 0.1, group = grpT)
t2   = input.float(2.0, "Significant ±", minval = 0.1, step = 0.1, group = grpT)
t3   = input.float(3.0, "Extreme ±",     minval = 0.1, step = 0.1, group = grpT)
 
grpS    = "Signals"
warmMin = input.int(30, "Warm-up after anchor (minutes)", options = [0, 15, 30, 60], group = grpS,
     tooltip = "σ is unstable right after the anchor. No EXH or tier alerts until this much time has passed. Ignored on D/W/M charts.")
exhArm  = input.float(3.0, "EXH arms at |z| ≥", minval = 0.1, step = 0.1, group = grpS,
     tooltip = "EXH fires when the prior bar closed at or beyond this z and the current bar closes back toward AVWAP with a counter-colour candle. One EXH per excursion; re-arms once |z| falls back below the Significant tier.")
showExh = input.bool(true, "Show EXH markers on price", group = grpS)
 
grpD      = "Display"
showAV    = input.bool(true, "AVWAP on price chart", group = grpD)
showB1    = input.bool(true, "±1σ bands", group = grpD)
showB2    = input.bool(true, "±2σ bands", group = grpD)
showB3    = input.bool(true, "±3σ bands", group = grpD)
showTable = input.bool(true, "Status table", group = grpD)
 
// ───────────────────────── Colours
colAV = #AB47BC
colN  = color.new(color.gray, 45)
colU1 = #FFB74D
colU2 = #FF7043
colU3 = #E53935
colD1 = #80CBC4
colD2 = #26A69A
colD3 = #00796B
 
// ───────────────────────── NYSE full-day closures 2024–2027 (YYYYMMDD)
var array<int> HOLIDAYS = array.from(
     20240101, 20240115, 20240219, 20240329, 20240527, 20240619, 20240704, 20240902, 20241128, 20241225,
     20250101, 20250109, 20250120, 20250217, 20250418, 20250526, 20250619, 20250704, 20250901, 20251127, 20251225,
     20260101, 20260119, 20260216, 20260403, 20260525, 20260619, 20260703, 20260907, 20261126, 20261225,
     20270101, 20270118, 20270215, 20270326, 20270531, 20270618, 20270705, 20270906, 20271125, 20271224)
 
// ───────────────────────── Helpers
f_ymd(int t, string tz) =>
    year(t, tz) * 10000 + month(t, tz) * 100 + dayofmonth(t, tz)
 
f_isTradingDay(int t) =>
    dow = dayofweek(t, TZ)
    dow != dayofweek.saturday and dow != dayofweek.sunday and not array.includes(HOLIDAYS, f_ymd(t, TZ))
 
// ───────────────────────── Anchor date (computed once, relative to the last bar on the chart)
var int anchorYMD = 0
if barstate.isfirst
    lb = last_bar_time
    int t = timestamp(TZ, year(lb, TZ), month(lb, TZ), dayofmonth(lb, TZ), 12, 0)   // noon avoids DST edges
    beforeOpen = timeframe.isintraday and (hour(lb, TZ) * 60 + minute(lb, TZ)) < 570
    if beforeOpen
        t -= DAY
    while not f_isTradingDay(t)
        t -= DAY
    int n = 0
    while n < daysBack
        t -= DAY
        if f_isTradingDay(t)
            n += 1
    anchorYMD := f_ymd(t, TZ)
 
// ───────────────────────── Accumulation from the anchor (regular session only)
barYMD   = f_ymd(time_tradingday, "UTC")
isRTH    = timeframe.isdwm or not na(time(timeframe.period, "0930-1600", TZ))
inAnchor = barYMD >= anchorYMD and isRTH
 
var float sV          = 0.0
var float sPV         = 0.0
var float sP2V        = 0.0
var int   anchorTime  = na
var int   anchorBarYMD = 0
var int   sessCount   = 0
var int   lastRTHymd  = 0
 
if inAnchor
    if na(anchorTime)
        anchorTime   := time
        anchorBarYMD := barYMD
    if barYMD != lastRTHymd
        sessCount  += 1
        lastRTHymd := barYMD
    v = nz(volume)
    sV   += v
    sPV  += src * v
    sP2V += src * src * v
 
started = not na(anchorTime) and sV > 0
float avwap = started ? sPV / sV : na
float sd    = started ? math.sqrt(math.max(sP2V / sV - avwap * avwap, 0.0)) : na
float z     = started and isRTH and sd > 0 ? (close - avwap) / sd : na
float dPct  = started ? (close - avwap) / avwap * 100 : na
 
warmDone = started and (timeframe.isdwm or time - anchorTime >= warmMin * 60000)
ready    = warmDone and not na(z)
 
// ───────────────────────── Tiers
az = math.abs(z)
int tier = na(z) ? 0 : az >= t3 ? 3 : az >= t2 ? 2 : az >= t1 ? 1 : 0
 
color zCol = na(z) ? na :
     not warmDone ? color.new(color.gray, 70) :
     z >= 0 ? (tier == 3 ? colU3 : tier == 2 ? colU2 : tier == 1 ? colU1 : colN) :
              (tier == 3 ? colD3 : tier == 2 ? colD2 : tier == 1 ? colD1 : colN)
 
// ───────────────────────── EXH (exhaustion) — one per excursion
var bool firedUp = false
var bool firedDn = false
if not na(z) and z < t2
    firedUp := false
if not na(z) and z > -t2
    firedDn := false
 
zPrev = z[1]
exhUp = ready and not firedUp and not na(zPrev) and zPrev >= exhArm  and z < zPrev and close < open
exhDn = ready and not firedDn and not na(zPrev) and zPrev <= -exhArm and z > zPrev and close > open
if exhUp
    firedUp := true
if exhDn
    firedDn := true
 
// Tier crossings (computed every bar)
xUp2 = ta.crossover(z, t2)
xUp3 = ta.crossover(z, t3)
xDn2 = ta.crossunder(z, -t2)
xDn3 = ta.crossunder(z, -t3)
 
// ───────────────────────── Pane: z-score
plot(z, "Z (AVWAP)", zCol, style = plot.style_columns)
hline(0,   "0",              color.new(color.gray, 40), hline.style_solid)
hline(t1,  "+Moderate",      color.new(colU1, 50), hline.style_dotted)
hline(-t1, "-Moderate",      color.new(colD1, 50), hline.style_dotted)
hline(t2,  "+Significant",   color.new(colU2, 40), hline.style_dashed)
hline(-t2, "-Significant",   color.new(colD2, 40), hline.style_dashed)
hline(t3,  "+Extreme",       color.new(colU3, 30), hline.style_solid)
hline(-t3, "-Extreme",       color.new(colD3, 30), hline.style_solid)
plot(dPct, "D% from AVWAP", display = display.data_window)
plot(sd,   "σ (price)",     display = display.data_window)
 
// ───────────────────────── Price chart: AVWAP + bands
plot(showAV ? avwap : na,            "AVWAP", colAV, 2, force_overlay = true)
plot(showB1 ? avwap + t1 * sd : na,  "+1σ", color.new(colU1, 30), 1, force_overlay = true)
plot(showB1 ? avwap - t1 * sd : na,  "-1σ", color.new(colD1, 30), 1, force_overlay = true)
plot(showB2 ? avwap + t2 * sd : na,  "+2σ", color.new(colU2, 20), 1, force_overlay = true)
plot(showB2 ? avwap - t2 * sd : na,  "-2σ", color.new(colD2, 20), 1, force_overlay = true)
plot(showB3 ? avwap + t3 * sd : na,  "+3σ", color.new(colU3, 10), 2, force_overlay = true)
plot(showB3 ? avwap - t3 * sd : na,  "-3σ", color.new(colD3, 10), 2, force_overlay = true)
 
plotshape(showExh and exhUp, "EXH up",   shape.triangledown, location.abovebar, colU3, text = "EXH", textcolor = colU3, size = size.small, force_overlay = true)
plotshape(showExh and exhDn, "EXH down", shape.triangleup,   location.belowbar, colD3, text = "EXH", textcolor = colD3, size = size.small, force_overlay = true)
 
// ───────────────────────── Alerts (set "Once Per Bar Close" and pick a sound in the alert dialog)
alertcondition(exhUp, "AVWAP-OX: EXH upside",   "{{ticker}} AVWAP-OX upside EXH — stretched above AVWAP, momentum fading")
alertcondition(exhDn, "AVWAP-OX: EXH downside", "{{ticker}} AVWAP-OX downside EXH — stretched below AVWAP, momentum fading")
alertcondition(ready and (xUp2 or xDn2), "AVWAP-OX: Significant tier", "{{ticker}} AVWAP-OX crossed into the ±Significant σ tier")
alertcondition(ready and (xUp3 or xDn3), "AVWAP-OX: Extreme tier",     "{{ticker}} AVWAP-OX crossed into the ±Extreme σ tier")
 
// ───────────────────────── Status table
var table tb = table.new(position.top_right, 2, 6, bgcolor = color.new(color.black, 80), border_width = 1)
if barstate.islast and showTable
    found = sessCount - 1
    string status = na(anchorTime) ? "⚠ Anchor not on chart — load more history or lower Days back" :
         anchorBarYMD != anchorYMD ? "⚠ Chart data starts after anchor date" :
         found != daysBack ? "⚠ Found " + str.tostring(found) + " sessions back — holiday/data gap?" :
         "✓ OK"
    color stCol = str.startswith(status, "✓") ? color.new(color.green, 0) : color.new(color.orange, 0)
    string anchorTxt = na(anchorTime) ? str.tostring(anchorYMD) : str.format_time(anchorTime, "EEE yyyy-MM-dd HH:mm", TZ) + " ET"
    string zTxt = na(z) ? "—" : str.tostring(z, "#.##") + "σ"
    string dTxt = na(dPct) ? "—" : str.tostring(dPct, "#.##") + "%"
    string avTxt = na(avwap) ? "—" : str.tostring(avwap, format.mintick)
    table.cell(tb, 0, 0, "Anchor",        text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 0, anchorTxt,       text_color = color.white,  text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 1, "Sessions back", text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 1, str.tostring(daysBack), text_color = color.white, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 2, "AVWAP",         text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 2, avTxt,           text_color = colAV,        text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 3, "Z",             text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 3, zTxt,            text_color = na(zCol) ? color.white : zCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 4, "D%",            text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 4, dTxt,            text_color = color.white,  text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 5, "Status",        text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 5, status,          text_color = stCol,        text_size = size.small, text_halign = text.align_left)

← 返回列表