GlowVwap | Anchored VWAP Pullback Strategy

blitz_algo · strategy · 318 行 · 点赞 436 · TradingView 原页

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

Pine Script

//@version=6
strategy("AVWAP Pullback Glow [Strategy]", shorttitle = "AVWAP-GLOW", overlay = true,
     initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10,
     commission_type = strategy.commission.percent, commission_value = 0.02, slippage = 2,
     pyramiding = 0, calc_on_every_tick = false, process_orders_on_close = false)
 
// ════════════════════════════════════════════════════════════════════════════
//  CORE IDEA (one setup, trade with the anchored-VWAP trend only)
//   1) Anchored VWAP + volume-weighted σ bands, reset each anchor.
//   2) Trend = accepted closes beyond VWAP + rising/falling VWAP + no chop.
//   3) Prior-anchor bridge = directional bias (block trades against a confirmed migration).
//   4) Entry = pullback into the VWAP zone that closes back on the trend side.
//   5) Risk = structural stop beyond VWAP, 2R target, breakeven at 1R, VWAP-lost exit, flat at anchor end.
// ════════════════════════════════════════════════════════════════════════════
 
// ─────────────────────────── INPUTS ───────────────────────────
string gT = "Trading"
string dirMode     = input.string("Both", "Direction", options = ["Both", "Long Only", "Short Only"], group = gT)
float  pullZ       = input.float(0.50, "Pullback: low/high within this many σ of VWAP", minval = 0.0, maxval = 2.0, step = 0.05, group = gT)
int    maxTrades   = input.int(2, "Max trades per anchor period", minval = 1, group = gT)
 
string gR = "Risk"
float  riskPct     = input.float(0.5, "Risk per trade (% of equity)", minval = 0.05, maxval = 5.0, step = 0.05, group = gR)
float  maxPosPct   = input.float(100.0, "Max position size (% of equity)", minval = 5.0, maxval = 500.0, step = 5.0, group = gR)
float  stopK       = input.float(1.0, "Stop distance beyond VWAP (× σeff)", minval = 0.3, step = 0.1, group = gR)
float  minStopATR  = input.float(0.75, "Min stop size (× ATR)", minval = 0.1, step = 0.05, group = gR)
float  maxStopATR  = input.float(3.0, "Skip trade if stop larger than (× ATR)", minval = 0.5, step = 0.1, group = gR)
float  rrMult      = input.float(2.0, "Target (R multiple)", minval = 0.5, step = 0.25, group = gR)
float  beR         = input.float(1.0, "Move stop to breakeven at (R)", minval = 0.3, step = 0.1, group = gR)
bool   flatAtAnchor = input.bool(true, "Flatten at each new anchor", group = gR)
 
string gA = "Anchor"
string anchorMode  = input.string("Day", "Anchor period", options = ["Session", "Day", "Week", "Month"], group = gA)
float  srcIn       = input.source(hlc3, "Price source", group = gA)
bool   useVolume   = input.bool(true, "Volume weighted (off = TWAP)", group = gA)
int    atrLen      = input.int(14, "ATR length", minval = 1, group = gA)
float  floorK      = input.float(0.4, "σ floor (× ATR)", minval = 0.0, step = 0.05, group = gA)
int    matMinutes  = input.int(60, "Maturity (minutes after anchor)", minval = 0, group = gA)
float  b1K         = input.float(1.0, "Inner band (× σeff)", minval = 0.1, step = 0.1, group = gA)
float  b2K         = input.float(2.0, "Outer band (× σeff)", minval = 0.1, step = 0.1, group = gA)
 
string gF = "Trend filters"
int    accBars     = input.int(2, "Accepted closes to confirm a side", minval = 1, group = gF)
float  hystK       = input.float(0.15, "Dead-zone around VWAP (× σeff)", minval = 0.0, step = 0.05, group = gF)
int    slopeBars   = input.int(5, "VWAP slope lookback (bars)", minval = 1, group = gF)
int    rotWin      = input.int(14, "Chop window (bars)", minval = 4, group = gF)
int    chopMax     = input.int(3, "Side flips in window = chop", minval = 2, group = gF)
 
string gM = "Prior-anchor bridge (bias)"
bool   useBridge   = input.bool(true, "Use bridge bias", group = gM)
string migFilter   = input.string("Block opposite", "Bias mode", options = ["Off", "Block opposite", "Require agree"], group = gM)
float  migEntry    = input.float(1.0, "Migration: new VWAP displacement (old σ)", minval = 0.3, step = 0.1, group = gM)
float  anchorEntry = input.float(0.20, "Migration: continued-anchor displacement (old σ)", minval = 0.05, step = 0.05, group = gM)
float  bridgeEntry = input.float(0.35, "Bridge: return distance (old σ)", minval = 0.1, step = 0.05, group = gM)
 
string gV = "Visuals"
bool   showGlow    = input.bool(true, "VWAP glow", group = gV)
bool   showBands   = input.bool(true, "Gradient bands", group = gV)
bool   showBridge  = input.bool(true, "Prior equilibrium + bridge fill", group = gV)
bool   showLevels  = input.bool(true, "Live trade levels", group = gV)
bool   showMarkers = input.bool(true, "Entry markers", group = gV)
bool   showPanel   = input.bool(true, "Dashboard", group = gV)
 
// ─────────────────────────── COLOURS ───────────────────────────
color cUp     = #00e5b0
color cDn     = #ff4d6d
color cNeu    = #8f9bb3
color cBridge = #3d9bff
 
// ─────────────────────────── ANCHOR & VWAP ENGINE ───────────────────────────
float atr = nz(ta.atr(atrLen))
float w   = useVolume and nz(volume) > 0 ? volume : 1.0
int matBars = math.max(int(math.ceil(matMinutes * 60.0 / timeframe.in_seconds())), 3)
 
bool chD = timeframe.change("D")
bool chW = timeframe.change("W")
bool chM = timeframe.change("M")
bool chS = session.isfirstbar
bool newAnchor = anchorMode == "Session" ? chS : anchorMode == "Week" ? chW : anchorMode == "Month" ? chM : chD
 
var float p0   = na
var float sW   = 0.0
var float sWD  = 0.0
var float sWD2 = 0.0
var int   n    = 0
var float vw   = na
var float sig  = na
 
var float refVw  = na
var float refSig = na
var float refW   = na
var bool  separated = false
 
var int runUp = 0
var int runDn = 0
var int gate  = 0
var int lastSide = 0
var int tradesAnchor = 0
 
bool resetNow = newAnchor or na(p0)
if resetNow
    if n >= 3 and not na(vw) and nz(sig) > 0 and sW > 0
        refVw  := vw
        refSig := math.max(sig, syminfo.mintick)
        refW   := sW
    else
        refVw  := na
        refSig := na
        refW   := na
    p0 := srcIn
    sW := 0.0
    sWD := 0.0
    sWD2 := 0.0
    n := 0
    separated := false
    runUp := 0
    runDn := 0
    gate := 0
    lastSide := 0
    tradesAnchor := 0
 
float dPx = srcIn - p0
sW   += w
sWD  += w * dPx
sWD2 += w * dPx * dPx
n    += 1
float mDev = sWD / sW
vw  := p0 + mDev
sig := math.sqrt(math.max(sWD2 / sW - mDev * mDev, 0.0))
 
float sEff   = math.max(nz(sig), floorK * atr)
bool  mature = n >= matBars and sEff > 0
float z      = mature ? (close - vw) / sEff : na
float dz     = hystK * sEff
 
// ─────────────────────────── BRIDGE (prior anchor) ───────────────────────────
bool  refValid = not na(refVw) and not na(refSig) and not na(refW)
float newShare = refValid ? sW / (refW + sW) : na
float disp     = refValid ? (vw - refVw) / refSig : na
float contDisp = refValid ? newShare * disp : na
float contVw   = refValid ? refVw + newShare * (vw - refVw) : na
if refValid and math.abs(disp) >= migEntry
    separated := true
 
int migSt = 0   // 1 up migration, -1 down migration, 2 bridged
if useBridge and refValid and mature
    if math.abs(disp) >= migEntry and math.abs(contDisp) >= anchorEntry
        migSt := disp > 0 ? 1 : -1
    else if separated and math.abs(disp) <= bridgeEntry
        migSt := 2
 
// ─────────────────────────── TREND STATE ───────────────────────────
runUp := close > vw + dz ? runUp + 1 : 0
runDn := close < vw - dz ? runDn + 1 : 0
if mature
    if runUp >= accBars
        gate := 1
    else if runDn >= accBars
        gate := -1
 
int side = mature ? (close > vw + dz ? 1 : close < vw - dz ? -1 : 0) : 0
bool flip = side != 0 and lastSide != 0 and side != lastSide
if side != 0
    lastSide := side
int rot = int(math.sum(flip ? 1 : 0, rotWin))
 
bool chop    = rot >= chopMax
bool slopeUp = n > slopeBars and vw > nz(vw[slopeBars])
bool slopeDn = n > slopeBars and vw < nz(vw[slopeBars])
int  rgS     = not mature ? 0 : chop ? 2 : gate      // 0 immature, 2 chop, 1 up, -1 down
 
// ─────────────────────────── SIGNALS ───────────────────────────
bool allowLong  = dirMode != "Short Only"
bool allowShort = dirMode != "Long Only"
bool flat       = strategy.position_size == 0
bool canTrade   = mature and flat and not chop and tradesAnchor < maxTrades and atr > 0
 
bool migOkL = migFilter == "Off" or not (useBridge and refValid) or (migFilter == "Block opposite" ? migSt != -1 : migSt == 1)
bool migOkS = migFilter == "Off" or not (useBridge and refValid) or (migFilter == "Block opposite" ? migSt != 1 : migSt == -1)
 
float lowZ  = (low - vw) / sEff
float highZ = (high - vw) / sEff
 
bool pullLong  = rgS == 1  and slopeUp and lowZ <= pullZ  and lowZ >= -stopK  and close > vw + dz and close > open and z < b2K
bool pullShort = rgS == -1 and slopeDn and highZ >= -pullZ and highZ <= stopK and close < vw - dz and close < open and z > -b2K
 
float rdL = math.max(close - (vw - stopK * sEff), minStopATR * atr)
float rdS = math.max((vw + stopK * sEff) - close, minStopATR * atr)
 
bool longSig  = canTrade and allowLong  and pullLong  and migOkL and rdL <= maxStopATR * atr
bool shortSig = canTrade and allowShort and pullShort and migOkS and rdS <= maxStopATR * atr
 
var float riskDist = na
var bool  beArmed  = false
var float curEntry = na
var float curStop  = na
var float curTgt   = na
 
float riskCash = strategy.equity * riskPct / 100.0
float capPct   = strategy.equity * maxPosPct / 100.0
 
if longSig
    float qty = math.min(riskCash / (rdL * syminfo.pointvalue), capPct / (close * syminfo.pointvalue))
    if qty > 0
        riskDist := rdL
        tradesAnchor += 1
        strategy.entry("Long", strategy.long, qty = qty, comment = "Pullback L")
        strategy.exit("XL", "Long", stop = close - rdL, limit = close + rrMult * rdL)
else if shortSig
    float qty = math.min(riskCash / (rdS * syminfo.pointvalue), capPct / (close * syminfo.pointvalue))
    if qty > 0
        riskDist := rdS
        tradesAnchor += 1
        strategy.entry("Short", strategy.short, qty = qty, comment = "Pullback S")
        strategy.exit("XS", "Short", stop = close + rdS, limit = close - rrMult * rdS)
 
// ─────────────────────────── TRADE MANAGEMENT ───────────────────────────
if strategy.position_size == 0
    beArmed := false
    curEntry := na
    curStop := na
    curTgt := na
else if not na(riskDist)
    float avg  = strategy.position_avg_price
    float dirS = strategy.position_size > 0 ? 1.0 : -1.0
    if not beArmed and dirS * (close - avg) >= beR * riskDist
        beArmed := true
    curEntry := avg
    curStop  := beArmed ? avg + dirS * syminfo.mintick : avg - dirS * riskDist
    curTgt   := avg + dirS * rrMult * riskDist
    if strategy.position_size > 0
        strategy.exit("XL", "Long", stop = curStop, limit = curTgt)
        if runDn >= accBars
            strategy.close("Long", comment = "VWAP lost")
    else
        strategy.exit("XS", "Short", stop = curStop, limit = curTgt)
        if runUp >= accBars
            strategy.close("Short", comment = "VWAP lost")
 
if flatAtAnchor and newAnchor and strategy.position_size != 0
    strategy.close_all(comment = "New anchor")
 
// ─────────────────────────── VISUALS ───────────────────────────
color rgCol = rgS == 1 ? cUp : rgS == -1 ? cDn : cNeu
color stCol = migSt == 1 ? cUp : migSt == -1 ? cDn : migSt == 2 ? cBridge : cNeu
 
float vwP = newAnchor ? na : vw
 
// glow layers (wide, faint -> narrow, bright) then the core line
plot(showGlow ? vwP : na, "Glow outer", color.new(rgCol, 94), 15, plot.style_linebr, display = display.pane)
plot(showGlow ? vwP : na, "Glow mid",   color.new(rgCol, 86), 9,  plot.style_linebr, display = display.pane)
plot(showGlow ? vwP : na, "Glow inner", color.new(rgCol, 72), 5,  plot.style_linebr, display = display.pane)
pVw = plot(vwP, "Anchored VWAP", rgCol, 2, plot.style_linebr)
 
// gradient bands: transparent at VWAP, solid toward the outer band
float vwB  = showBands and not newAnchor ? vw : na
float b2uV = showBands and not newAnchor ? vw + b2K * sEff : na
float b2dV = showBands and not newAnchor ? vw - b2K * sEff : na
pB2u = plot(b2uV, "Outer band +", color.new(rgCol, 80), 1, plot.style_linebr)
pB2d = plot(b2dV, "Outer band -", color.new(rgCol, 80), 1, plot.style_linebr)
plot(showBands and not newAnchor ? vw + b1K * sEff : na, "Inner band +", color.new(rgCol, 65), 1, plot.style_linebr)
plot(showBands and not newAnchor ? vw - b1K * sEff : na, "Inner band -", color.new(rgCol, 65), 1, plot.style_linebr)
fill(pB2u, pVw, top_value = b2uV, bottom_value = vwB, top_color = color.new(rgCol, 72), bottom_color = color.new(rgCol, 100), title = "Upper gradient")
fill(pVw, pB2d, top_value = vwB, bottom_value = b2dV, top_color = color.new(rgCol, 100), bottom_color = color.new(rgCol, 72), title = "Lower gradient")
 
// VWAP <-> close fill: stronger the further price is stretched
pCl = plot(close, "Close link", na, display = display.none, editable = false)
int stretchT = int(92 - 34 * math.min(math.abs(nz(z)) / b2K, 1.0))
fill(pVw, pCl, mature and not newAnchor ? color.new(rgCol, stretchT) : na, "VWAP to close")
 
// bridge: frozen prior equilibrium + maturity-weighted fill between new and continued VWAP
bool bridgeVis = showBridge and refValid and not newAnchor
plot(bridgeVis ? refVw : na, "Prior equilibrium", color.new(cNeu, 30), 1, plot.style_linebr)
pNew  = plot(bridgeVis ? vw : na, "Bridge new", na, display = display.none, editable = false)
pCont = plot(bridgeVis ? contVw : na, "Bridge continued", color.new(cNeu, 55), 1, plot.style_linebr)
fill(pNew, pCont, bridgeVis ? color.new(stCol, int(92 - 45 * nz(newShare))) : na, "Reset bridge")
 
// live trade levels
bool inTrade = strategy.position_size != 0
pEnt = plot(showLevels and inTrade ? curEntry : na, "Entry", color.new(cNeu, 20), 1, plot.style_linebr)
pStp = plot(showLevels and inTrade ? curStop : na, "Stop", color.new(cDn, 10), 1, plot.style_linebr)
pTgt = plot(showLevels and inTrade ? curTgt : na, "Target", color.new(cUp, 10), 1, plot.style_linebr)
fill(pEnt, pTgt, showLevels and inTrade ? color.new(cUp, 88) : na, "Target zone")
fill(pEnt, pStp, showLevels and inTrade ? color.new(cDn, 88) : na, "Risk zone")
 
plotshape(showMarkers and longSig,  "Long",  shape.triangleup,   location.belowbar, cUp, size = size.tiny)
plotshape(showMarkers and shortSig, "Short", shape.triangledown, location.abovebar, cDn, size = size.tiny)
 
// ─────────────────────────── DASHBOARD ───────────────────────────
f_num(float x, string fmt) =>
    na(x) ? "--" : str.tostring(x, fmt)
 
f_rg(int s) =>
    s == 1 ? "UP TREND" : s == -1 ? "DOWN TREND" : s == 2 ? "CHOP" : "IMMATURE"
 
f_mig(int s, bool ok) =>
    not ok ? "NO PRIOR ANCHOR" : s == 1 ? "UP MIGRATION" : s == -1 ? "DOWN MIGRATION" : s == 2 ? "BRIDGED" : "UNRESOLVED"
 
var table panel = table.new(position.top_right, 2, 8, bgcolor = color.new(chart.bg_color, 12), frame_color = color.new(cNeu, 50), frame_width = 1, border_width = 1, border_color = color.new(cNeu, 80))
if barstate.islast and showPanel
    float wr = strategy.closedtrades > 0 ? strategy.wintrades / strategy.closedtrades * 100.0 : na
    string posTxt = strategy.position_size > 0 ? "LONG" : strategy.position_size < 0 ? "SHORT" : "FLAT"
    table.cell(panel, 0, 0, "AVWAP GLOW", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 1, 0, f_rg(rgS), text_color = rgCol, text_size = size.small)
    table.cell(panel, 0, 1, "Bridge bias", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 1, 1, f_mig(migSt, refValid), text_color = stCol, text_size = size.small)
    table.cell(panel, 0, 2, "z (σ from VWAP)", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 1, 2, f_num(z, "#.00"), text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 0, 3, "Slope / flips", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 1, 3, (slopeUp ? "UP" : slopeDn ? "DOWN" : "FLAT") + " / " + str.tostring(rot), text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 0, 4, "Trades this anchor", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 1, 4, str.tostring(tradesAnchor) + " / " + str.tostring(maxTrades), text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 0, 5, "Net profit", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 1, 5, str.tostring(strategy.netprofit, format.mintick), text_color = strategy.netprofit >= 0 ? cUp : cDn, text_size = size.small)
    table.cell(panel, 0, 6, "Win rate (trades)", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 1, 6, f_num(wr, "#.0") + "% (" + str.tostring(strategy.closedtrades) + ")", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 0, 7, "Position", text_color = chart.fg_color, text_size = size.small)
    table.cell(panel, 1, 7, posTxt, text_color = strategy.position_size > 0 ? cUp : strategy.position_size < 0 ? cDn : chart.fg_color, text_size = size.small)

← 返回列表