本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Volatility of Volatility State Lattice [Pineify]", shorttitle="VoV Lattice [Pineify]", overlay=false, max_bars_back=600, precision=1)
string gCalc = "Measurement"
int baseLength = input.int(80, "Prior baseline bars", minval=20, maxval=240, group=gCalc)
int pathLength = input.int(16, "Recent path steps", minval=6, maxval=60, group=gCalc)
int memoryLength = input.int(8, "Pressure memory bars", minval=2, maxval=40, group=gCalc)
float speedReference = input.float(0.60, "Speed reference (robust units / bar)", minval=0.05, maxval=5.0, step=0.05, group=gCalc)
float directionFloor = input.float(0.05, "Direction deadband (robust units)", minval=0.0, maxval=1.0, step=0.01, group=gCalc)
string gState = "State confirmation"
float pressureEntry = input.float(55.0, "Instability entry", minval=40.0, maxval=90.0, group=gState)
float pressureExit = input.float(30.0, "Instability release", minval=5.0, maxval=35.0, group=gState)
float levelEntry = input.float(1.0, "High level entry (robust units)", minval=0.5, maxval=5.0, step=0.1, group=gState)
float levelGap = input.float(0.5, "Level hysteresis width", minval=0.1, maxval=2.0, step=0.1, group=gState)
int confirmBars = input.int(2, "Consecutive transition closes", minval=1, maxval=5, group=gState)
int settlingBars = input.int(5, "Quiet closes after release", minval=2, maxval=30, group=gState)
string gVisual = "Visual layers"
bool showRibbon = input.bool(true, "Pressure-memory separation ribbon", group=gVisual)
bool showBackground = input.bool(true, "State background", group=gVisual)
bool showEvents = input.bool(true, "Confirmed event marks", group=gVisual)
bool showTable = input.bool(true, "State lattice and diagnostics", group=gVisual)
color lowColor = #2875B8
color highColor = #A66908
color unstableColor = #B6408A
color settlingColor = #14847E
color waitingColor = #6C7280
f_color(int s) =>
switch s
1 => lowColor
2 => highColor
3 => unstableColor
4 => settlingColor
=> waitingColor
f_number(float x) =>
na(x) ? "--" : str.tostring(x, "#.00")
// Invalid observations keep their bar slots; array statistics never skip them silently.
bool validOHLC = not na(open) and not na(high) and not na(low) and not na(close) and not na(close[1]) and high >= math.max(open, close) and low <= math.min(open, close) and high >= low
float trueRange = validOHLC ? math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1]))) : na
array<float> baseline = array.new<float>()
array<float> deviations = array.new<float>()
array<float> path = array.new<float>()
int validCount = 0
for i = 0 to baseLength - 1
float x = trueRange[pathLength + 1 + i]
if not na(x)
validCount += 1
array.push(baseline, x)
for i = 0 to pathLength
float x = trueRange[pathLength - i]
if not na(x)
validCount += 1
array.push(path, x)
int totalSlots = baseLength + pathLength + 1
float coverage = float(validCount) / totalSlots
bool calculationReady = validCount == totalSlots and syminfo.mintick > 0
float center = na
float scale = na
float level = na
float speed = na
float reversal = na
float efficiency = na
float pressure = na
bool scaleFloored = false
if calculationReady
center := array.median(baseline)
for x in baseline
array.push(deviations, math.abs(x - center))
float rawScale = 1.4826 * array.median(deviations)
float scaleFloor = math.max(syminfo.mintick, 0.10 * center)
scale := math.max(rawScale, scaleFloor)
scaleFloored := rawScale < scaleFloor
// All path points share one strictly older center and scale, recomputed each bar.
for i = 0 to pathLength
array.set(path, i, (array.get(path, i) - center) / scale)
level := array.median(path)
float travel = 0.0
int flips = 0
int previousSign = 0
for i = 1 to pathLength
float delta = array.get(path, i) - array.get(path, i - 1)
travel += math.abs(delta)
int direction = math.abs(delta) > directionFloor ? (delta > 0 ? 1 : -1) : 0
if direction != 0 and previousSign != 0 and direction != previousSign
flips += 1
// A quiet step breaks adjacency; we do not splice across it.
previousSign := direction
speed := travel / pathLength
reversal := float(flips) / (pathLength - 1)
efficiency := travel > 0 ? math.min(1.0, math.abs(array.last(path) - array.first(path)) / travel) : 0.0
pressure := 100.0 * speed / (speed + speedReference) * (0.25 + 0.40 * reversal + 0.35 * (1.0 - efficiency))
// The preview includes this live bar once. Only confirmed closes enter persistent memory.
var array<float> pressureMemory = array.new<float>()
array<float> previewMemory = array.copy(pressureMemory)
if calculationReady
array.push(previewMemory, pressure)
if array.size(previewMemory) > memoryLength
array.shift(previewMemory)
else
array.clear(previewMemory)
float memory = array.size(previewMemory) > 0 ? array.avg(previewMemory) : na
float evidenceCoverage = coverage * float(array.size(previewMemory)) / memoryLength
bool stateReady = calculationReady and array.size(previewMemory) == memoryLength
var int state = 0
var bool highLevel = false
var int candidate = 0
var int candidateRun = 0
var int quietRun = 0
bool enteredUnstable = false
bool enteredHigh = false
bool restabilized = false
if barstate.isconfirmed
pressureMemory := previewMemory
if not stateReady
state := 0
highLevel := false
candidate := 0
candidateRun := 0
quietRun := 0
else
if level >= levelEntry
highLevel := true
else if level <= levelEntry - levelGap
highLevel := false
bool enterRisk = pressure >= pressureEntry and memory >= pressureEntry
bool releaseRisk = pressure <= pressureExit and memory <= pressureExit
int calmState = highLevel ? 2 : 1
int desired = state
if state == 0
// Unknown cannot be called stable until both current and memory are quiet.
desired := enterRisk ? 3 : releaseRisk ? calmState : 0
else if state == 3
desired := releaseRisk ? 4 : 3
else if state == 4
quietRun := releaseRisk ? math.min(quietRun + 1, settlingBars) : 0
desired := enterRisk ? 3 : quietRun >= settlingBars ? calmState : 4
else
desired := enterRisk ? 3 : calmState
if desired != state
candidateRun := desired == candidate ? candidateRun + 1 : 1
candidate := desired
if candidateRun >= confirmBars
int oldState = state
state := desired
enteredUnstable := state == 3
enteredHigh := state == 2
restabilized := oldState == 4 and (state == 1 or state == 2)
candidateRun := 0
candidate := state
quietRun := 0
else
candidate := state
candidateRun := 0
color stateColor = f_color(state)
plot(pressure, "Live instability pressure (0-100)", color=stateColor, linewidth=3, style=plot.style_linebr)
plot(memory, "Finite pressure memory", color=color.new(chart.fg_color, 35), linewidth=1, style=plot.style_linebr)
pLive = plot(showRibbon ? pressure : na, "Ribbon pressure edge", color=na, display=display.none)
pMemory = plot(showRibbon ? memory : na, "Ribbon memory edge", color=na, display=display.none)
fill(pLive, pMemory, color=color.new(stateColor, 80), title="Observed pressure-memory separation", fillgaps=false)
hline(100.0, "Maximum pressure", color=color.new(waitingColor, 85))
hline(0.0, "Zero pressure", color=color.new(waitingColor, 85))
hline(pressureEntry, "Instability entry threshold", color=color.new(unstableColor, 35), linestyle=hline.style_dashed)
hline(pressureExit, "Quiet release threshold", color=color.new(settlingColor, 35), linestyle=hline.style_dashed)
bgcolor(showBackground and state != 0 ? color.new(stateColor, 94) : na, title="Confirmed state")
plotshape(showEvents and enteredUnstable ? pressure : na, title="Instability confirmed", style=shape.diamond, location=location.absolute, color=unstableColor, text="U", textcolor=chart.fg_color, size=size.tiny)
plotshape(showEvents and enteredHigh ? pressure : na, title="Stable high confirmed", style=shape.triangleup, location=location.absolute, color=highColor, text="H", textcolor=chart.fg_color, size=size.tiny)
plotshape(showEvents and restabilized ? pressure : na, title="Restabilization completed", style=shape.circle, location=location.absolute, color=settlingColor, text="R", textcolor=chart.fg_color, size=size.tiny)
plot(level, "Robust path level", display=display.data_window)
plot(speed, "Path speed (robust units / bar)", display=display.data_window)
plot(100.0 * reversal, "Adjacent flip density (%)", display=display.data_window)
plot(100.0 * efficiency, "Path efficiency (%)", display=display.data_window)
plot(100.0 * evidenceCoverage, "Coverage and memory maturity (%)", display=display.data_window)
plot(state, "Confirmed state (0 waiting, 1 low, 2 high, 3 unstable, 4 settling)", display=display.data_window)
var table lattice = table.new(position.top_right, 2, 8, frame_color=color.new(chart.fg_color, 65), frame_width=1)
if barstate.islast
if showTable
table.cell(lattice, 0, 0, "1 STABLE LOW", bgcolor=state == 1 ? lowColor : chart.bg_color, text_color=state == 1 ? color.white : chart.fg_color, text_size=size.small)
table.cell(lattice, 1, 0, "2 STABLE HIGH", bgcolor=state == 2 ? highColor : chart.bg_color, text_color=state == 2 ? color.white : chart.fg_color, text_size=size.small)
table.cell(lattice, 0, 1, "3 UNSTABLE", bgcolor=state == 3 ? unstableColor : chart.bg_color, text_color=state == 3 ? color.white : chart.fg_color, text_size=size.small)
table.cell(lattice, 1, 1, "4 RE-STABILIZING", bgcolor=state == 4 ? settlingColor : chart.bg_color, text_color=state == 4 ? color.white : chart.fg_color, text_size=size.small)
table.cell(lattice, 0, 2, state == 0 ? "WAITING / CALIBRATING" : "CONFIRMED STATE", text_color=stateColor, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 1, 2, barstate.isconfirmed ? "CLOSE" : "LIVE VALUES / LAST STATE", text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 0, 3, "Pressure / memory", text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 1, 3, f_number(pressure) + " / " + f_number(memory), text_color=stateColor, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 0, 4, "Level / speed", text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 1, 4, f_number(level) + " / " + f_number(speed), text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 0, 5, "Flips / efficiency %", text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 1, 5, f_number(100.0 * reversal) + " / " + f_number(100.0 * efficiency), text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 0, 6, "Coverage / scale floor", text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 1, 6, f_number(100.0 * evidenceCoverage) + "% / " + (calculationReady ? (scaleFloored ? "YES" : "NO") : "--"), text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 0, 7, "Quiet closes / candidate", text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
table.cell(lattice, 1, 7, str.tostring(quietRun) + " / " + str.tostring(candidateRun), text_color=chart.fg_color, bgcolor=chart.bg_color, text_size=size.small)
else
table.clear(lattice, 0, 0, 1, 7)
alertcondition(enteredUnstable, "Instability confirmed", "VoV Lattice: current and remembered pressure confirmed instability on {{ticker}} {{interval}}.")
alertcondition(enteredHigh, "Stable high volatility confirmed", "VoV Lattice: stable high relative volatility confirmed on {{ticker}} {{interval}}.")
alertcondition(restabilized, "Volatility restabilized", "VoV Lattice: the post-release quiet interval completed on {{ticker}} {{interval}}.")