Strategies KB.ZH
Strategies

VWAP偏差带与波动性过滤交易策略-VWAP-Deviation-Band-and-Volatility-Filter-Trading-Strategy

ianzeng123 · PineScript · Volatility and Channels · 2025-04-07 11:57:10

All strategies →

No English write-up in the source (no author description).

Read the Chinese version →

Source code (140 lines)
/*backtest
start: 2025-03-30 00:00:00
end: 2025-03-31 20:00:00
period: 1m
basePeriod: 1m
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=5
strategy("VWAP Strategy", overlay=true, default_qty_type=strategy.fixed, default_qty_value=1, initial_capital=2000)

// === Inputs ===
src = input.source(hlc3, "Source")
stopPoints = input.float(20.0, "Stop Buffer (Points from Signal Bar High/Low)", step=0.25)

exitModeLong = input.string("VWAP", "Long Exit Rule", options=["VWAP", "Deviation Band", "None"])
exitModeShort = input.string("VWAP", "Short Exit Rule", options=["VWAP", "Deviation Band", "None"])
targetLongDeviation = input.float(2.0, "Long Target Deviation", step=0.1)
targetShortDeviation = input.float(2.0, "Short Target Deviation", step=0.1)

enableSafetyExit = input.bool(true, "Enable Safety Exit")
numOpposingBars = input.int(3, "Opposing Bars for Safety Exit", minval=1)

allowLongs = input.bool(true, "Allow Long Trades")
allowShorts = input.bool(true, "Allow Short Trades")

minStrength = input.float(0.7, "Minimum Signal Strength (0-1)", step=0.05)

showVWAP = input.bool(true, "Show VWAP")
showBands = input.bool(true, "Show Entry Bands")
showLowVolZones = input.bool(true, "Highlight Low Vol Zones")

// === VWAP Session Logic ===
var float sumSrc = na
var float sumVol = na
var float sumSrcSqVol = na

newSession = ta.change(time("D"))
if newSession or na(sumSrc)
    sumSrc := 0.0
    sumVol := 0.0
    sumSrcSqVol := 0.0

sumSrc += src * volume
sumVol += volume
sumSrcSqVol += math.pow(src, 2) * volume

vwap = sumSrc / sumVol
variance = (sumSrcSqVol / sumVol) - math.pow(vwap, 2)
stdev = math.sqrt(variance)

// === Deviation Bands ===
bandEntryMult = 2.0
entryUpper = vwap + stdev * bandEntryMult
entryLower = vwap - stdev * bandEntryMult

targetUpperLong = vwap + stdev * targetLongDeviation
targetLowerShort = vwap - stdev * targetShortDeviation

// === ATR-Based Volatility Filter ===
atrVal = ta.atr(14)
isVolTooLow = stdev * 2 < atrVal * 3
bgcolor(showLowVolZones and isVolTooLow ? color.new(color.orange, 85) : na, title="Low Volatility Zone")

// === Signal Strength Calculations ===
barRange = high - low
bullStrength = barRange > 0 ? (close - low) / barRange : 0
bearStrength = barRange > 0 ? (high - close) / barRange : 0

// === Entry Triggers with Strength Filter ===
isH1H2 = open < entryLower and close > entryLower and bullStrength >= minStrength
isL1L2 = open > entryUpper and close < entryUpper and bearStrength >= minStrength

plotshape(isH1H2, title="H1/H2", location=location.belowbar, color=color.lime, style=shape.triangleup, size=size.tiny)
plotshape(isL1L2, title="L1/L2", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.tiny)

// === Signal Bar Stop Tracking ===
var float signalLow = na
var float signalHigh = na

// === Entry Logic ===
longCondition = allowLongs and isH1H2 and strategy.position_size == 0 and not isVolTooLow
shortCondition = allowShorts and isL1L2 and strategy.position_size == 0 and not isVolTooLow

if longCondition
    strategy.entry("Long", strategy.long)
    signalLow := low

if shortCondition
    strategy.entry("Short", strategy.short)
    signalHigh := high

// === Reset Signal Bar Info
if strategy.position_size == 0
    signalLow := na
    signalHigh := na

// === Apply Signal-Bar-Based Stop
if strategy.opentrades > 0
    if strategy.position_size > 0 and not na(signalLow)
        strategy.exit("Long SL", from_entry="Long", stop=signalLow - stopPoints)
    if strategy.position_size < 0 and not na(signalHigh)
        strategy.exit("Short SL", from_entry="Short", stop=signalHigh + stopPoints)

// === Target Exits (Independent per side)
exitLongVWAP = strategy.position_size > 0 and exitModeLong == "VWAP" and high >= vwap
exitLongDev  = strategy.position_size > 0 and exitModeLong == "Deviation Band" and high >= targetUpperLong
exitShortVWAP = strategy.position_size < 0 and exitModeShort == "VWAP" and low <= vwap
exitShortDev  = strategy.position_size < 0 and exitModeShort == "Deviation Band" and low <= targetLowerShort

if exitModeLong != "None" and (exitLongVWAP or exitLongDev)
    strategy.close("Long", comment="Target Exit")

if exitModeShort != "None" and (exitShortVWAP or exitShortDev)
    strategy.close("Short", comment="Target Exit")

// === Safety Exit
bullishBar(i) => close[i] > open[i]
bearishBar(i) => close[i] < open[i]

bullCount = 0
bearCount = 0
for i = 0 to numOpposingBars - 1
    bullCount += bullishBar(i) ? 1 : 0
    bearCount += bearishBar(i) ? 1 : 0

exitSafetyLong = enableSafetyExit and strategy.position_size > 0 and bearCount == numOpposingBars
exitSafetyShort = enableSafetyExit and strategy.position_size < 0 and bullCount == numOpposingBars

if exitSafetyLong
    strategy.close("Long", comment="Safety Exit")

if exitSafetyShort
    strategy.close("Short", comment="Safety Exit")

// === Plotting ===
plot(showVWAP ? vwap : na, color=color.blue, title="VWAP")
pUpper = plot(showBands ? entryUpper : na, color=color.green, title="Upper Entry Band")
pLower = plot(showBands ? entryLower : na, color=color.red, title="Lower Entry Band")
fill(pUpper, pLower, color=color.new(color.gray, 85))