Eye Smart VWAP [EyeAlgo]

eyealgo · study · 728 行 · 点赞 231 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EyeAlgo
//@version=6
indicator("Eye Smart VWAP [EyeAlgo]", "Eye Smart VWAP", overlay=true, max_lines_count=500, max_labels_count=500, max_polylines_count=100, max_bars_back=5000)
 
// ═════════════════════════ INPUTS ═════════════════════════
grpP = "Quick setup"
preset = input.string("Auto by timeframe", "Preset", options=["Auto by timeframe", "Scalp (1-5m)", "Intraday (15m-1H)", "Swing (2H-1D)", "Custom (use inputs below)"], group=grpP, tooltip="Auto by timeframe picks swing length, gap between anchors and retest distance for your chart timeframe. Choose Custom to use your own values below.")
 
grpA = "Smart VWAP (auto anchor)"
anchorMode = input.string("Structure break + Liquidity sweep", "Anchor on", options=["Structure break + Liquidity sweep", "Structure break", "Liquidity sweep", "Every confirmed swing", "Highest volume bar", "Origin of N-bar range"], group=grpA, tooltip="Structure break: when price closes beyond the last swing, the VWAP is anchored at the start of that move.\nLiquidity sweep: when a wick runs a swing level and closes back, the VWAP is anchored on that candle.")
swingLen   = input.int(10, "Swing length", minval=2, maxval=50, group=grpA)
minGap     = input.int(10, "Min bars between anchors", minval=1, group=grpA)
sweepAtr   = input.float(0.25, "Sweep min wick beyond level (× ATR)", minval=0.0, step=0.05, group=grpA)
volLook    = input.int(50, "Highest volume bar lookback", minval=5, maxval=2000, group=grpA, tooltip="On symbols without volume this becomes the largest-range bar.")
nBar       = input.int(50, "N-bar range length", minval=5, maxval=1000, group=grpA)
srcIn      = input.source(hlc3, "Price source", group=grpA, tooltip="hlc3 matches TradingView's built-in VWAP / Anchored VWAP.")
wMode      = input.string("Auto", "Weighting", options=["Auto", "Volume", "Range"], group=grpA, tooltip="Auto = real volume; if the symbol gives no volume it uses candle range, so lines and bands never go blank.")
 
grpB = "Smart VWAP bands"
m1 = input.float(1.0, "Band 1 (σ)", minval=0.1, step=0.1, inline="m", group=grpB)
m2 = input.float(2.0, "Band 2 (σ)", minval=0.1, step=0.1, inline="m", group=grpB)
m3 = input.float(3.0, "Band 3 (σ)", minval=0.1, step=0.1, inline="m", group=grpB)
showB1     = input.bool(true,  "Show band 1", group=grpB)
showB2     = input.bool(true,  "Show band 2", group=grpB)
showB3     = input.bool(false, "Show band 3", group=grpB)
showFill   = input.bool(true,  "Fill inside band 2", group=grpB)
barCol     = input.bool(false, "Color candles by band zone", group=grpB)
keepSeg    = input.int(4, "Past Smart VWAPs kept on chart", minval=0, maxval=30, group=grpB)
showMem    = input.bool(true,  "Memory VWAP (previous anchor keeps running)", group=grpB)
showAnchor = input.bool(true,  "Anchor marks", group=grpB)
lblGap     = input.float(0.6, "Right label spacing (× ATR)", minval=0.1, step=0.1, group=grpB, tooltip="Minimum gap between the line names at the right edge, so they never overlap.")
 
grpC = "Period VWAPs"
showD   = input.bool(true,  "Daily VWAP", group=grpC)
showDB  = input.bool(false, "Daily VWAP bands (band 1 / band 2)", group=grpC)
showPD  = input.bool(true,  "Previous Day VWAP", group=grpC)
showW   = input.bool(true,  "Weekly VWAP", group=grpC)
showWB  = input.bool(false, "Weekly VWAP bands (band 1 / band 2)", group=grpC)
showPW  = input.bool(false, "Previous Week VWAP", group=grpC)
showM   = input.bool(false, "Monthly VWAP", group=grpC)
showMD  = input.bool(false, "Multi-day VWAP (rolling: today + previous N-1 days)", group=grpC)
mdDays  = input.int(2, "Multi-day VWAP days", minval=2, maxval=5, group=grpC)
showS   = input.bool(false, "Session VWAP (Asia / London / New York)", group=grpC)
showCS  = input.bool(false, "Custom session VWAP (e.g. RTH)", group=grpC)
csSess  = input.session("1330-2000", "Custom session window", group=grpC, tooltip="Resets at the start of this window, in the timezone set below. Example: US cash session 09:30-16:00 New York = 13:30-20:00 UTC (summer).")
 
grpS = "Sessions (Session VWAP + stats)"
tz    = input.string("Etc/UTC", "Timezone", group=grpS, tooltip="Session times below are read in this timezone. Keep Etc/UTC unless you want to type times in your own zone (e.g. Asia/Kolkata, America/New_York).")
sAsia = input.session("0000-0700", "Asia", group=grpS)
sLon  = input.session("0700-1230", "London", group=grpS)
sNy   = input.session("1230-2100", "New York", group=grpS)
 
grpT = "Retest setups"
showSig    = input.bool(true, "Show retest setups", group=grpT)
needAway   = input.float(1.5, "Price first moves away from VWAP (σ)", minval=0.2, step=0.1, group=grpT)
awayBars   = input.int(30, "…within last N bars", minval=3, group=grpT)
touchTol   = input.float(0.25, "Retest zone around VWAP (σ)", minval=0.0, step=0.05, group=grpT)
useDaily   = input.bool(true, "Filter: same side of Daily VWAP", group=grpT)
useEma     = input.bool(false, "Filter: EMA trend", inline="ema", group=grpT)
emaLen     = input.int(200, "", minval=5, inline="ema", group=grpT)
showEma    = input.bool(false, "Show EMA line", group=grpT)
useWeekly  = input.bool(true, "Filter: same side of Weekly VWAP", group=grpT)
useSlope   = input.bool(true, "Filter: Smart VWAP sloping with the trade", group=grpT)
maxRet     = input.int(1, "Max retests per anchor (0 = no limit)", minval=0, group=grpT)
slSig      = input.float(1.0, "Stop beyond VWAP (σ)", minval=0.2, step=0.1, group=grpT)
minSlAtr   = input.float(0.5, "Min stop (× ATR)", minval=0.1, step=0.1, group=grpT)
tp1R       = input.float(1.0, "TP1 (R)", minval=0.2, step=0.1, group=grpT)
tp2R       = input.float(2.0, "TP2 (R)", minval=0.5, step=0.1, group=grpT)
maxHold    = input.int(60, "Max bars in trade", minval=5, group=grpT)
keepTrades = input.int(8, "Trade plans kept on chart", minval=1, maxval=60, group=grpT)
 
grpD = "Dashboard"
showTbl  = input.bool(true, "Show dashboard", group=grpD)
tblPos   = input.string("Bottom Left", "Position", options=["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group=grpD)
tblSize  = input.string("Small", "Text size", options=["Tiny", "Small", "Normal"], group=grpD)
statBars = input.int(30, "Band 2 touch result window (bars)", minval=5, group=grpD)
 
grpK = "Colors"
cBull  = input.color(#089981, "Smart VWAP bullish", group=grpK)
cBear  = input.color(#F23645, "Smart VWAP bearish", group=grpK)
cBand  = input.color(#787B86, "Bands", group=grpK)
cDay   = input.color(#7E57C2, "Daily VWAP", group=grpK)
cWeek  = input.color(#FF9800, "Weekly VWAP", group=grpK)
cMonth = input.color(#2962FF, "Monthly VWAP", group=grpK)
cSess  = input.color(#00ACC1, "Session VWAP", group=grpK)
 
// ═════════════════════════ PRESET ═════════════════════════
int tfSec = timeframe.in_seconds()
string pr = preset == "Auto by timeframe" ? (tfSec <= 300 ? "Scalp (1-5m)" : tfSec <= 3600 ? "Intraday (15m-1H)" : "Swing (2H-1D)") : preset
int   sLen  = pr == "Scalp (1-5m)" ? 6 : pr == "Intraday (15m-1H)" ? 10 : pr == "Swing (2H-1D)" ? 8 : swingLen
int   gapN  = pr == "Scalp (1-5m)" ? 8 : pr == "Intraday (15m-1H)" ? 10 : pr == "Swing (2H-1D)" ? 6 : minGap
float awayN = pr == "Scalp (1-5m)" ? 2.0 : pr == "Intraday (15m-1H)" ? 1.5 : pr == "Swing (2H-1D)" ? 1.5 : needAway
 
// ═════════════════════════ CORE ═════════════════════════
int MAXPTS = 3000
float atr  = ta.atr(14)
float src  = srcIn
float rng  = high - low
bool  hasVol = ta.cum(nz(volume)) > 0
float w    = switch wMode
    "Volume" => nz(volume)
    "Range"  => rng
    => hasVol ? nz(volume) : rng
w := math.max(w, 1e-10)
 
// period VWAP with own variance (weighted)
f_cum(bool reset) =>
    var float sw  = 0.0
    var float sp  = 0.0
    var float sp2 = 0.0
    if reset
        sw  := 0.0
        sp  := 0.0
        sp2 := 0.0
    sw  += w
    sp  += w * src
    sp2 += w * src * src
    float v = sp / sw
    [v, math.sqrt(math.max(sp2 / sw - v * v, 0.0))]
 
bool newD = timeframe.change("D")
bool newW = timeframe.change("W")
bool newM = timeframe.change("M")
[dV, dSD] = f_cum(newD)
[wV, wSD] = f_cum(newW)
[mV, mSDu] = f_cum(newM)
 
bool inA = not na(time(timeframe.period, sAsia, tz))
bool inL = not na(time(timeframe.period, sLon, tz))
bool inN = not na(time(timeframe.period, sNy, tz))
int sessId = not timeframe.isintraday ? 0 : inN ? 3 : inL ? 2 : inA ? 1 : 0
bool newS = sessId != nz(sessId[1], -1) and sessId != 0
[sV, sSD] = f_cum(newS)
 
bool inCS = not na(time(timeframe.period, csSess, tz))
bool newCS = inCS and not inCS[1]
[csV, csSD] = f_cum(newCS)
 
// multi-day VWAP: completed day sums + today
var array<float> dSw = array.new<float>()
var array<float> dSp = array.new<float>()
var float tdW = 0.0
var float tdP = 0.0
if newD
    if tdW > 0
        dSw.push(tdW)
        dSp.push(tdP)
        if dSw.size() > 5
            dSw.shift()
            dSp.shift()
    tdW := 0.0
    tdP := 0.0
tdW += w
tdP += w * src
float mdW = tdW
float mdP = tdP
int nPrev = math.min(mdDays - 1, dSw.size())
if nPrev > 0
    for i = 1 to nPrev
        mdW += dSw.get(dSw.size() - i)
        mdP += dSp.get(dSp.size() - i)
float mdV = nPrev == mdDays - 1 ? mdP / mdW : na
float emaV = ta.ema(close, emaLen)
 
var float pdV = na
var float pwV = na
if newD
    pdV := dV[1]
if newW
    pwV := wV[1]
 
// value migration (daily VWAP closes)
var array<float> dayClose = array.new<float>()
if newD and not na(dV[1])
    dayClose.push(dV[1])
    if dayClose.size() > 5
        dayClose.shift()
 
// ═════════════════════════ SWINGS & ANCHOR EVENTS ═════════════════════════
float ph = ta.pivothigh(high, sLen, sLen)
float pl = ta.pivotlow(low, sLen, sLen)
var float shP = na
var int   shB = na
var bool  shUsed = true
var float slP = na
var int   slB = na
var bool  slUsed = true
if not na(ph)
    shP := ph
    shB := bar_index - sLen
    shUsed := false
if not na(pl)
    slP := pl
    slB := bar_index - sLen
    slUsed := false
 
bool conf  = barstate.isconfirmed
bool bosUp = conf and not na(shP) and not shUsed and close > shP
bool bosDn = conf and not na(slP) and not slUsed and close < slP
bool swpBu = conf and not na(slP) and not slUsed and low < slP and close > slP and (slP - low) >= sweepAtr * atr
bool swpBe = conf and not na(shP) and not shUsed and high > shP and close < shP and (high - shP) >= sweepAtr * atr
if bosUp or swpBe
    shUsed := true
if bosDn or swpBu
    slUsed := true
 
bool useBOS   = anchorMode == "Structure break + Liquidity sweep" or anchorMode == "Structure break"
bool useSweep = anchorMode == "Structure break + Liquidity sweep" or anchorMode == "Liquidity sweep"
bool useSwing = anchorMode == "Every confirmed swing"
bool useVolA  = anchorMode == "Highest volume bar"
bool useNBar  = anchorMode == "Origin of N-bar range"
bool volTop   = w >= ta.highest(w, volLook)
int  hiOff    = -ta.highestbars(high, nBar)
int  loOff    = -ta.lowestbars(low, nBar)
int  orgBar   = loOff > hiOff ? bar_index - loOff : bar_index - hiOff
int  orgDir   = loOff > hiOff ? 1 : -1
 
var int aBar = na
var int lastEvt = na
bool canAnchor = conf and (na(lastEvt) or bar_index - lastEvt >= gapN)
 
int    evBar = na
int    evDir = 0
string evWhy = ""
if canAnchor
    if useBOS and bosUp
        int lb = math.min(bar_index - shB, 300)
        int idx = 0
        float lo = low
        for i = 0 to lb
            if low[i] < lo
                lo  := low[i]
                idx := i
        evBar := bar_index - idx
        evDir := 1
        evWhy := "Structure break ▲"
    else if useBOS and bosDn
        int lb = math.min(bar_index - slB, 300)
        int idx = 0
        float hi = high
        for i = 0 to lb
            if high[i] > hi
                hi  := high[i]
                idx := i
        evBar := bar_index - idx
        evDir := -1
        evWhy := "Structure break ▼"
    else if useSweep and swpBu
        evBar := bar_index
        evDir := 1
        evWhy := "Liquidity sweep ▲"
    else if useSweep and swpBe
        evBar := bar_index
        evDir := -1
        evWhy := "Liquidity sweep ▼"
    else if useSwing and not na(pl)
        evBar := bar_index - sLen
        evDir := 1
        evWhy := "Swing low ▲"
    else if useSwing and not na(ph)
        evBar := bar_index - sLen
        evDir := -1
        evWhy := "Swing high ▼"
    else if useVolA and volTop
        evBar := bar_index
        evDir := close >= open ? 1 : -1
        evWhy := close >= open ? "Highest volume bar ▲" : "Highest volume bar ▼"
    else if useNBar and (na(aBar) or orgBar != aBar)
        evBar := orgBar
        evDir := orgDir
        evWhy := orgDir == 1 ? "N-bar range low ▲" : "N-bar range high ▼"
 
// ═════════════════════════ SMART VWAP STATE ═════════════════════════
var float  aW = 0.0
var float  aP = 0.0
var float  aP2 = 0.0
var int    aDir = 0
var string aWhy = "waiting for first anchor"
var array<int>   segX = array.new<int>()
var array<float> segV = array.new<float>()
var array<float> segS = array.new<float>()
 
var bool  mOn = false
var int   mDir = 0
var float mW = 0.0
var float mP = 0.0
var float mP2 = 0.0
var array<int>   memX = array.new<int>()
var array<float> memV = array.new<float>()
 
var array<polyline> frozen = array.new<polyline>()
var array<label>    anchorLbls = array.new<label>()
 
f_pts(array<int> xs, array<float> vs, array<float> ss, float k) =>
    array<chart.point> pts = array.new<chart.point>()
    int n = xs.size()
    int lim = bar_index - 4900
    if n > 0
        for i = 0 to n - 1
            int x = xs.get(i)
            if x >= lim
                pts.push(chart.point.from_index(x, vs.get(i) + k * ss.get(i)))
    pts
 
f_fill(array<int> xs, array<float> vs, array<float> ss, float k) =>
    array<chart.point> pts = array.new<chart.point>()
    int n = xs.size()
    int lim = bar_index - 4900
    if n > 1
        for i = 0 to n - 1
            int x = xs.get(i)
            if x >= lim
                pts.push(chart.point.from_index(x, vs.get(i) + k * ss.get(i)))
        for i = n - 1 to 0
            int x = xs.get(i)
            if x >= lim
                pts.push(chart.point.from_index(x, vs.get(i) - k * ss.get(i)))
    pts
 
f_push(array<int> xs, array<float> vs, array<float> ss, int x, float v, float s) =>
    xs.push(x)
    vs.push(v)
    ss.push(s)
    if xs.size() > MAXPTS
        xs.shift()
        vs.shift()
        ss.shift()
 
bool newAnchor = not na(evBar)
if newAnchor
    // freeze the running Smart VWAP as a faded past line
    if keepSeg > 0 and segX.size() > 1
        color fc = aDir == 1 ? cBull : cBear
        frozen.push(polyline.new(f_pts(segX, segV, segS, 0.0), line_color=color.new(fc, 45), line_width=1))
        while frozen.size() > keepSeg
            frozen.shift().delete()
    // memory VWAP = old anchor keeps running
    if aW > 0
        mOn := true
        mDir := aDir
        mW := aW
        mP := aP
        mP2 := aP2
        memX.clear()
        memV.clear()
    // re-anchor and rebuild from the anchor bar (anchor bar is in the past = known origin)
    aW := 0.0
    aP := 0.0
    aP2 := 0.0
    segX.clear()
    segV.clear()
    segS.clear()
    int n = bar_index - evBar
    for i = n to 0
        aW  += w[i]
        aP  += w[i] * src[i]
        aP2 += w[i] * src[i] * src[i]
        float v = aP / aW
        f_push(segX, segV, segS, bar_index - i, v, math.sqrt(math.max(aP2 / aW - v * v, 0.0)))
    aBar := evBar
    lastEvt := bar_index
    aDir := evDir
    aWhy := evWhy
    if showAnchor
        bool up = evDir == 1
        anchorLbls.push(label.new(evBar, up ? low[n] : high[n], up ? "▲" : "▼", style=up ? label.style_label_up : label.style_label_down, yloc=up ? yloc.belowbar : yloc.abovebar, color=color(na), textcolor=color.new(up ? cBull : cBear, 10), size=size.small, tooltip="Smart VWAP anchor · " + evWhy))
        if anchorLbls.size() > 20
            anchorLbls.shift().delete()
else if not na(aBar)
    aW  += w
    aP  += w * src
    aP2 += w * src * src
    float v = aP / aW
    f_push(segX, segV, segS, bar_index, v, math.sqrt(math.max(aP2 / aW - v * v, 0.0)))
 
if mOn
    mW  += w
    mP  += w * src
    mP2 += w * src * src
    memX.push(bar_index)
    memV.push(mP / mW)
    if memX.size() > MAXPTS
        memX.shift()
        memV.shift()
 
float vw = aW > 0 ? aP / aW : na
float sd = aW > 0 ? math.sqrt(math.max(aP2 / aW - vw * vw, 0.0)) : na
float z  = sd > 0 ? (close - vw) / sd : na
float memVal = mOn and mW > 0 ? mP / mW : na
 
// ═════════════════════════ RETEST SETUPS ═════════════════════════
// "moved away" is measured only against the current anchor, after it has a real σ
bool statOk = not na(lastEvt) and not newAnchor and bar_index - lastEvt >= 10 and sd >= 0.3 * atr
var int awayUp = na
var int awayDn = na
if newAnchor
    awayUp := na
    awayDn := na
bool wasAwayUp = not na(awayUp) and bar_index - awayUp <= awayBars
bool wasAwayDn = not na(awayDn) and bar_index - awayDn <= awayBars
if statOk and z >= awayN
    awayUp := bar_index
if statOk and z <= -awayN
    awayDn := bar_index
 
var int   tState = 0
var float tE = na
var float tSL = na
var float tT1 = na
var float tT2 = na
var float tRisk = na
var int   tBar = na
var bool  tHit1 = false
var bool  tHit2 = false
float tp2E = math.max(tp2R, tp1R + 0.1)
var int   nT = 0
var int   nT1 = 0
var int   nT2 = 0
var float sumR = 0.0
var array<line>  tLines = array.new<line>()
var array<label> tLbls  = array.new<label>()
 
if tState != 0 and bar_index > tBar and conf
    bool isL   = tState == 1
    bool hitSL = isL ? low <= tSL : high >= tSL
    bool hit1  = isL ? high >= tT1 : low <= tT1
    bool hit2  = isL ? high >= tT2 : low <= tT2
    float r = na
    if not tHit1
        if hitSL
            r := -1.0
        else if hit2
            r := 0.5 * tp1R + 0.5 * tp2E
            tHit1 := true
            tHit2 := true
        else if hit1
            tHit1 := true
            tSL := tE
    else
        if hitSL
            r := 0.5 * tp1R
        else if hit2
            r := 0.5 * tp1R + 0.5 * tp2E
            tHit2 := true
    if na(r) and bar_index - tBar >= maxHold
        float openR = (isL ? close - tE : tE - close) / tRisk
        r := tHit1 ? 0.5 * tp1R + 0.5 * openR : openR
    if not na(r)
        nT += 1
        nT1 += tHit1 ? 1 : 0
        nT2 += tHit2 ? 1 : 0
        sumR += r
        tState := 0
 
var int retCount = 0
if newAnchor
    retCount := 0
bool emaOkL = not useEma or close > emaV
bool emaOkS = not useEma or close < emaV
float vw3 = segV.size() > 3 ? segV.get(segV.size() - 4) : na
bool slopeUp = not na(vw3) and vw > vw3
bool slopeDn = not na(vw3) and vw < vw3
bool baseOk = conf and tState == 0 and (maxRet == 0 or retCount < maxRet) and not na(aBar) and sd > 0 and statOk
bool longSig  = baseOk and aDir == 1  and low <= vw + touchTol * sd and close > vw and close > open and wasAwayUp and (not useDaily or close > dV) and (not useWeekly or close > wV) and (not useSlope or slopeUp) and emaOkL
bool shortSig = baseOk and aDir == -1 and high >= vw - touchTol * sd and close < vw and close < open and wasAwayDn and (not useDaily or close < dV) and (not useWeekly or close < wV) and (not useSlope or slopeDn) and emaOkS
 
if longSig or shortSig
    int d = longSig ? 1 : -1
    float slRaw = vw - d * slSig * sd
    float dist = math.max(math.abs(close - slRaw), minSlAtr * atr)
    tState := d
    tE := close
    tRisk := dist
    tSL := close - d * dist
    tT1 := close + d * tp1R * dist
    tT2 := close + d * tp2E * dist
    tBar := bar_index
    tHit1 := false
    tHit2 := false
    retCount += 1
    if showSig
        color c = d == 1 ? cBull : cBear
        tLines.push(line.new(bar_index, tE, bar_index + 10, tE, color=color.new(chart.fg_color, 50), width=1))
        tLines.push(line.new(bar_index, tSL, bar_index + 10, tSL, color=color.new(cBear, 30), width=1, style=line.style_dotted))
        tLines.push(line.new(bar_index, tT1, bar_index + 10, tT1, color=color.new(cBull, 30), width=1, style=line.style_dotted))
        tLines.push(line.new(bar_index, tT2, bar_index + 10, tT2, color=color.new(cBull, 30), width=1, style=line.style_dotted))
        string txt = (d == 1 ? "Long retest" : "Short retest") + "\nEntry " + str.tostring(tE, format.mintick) + "\nSL " + str.tostring(tSL, format.mintick) + "\nTP1 " + str.tostring(tT1, format.mintick) + " · TP2 " + str.tostring(tT2, format.mintick)
        tLbls.push(label.new(bar_index, d == 1 ? low : high, d == 1 ? "Long" : "Short", yloc=d == 1 ? yloc.belowbar : yloc.abovebar, style=d == 1 ? label.style_label_up : label.style_label_down, color=color.new(c, 15), textcolor=color.white, size=size.tiny, tooltip=txt))
        while tLines.size() > keepTrades * 4
            tLines.shift().delete()
        while tLbls.size() > keepTrades
            tLbls.shift().delete()
 
// ═════════════════════════ BAND 2 TOUCH STATS (per session) ═════════════════════════
var array<int> evN   = array.new<int>(4, 0)
var array<int> evRev = array.new<int>(4, 0)
var int uBar = na
var int uSes = 0
var int dBar = na
var int dSes = 0
 
// a re-anchor cancels a pending touch (the new VWAP would make the return automatic)
if newAnchor
    uBar := na
    dBar := na
if conf and not na(vw) and not newAnchor
    if not na(uBar) and bar_index > uBar
        bool f3u = high >= vw + m3 * sd
        if low <= vw and not f3u
            evN.set(uSes, evN.get(uSes) + 1)
            evRev.set(uSes, evRev.get(uSes) + 1)
            uBar := na
        else if f3u or bar_index - uBar >= statBars
            evN.set(uSes, evN.get(uSes) + 1)
            uBar := na
    if not na(dBar) and bar_index > dBar
        bool f3d = low <= vw - m3 * sd
        if high >= vw and not f3d
            evN.set(dSes, evN.get(dSes) + 1)
            evRev.set(dSes, evRev.get(dSes) + 1)
            dBar := na
        else if f3d or bar_index - dBar >= statBars
            evN.set(dSes, evN.get(dSes) + 1)
            dBar := na
 
float up2 = vw + m2 * sd
float dn2 = vw - m2 * sd
bool touchUp2 = conf and statOk and high >= up2 and not na(up2[1]) and high[1] < up2[1]
bool touchDn2 = conf and statOk and low <= dn2 and not na(dn2[1]) and low[1] > dn2[1]
if touchUp2 and na(uBar)
    uBar := bar_index
    uSes := sessId
if touchDn2 and na(dBar)
    dBar := bar_index
    dSes := sessId
 
// ═════════════════════════ DRAW CURRENT SMART VWAP ═════════════════════════
var array<polyline> live = array.new<polyline>()
var array<label> rLbls = array.new<label>()
f_pctTxt(string name, float ref) =>
    name + "  " + str.tostring((ref - close) / close * 100, "+0.00;-0.00") + "%"
 
if barstate.islast
    while live.size() > 0
        live.shift().delete()
    if segX.size() > 1
        color lc = aDir == 1 ? cBull : cBear
        if showFill and showB2
            live.push(polyline.new(f_fill(segX, segV, segS, m2), closed=true, line_color=color(na), fill_color=color.new(lc, 91)))
        if showB3
            live.push(polyline.new(f_pts(segX, segV, segS, m3), line_color=color.new(cBand, 30), line_style=line.style_dotted))
            live.push(polyline.new(f_pts(segX, segV, segS, -m3), line_color=color.new(cBand, 30), line_style=line.style_dotted))
        if showB2
            live.push(polyline.new(f_pts(segX, segV, segS, m2), line_color=color.new(cBand, 20)))
            live.push(polyline.new(f_pts(segX, segV, segS, -m2), line_color=color.new(cBand, 20)))
        if showB1
            live.push(polyline.new(f_pts(segX, segV, segS, m1), line_color=color.new(cBand, 35), line_style=line.style_dashed))
            live.push(polyline.new(f_pts(segX, segV, segS, -m1), line_color=color.new(cBand, 35), line_style=line.style_dashed))
        live.push(polyline.new(f_pts(segX, segV, segS, 0.0), line_color=lc, line_width=2))
    if showMem and memX.size() > 1
        array<chart.point> mp = array.new<chart.point>()
        int lim = bar_index - 4900
        for i = 0 to memX.size() - 1
            if memX.get(i) >= lim
                mp.push(chart.point.from_index(memX.get(i), memV.get(i)))
        if mp.size() > 1
            live.push(polyline.new(mp, line_color=color.new(mDir == 1 ? cBull : cBear, 35), line_width=1, line_style=line.style_dashed))
 
    while rLbls.size() > 0
        rLbls.shift().delete()
    array<float>  rP = array.new<float>()
    array<string> rT = array.new<string>()
    array<color>  rC = array.new<color>()
    if not na(vw)
        rP.push(vw)
        rT.push(f_pctTxt("Smart VWAP", vw))
        rC.push(aDir == 1 ? cBull : cBear)
    if showD
        rP.push(dV)
        rT.push(f_pctTxt("Daily VWAP", dV))
        rC.push(cDay)
    if showPD and not na(pdV)
        rP.push(pdV)
        rT.push(f_pctTxt("Prev Day VWAP", pdV))
        rC.push(color.new(cDay, 30))
    if showW
        rP.push(wV)
        rT.push(f_pctTxt("Weekly VWAP", wV))
        rC.push(cWeek)
    if showPW and not na(pwV)
        rP.push(pwV)
        rT.push(f_pctTxt("Prev Week VWAP", pwV))
        rC.push(color.new(cWeek, 30))
    if showM
        rP.push(mV)
        rT.push(f_pctTxt("Monthly VWAP", mV))
        rC.push(cMonth)
    if showMem and not na(memVal)
        rP.push(memVal)
        rT.push(f_pctTxt("Memory VWAP", memVal))
        rC.push(color.new(mDir == 1 ? cBull : cBear, 30))
    if showMD and not na(mdV)
        rP.push(mdV)
        rT.push(f_pctTxt(str.tostring(mdDays) + "-Day VWAP", mdV))
        rC.push(color.new(cMonth, 40))
    if showCS and inCS
        rP.push(csV)
        rT.push(f_pctTxt("Custom Session VWAP", csV))
        rC.push(cSess)
    // stack labels top-down so text never overlaps
    int nL = rP.size()
    if nL > 0
        array<int> ord = rP.sort_indices(order.descending)
        float gap = nz(atr, syminfo.mintick * 10) * lblGap
        float prevY = na
        for k = 0 to nL - 1
            int j = ord.get(k)
            float y = rP.get(j)
            if not na(prevY) and prevY - y < gap
                y := prevY - gap
            prevY := y
            rLbls.push(label.new(bar_index + 2, y, rT.get(j), style=label.style_label_left, color=color(na), textcolor=rC.get(j), size=size.small, tooltip=str.tostring(rP.get(j), format.mintick)))
 
// ═════════════════════════ DASHBOARD ═════════════════════════
f_pos() =>
    switch tblPos
        "Top Left"     => position.top_left
        "Bottom Left"  => position.bottom_left
        "Bottom Right" => position.bottom_right
        => position.top_right
f_size() =>
    switch tblSize
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
var table tb = table.new(f_pos(), 2, 17, border_width=1, frame_width=1, frame_color=color.new(chart.fg_color, 80), border_color=color.new(chart.fg_color, 90))
if barstate.isfirst
    table.merge_cells(tb, 0, 0, 1, 0)
 
f_row(int r, string k, string v, color vc) =>
    table.cell(tb, 0, r, k, text_color=color.new(chart.fg_color, 25), text_halign=text.align_left, text_size=f_size(), bgcolor=color.new(chart.bg_color, 5))
    table.cell(tb, 1, r, v, text_color=vc, text_halign=text.align_left, text_size=f_size(), bgcolor=color.new(chart.bg_color, 5))
 
f_side(float ref) =>
    na(ref) ? "–" : str.tostring(ref, format.mintick) + (close >= ref ? "  · price above" : "  · price below")
 
f_pct(int a, int b) =>
    b > 0 ? str.tostring(100.0 * a / b, "0") + "%  (n " + str.tostring(b) + ")" : "no data yet"
 
if barstate.islast and showTbl
    table.cell(tb, 0, 0, "Eye Smart VWAP", text_color=chart.fg_color, text_size=f_size(), bgcolor=color.new(chart.fg_color, 90))
    int score = (aDir == 1 ? 1 : aDir == -1 ? -1 : 0) + (na(vw) ? 0 : close > vw ? 1 : -1) + (close > dV ? 1 : -1)
    string bias = score >= 3 ? "Strong bullish (3/3)" : score >= 1 ? "Bullish lean" : score <= -3 ? "Strong bearish (3/3)" : score <= -1 ? "Bearish lean" : "Neutral"
    color bc = score > 0 ? cBull : score < 0 ? cBear : chart.fg_color
    f_row(1, "Bias", bias, bc)
    f_row(2, "Smart VWAP", na(vw) ? "–" : str.tostring(vw, format.mintick) + (na(z) ? "" : "   " + str.tostring(z, "+0.0;-0.0") + "σ from VWAP"), aDir == 1 ? cBull : cBear)
    f_row(3, "Anchor", aWhy + (na(aBar) ? "" : " · " + str.tostring(bar_index - aBar) + " bars ago"), chart.fg_color)
    f_row(4, "Daily VWAP", f_side(dV), cDay)
    f_row(5, "Prev Day VWAP", na(pdV) ? "–" : str.tostring(pdV, format.mintick), cDay)
    f_row(6, "Weekly VWAP", f_side(wV), cWeek)
    int ups = 0
    int steps = dayClose.size() - 1
    if steps > 0
        for i = 1 to steps
            if dayClose.get(i) > dayClose.get(i - 1)
                ups += 1
    string mig = steps <= 0 ? "need more days" : ups >= math.ceil(steps * 0.75) ? "↑ Rising (" + str.tostring(ups) + " of " + str.tostring(steps) + " days)" : ups <= math.floor(steps * 0.25) ? "↓ Falling (" + str.tostring(steps - ups) + " of " + str.tostring(steps) + " days)" : "↔ Mixed (" + str.tostring(ups) + " up of " + str.tostring(steps) + ")"
    f_row(7, "Value migration", mig, ups * 2 > steps ? cBull : ups * 2 < steps ? cBear : chart.fg_color)
    f_row(8, "Session now", sessId == 1 ? "Asia" : sessId == 2 ? "London" : sessId == 3 ? "New York" : "Off-session", chart.fg_color)
    string rs = nT > 0 ? "TP1 " + str.tostring(100.0 * nT1 / nT, "0") + "% · TP2 " + str.tostring(100.0 * nT2 / nT, "0") + "% · avg " + str.tostring(sumR / nT, "+0.00;-0.00") + "R · n " + str.tostring(nT) : "no closed setups yet"
    f_row(9, "Retest setups", rs, nT > 0 and sumR > 0 ? cBull : nT > 0 ? cBear : chart.fg_color)
    string openTxt = tState == 0 ? "none" : (tState == 1 ? "Long" : "Short") + " · entry " + str.tostring(tE, format.mintick) + (tHit1 ? " · TP1 hit, stop at entry" : "")
    f_row(10, "Open setup", openTxt, tState == 1 ? cBull : tState == -1 ? cBear : chart.fg_color)
    f_row(11, "Band 2 touch → back to VWAP", "", chart.fg_color)
    f_row(12, "   Asia", f_pct(evRev.get(1), evN.get(1)), chart.fg_color)
    f_row(13, "   London", f_pct(evRev.get(2), evN.get(2)), chart.fg_color)
    f_row(14, "   New York", f_pct(evRev.get(3), evN.get(3)), chart.fg_color)
    string zoneTxt = na(z) ? "–" : z >= m3 ? "Above band 3 (stretched)" : z >= m2 ? "Between band 2 and 3 (up)" : z >= m1 ? "Between band 1 and 2 (up)" : z >= 0 ? "VWAP to band 1 (up)" : z > -m1 ? "VWAP to band 1 (down)" : z > -m2 ? "Between band 1 and 2 (down)" : z > -m3 ? "Between band 2 and 3 (down)" : "Below band 3 (stretched)"
    f_row(15, "Band zone", zoneTxt, na(z) ? chart.fg_color : z >= 0 ? cBull : cBear)
    f_row(16, "Note", "Stats in-sample on this chart, before costs", color.new(chart.fg_color, 45))
 
// ═════════════════════════ PLOTS ═════════════════════════
plot(showD ? dV : na, "Daily VWAP", newD ? color(na) : cDay, 2)
plot(showD and showDB ? dV + m1 * dSD : na, "Daily band 1 up", newD ? color(na) : color.new(cDay, 60), 1)
plot(showD and showDB ? dV - m1 * dSD : na, "Daily band 1 down", newD ? color(na) : color.new(cDay, 60), 1)
plot(showD and showDB ? dV + m2 * dSD : na, "Daily band 2 up", newD ? color(na) : color.new(cDay, 40), 1)
plot(showD and showDB ? dV - m2 * dSD : na, "Daily band 2 down", newD ? color(na) : color.new(cDay, 40), 1)
plot(showPD ? pdV : na, "Prev Day VWAP", newD ? color(na) : color.new(cDay, 35), 1, plot.style_circles)
plot(showW ? wV : na, "Weekly VWAP", newW ? color(na) : cWeek, 2)
plot(showW and showWB ? wV + m1 * wSD : na, "Weekly band 1 up", newW ? color(na) : color.new(cWeek, 60), 1)
plot(showW and showWB ? wV - m1 * wSD : na, "Weekly band 1 down", newW ? color(na) : color.new(cWeek, 60), 1)
plot(showW and showWB ? wV + m2 * wSD : na, "Weekly band 2 up", newW ? color(na) : color.new(cWeek, 40), 1)
plot(showW and showWB ? wV - m2 * wSD : na, "Weekly band 2 down", newW ? color(na) : color.new(cWeek, 40), 1)
plot(showPW ? pwV : na, "Prev Week VWAP", newW ? color(na) : color.new(cWeek, 35), 1, plot.style_circles)
plot(showM ? mV : na, "Monthly VWAP", newM ? color(na) : cMonth, 2)
plot(showS and sessId != 0 ? sV : na, "Session VWAP", newS ? color(na) : cSess, 1, plot.style_linebr)
plot(showMD ? mdV : na, "Multi-day VWAP", newD ? color(na) : color.new(cMonth, 40), 2)
plot(showCS and inCS ? csV : na, "Custom Session VWAP", newCS ? color(na) : cSess, 2, plot.style_linebr)
plot(showEma ? emaV : na, "EMA", color.new(chart.fg_color, 50), 1)
color zc = na(z) or not barCol ? color(na) : z >= m2 ? cBull : z >= m1 ? color.new(cBull, 45) : z <= -m2 ? cBear : z <= -m1 ? color.new(cBear, 45) : color(na)
barcolor(zc)
plot(vw, "Smart VWAP", display=display.data_window)
plot(z, "Smart VWAP distance (σ)", display=display.data_window)
 
// ═════════════════════════ ALERTS ═════════════════════════
bool crossUp = conf and not na(vw) and not na(vw[1]) and not newAnchor and close > vw and close[1] <= nz(vw[1], close[1])
bool crossDn = conf and not na(vw) and not na(vw[1]) and not newAnchor and close < vw and close[1] >= nz(vw[1], close[1])
bool rejUp   = conf and statOk and high >= up2 and close < up2
bool rejDn   = conf and statOk and low <= dn2 and close > dn2
bool dCross  = conf and ((close > dV and close[1] <= dV[1]) or (close < dV and close[1] >= dV[1])) and not newD
 
alertcondition(newAnchor, "Smart VWAP re-anchored", "Eye Smart VWAP: new anchor on {{ticker}} {{interval}}")
alertcondition(longSig,  "Long retest setup",  "Eye Smart VWAP: Long retest on {{ticker}} {{interval}} at {{close}}")
alertcondition(shortSig, "Short retest setup", "Eye Smart VWAP: Short retest on {{ticker}} {{interval}} at {{close}}")
alertcondition(crossUp,  "Price crossed above Smart VWAP", "Eye Smart VWAP: {{ticker}} closed above Smart VWAP")
alertcondition(crossDn,  "Price crossed below Smart VWAP", "Eye Smart VWAP: {{ticker}} closed below Smart VWAP")
alertcondition(touchUp2, "Touch upper band 2", "Eye Smart VWAP: {{ticker}} touched upper band 2")
alertcondition(touchDn2, "Touch lower band 2", "Eye Smart VWAP: {{ticker}} touched lower band 2")
alertcondition(rejUp,    "Rejected at upper band 2", "Eye Smart VWAP: {{ticker}} touched upper band 2 and closed back inside")
alertcondition(rejDn,    "Rejected at lower band 2", "Eye Smart VWAP: {{ticker}} touched lower band 2 and closed back inside")
alertcondition(dCross,   "Daily VWAP cross", "Eye Smart VWAP: {{ticker}} crossed Daily VWAP")
 
if newAnchor
    alert("Eye Smart VWAP | " + syminfo.ticker + " | new anchor: " + aWhy, alert.freq_once_per_bar_close)
if longSig or shortSig
    alert("Eye Smart VWAP | " + syminfo.ticker + " | " + (longSig ? "LONG" : "SHORT") + " retest | entry " + str.tostring(tE, format.mintick) + " | SL " + str.tostring(tSL, format.mintick) + " | TP1 " + str.tostring(tT1, format.mintick) + " | TP2 " + str.tostring(tT2, format.mintick), alert.freq_once_per_bar_close)

← 返回列表