本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Volatility Shock Memory Curve [Pineify]", shorttitle="Shock Memory [Pineify]", overlay=false, max_bars_back=600, precision=1)
// Independent event study. The exponential corridor is a reference scenario,
// not a forecast, fitted model, confidence interval, or price direction signal.
string detectionGroup = "1. Shock detection"
int baselineLength = input.int(60, "Prior true-range samples", minval=20, maxval=200, group=detectionGroup)
float scaleFloor = input.float(0.15, "Scale floor / prior median", minval=0.05, maxval=1.0, step=0.05, group=detectionGroup)
float shockThreshold = input.float(4.0, "Shock threshold (robust units)", minval=2.0, maxval=12.0, step=0.25, group=detectionGroup)
string memoryGroup = "2. Event memory"
int memoryLength = input.int(5, "Residual smoothing length", minval=1, maxval=20, group=memoryGroup)
int referenceHalfLife = input.int(8, "Reference half-life (bars)", minval=2, maxval=80, group=memoryGroup)
int observationLimit = input.int(120, "Maximum event age (bars)", minval=20, maxval=500, group=memoryGroup)
int recentLength = input.int(5, "Recent residual samples", minval=2, maxval=20, group=memoryGroup)
float recoveryLevel = input.float(0.12, "Normalization residual ratio", minval=0.02, maxval=0.20, step=0.02, group=memoryGroup)
float persistenceMargin = input.float(0.25, "Persistence margin above normalization", minval=0.10, maxval=1.0, step=0.05, group=memoryGroup)
int confirmationBars = input.int(3, "Consecutive confirmation closes", minval=1, maxval=10, group=memoryGroup)
string visualGroup = "3. Visual layers"
bool showCorridor = input.bool(true, "Half-life reference corridor", group=visualGroup)
bool showResidual = input.bool(true, "Raw residual / memory gap", group=visualGroup)
bool showBackground = input.bool(false, "Confirmed phase background", group=visualGroup)
bool showEvents = input.bool(true, "Event markers", group=visualGroup)
bool showSummary = input.bool(true, "Event summary", group=visualGroup)
// Strict contiguous coverage: no fallback TR on a missing preceding close.
bool ohlcValid = not na(open) and not na(high) and not na(low) and not na(close) and not na(close[1]) and high >= low and high >= math.max(open, close) and low <= math.min(open, close)
float trueRange = ohlcValid ? math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1]))) : na
array<float> priorRanges = array.new<float>()
bool baselineValid = bar_index >= baselineLength + 1
for i = 1 to baselineLength
float sample = trueRange[i]
if na(sample)
baselineValid := false
else
array.push(priorRanges, sample)
float priorCenter = na
float priorScale = na
if baselineValid and array.size(priorRanges) == baselineLength
priorCenter := array.median(priorRanges)
array<float> deviations = array.new<float>()
for i = 0 to baselineLength - 1
array.push(deviations, math.abs(array.get(priorRanges, i) - priorCenter))
priorScale := math.max(1.4826 * array.median(deviations), math.max(priorCenter * scaleFloor, syminfo.mintick))
bool coverage = baselineValid and ohlcValid and not na(priorCenter) and priorCenter > 0 and not na(priorScale) and priorScale > 0
float robustScore = coverage ? (trueRange - priorCenter) / priorScale : na
// State codes: 0 baseline, 1 shock, 2 cooling, 3 persistent,
// 4 normalized (terminal), 5 expired (terminal), 6 unavailable.
var bool active = false
var bool armed = true
var bool coverageSeen = false
var bool lastCoverage = false
var int phase = 6
var int age = 0
var int quietCloses = 0
var int candidate = 0
var int candidateCloses = 0
var float frozenCenter = na
var float frozenScale = na
var float initialExcess = na
var float initialScore = na
var float memory = na
var float residual = na
var float recentResidual = na
var float decayRate = na
var float referenceFast = na
var float referenceMid = na
var float referenceSlow = na
var float scoreSnapshot = na
var array<float> recentSamples = array.new<float>()
bool newShock = false
bool persistentEvent = false
bool coolingEvent = false
bool normalizedEvent = false
bool expiredEvent = false
bool coverageLost = false
bool coverageRestored = false
if barstate.isconfirmed
coverageLost := coverageSeen and lastCoverage and not coverage
coverageRestored := coverageSeen and not lastCoverage and coverage
coverageSeen := true
lastCoverage := coverage
scoreSnapshot := robustScore
if not coverage
active := false
armed := false
phase := 6
age := 0
quietCloses := 0
candidate := 0
candidateCloses := 0
frozenCenter := na
frozenScale := na
initialExcess := na
initialScore := na
memory := na
residual := na
recentResidual := na
decayRate := na
referenceFast := na
referenceMid := na
referenceSlow := na
array.clear(recentSamples)
else if active
age += 1
// Frozen event denominator never absorbs subsequent high ranges.
residual := math.max(0.0, trueRange - frozenCenter) / initialExcess
float priorMemory = memory
memory += (2.0 / (memoryLength + 1.0)) * (residual - memory)
decayRate := priorMemory > 0 ? 1.0 - memory / priorMemory : na
array.push(recentSamples, residual)
if array.size(recentSamples) > recentLength
array.shift(recentSamples)
recentResidual := array.avg(recentSamples)
referenceFast := math.pow(0.5, age / (referenceHalfLife * 0.5))
referenceMid := math.pow(0.5, age / float(referenceHalfLife))
referenceSlow := math.pow(0.5, age / (referenceHalfLife * 2.0))
bool quiet = residual <= recoveryLevel and memory <= recoveryLevel
quietCloses := quiet ? quietCloses + 1 : 0
if quietCloses >= confirmationBars
phase := 4
active := false
armed := false
normalizedEvent := true
candidate := 0
candidateCloses := 0
else if age >= observationLimit
phase := 5
active := false
armed := false
expiredEvent := true
candidate := 0
candidateCloses := 0
else
float recentGate = recoveryLevel + persistenceMargin * (phase == 3 ? 0.5 : 1.0)
float referenceGate = phase == 3 ? referenceMid : referenceSlow
bool sustained = array.size(recentSamples) == recentLength and recentResidual >= recentGate and memory >= referenceGate
int target = sustained ? 3 : 2
if phase == 1
phase := 2
if target == phase
candidate := 0
candidateCloses := 0
else
if candidate == target
candidateCloses += 1
else
candidate := target
candidateCloses := 1
if candidateCloses >= confirmationBars
persistentEvent := target == 3
coolingEvent := target == 2
phase := target
candidate := 0
candidateCloses := 0
else
phase := 0
memory := na
residual := na
recentResidual := na
decayRate := na
referenceFast := na
referenceMid := na
referenceSlow := na
// Rearm only outside an event after a quiet rolling-baseline score.
if robustScore <= 1.0
armed := true
if armed and robustScore >= shockThreshold
active := true
armed := false
newShock := true
phase := 1
age := 0
frozenCenter := priorCenter
frozenScale := priorScale
initialExcess := trueRange - priorCenter
initialScore := robustScore
memory := 1.0
residual := 1.0
recentResidual := na
decayRate := na
referenceFast := 1.0
referenceMid := 1.0
referenceSlow := 1.0
quietCloses := 0
candidate := 0
candidateCloses := 0
// Entry spike is excluded from recent persistence evidence.
array.clear(recentSamples)
color shockColor = color.rgb(193, 112, 0)
color coolingColor = color.rgb(0, 133, 169)
color persistentColor = color.rgb(153, 77, 204)
color normalColor = color.rgb(25, 145, 100)
color phaseColor = phase == 1 ? shockColor : phase == 2 ? coolingColor : phase == 3 ? persistentColor : phase == 4 ? normalColor : chart.fg_color
bool eventVisible = active or phase == 4 or phase == 5
float memoryPercent = eventVisible ? 100.0 * memory : na
float rawPercent = eventVisible ? 100.0 * residual : na
float haloHigh = eventVisible ? math.max(memoryPercent, rawPercent) : na
float haloLow = eventVisible ? math.min(memoryPercent, rawPercent) : na
plot(memoryPercent, "Shock memory (%)", color=phaseColor, linewidth=3, style=plot.style_linebr)
fastPlot = plot(showCorridor and eventVisible ? 100.0 * referenceFast : na, "Fast half-life reference", color=color.new(chart.fg_color, 70), style=plot.style_linebr)
slowPlot = plot(showCorridor and eventVisible ? 100.0 * referenceSlow : na, "Slow half-life reference", color=color.new(chart.fg_color, 55), style=plot.style_linebr)
plot(showCorridor and eventVisible ? 100.0 * referenceMid : na, "Central half-life reference", color=color.new(chart.fg_color, 40), linewidth=1, style=plot.style_linebr)
fill(fastPlot, slowPlot, color=color.new(chart.fg_color, 93), title="Reference scenarios (not probability)")
highPlot = plot(showResidual ? haloHigh : na, "Residual gap upper", color=na, style=plot.style_linebr)
lowPlot = plot(showResidual ? haloLow : na, "Residual gap lower", color=na, style=plot.style_linebr)
fill(highPlot, lowPlot, color=rawPercent >= memoryPercent ? color.new(shockColor, 82) : color.new(coolingColor, 84), title="Actual residual minus smoothed memory")
plot(showResidual ? rawPercent : na, "Unsmoothed residual (%)", color=color.new(phaseColor, 35), style=plot.style_circles, linewidth=1)
hline(100, "Initial shock excess = 100%", color=color.new(chart.fg_color, 70), linestyle=hline.style_dotted)
hline(0, "Frozen baseline", color=color.new(chart.fg_color, 60))
plot(eventVisible ? recoveryLevel * 100.0 : na, "Normalization gate", color=color.new(normalColor, 55), style=plot.style_linebr)
bgcolor(showBackground and eventVisible ? color.new(phaseColor, 94) : na, title="Confirmed event phase")
plotshape(showEvents and newShock ? memoryPercent : na, title="New shock", style=shape.diamond, location=location.absolute, color=shockColor, text="S", textcolor=chart.fg_color, size=size.tiny)
plotshape(showEvents and persistentEvent ? memoryPercent : na, title="Persistent memory", style=shape.square, location=location.absolute, color=persistentColor, text="P", textcolor=chart.fg_color, size=size.tiny)
plotshape(showEvents and normalizedEvent ? memoryPercent : na, title="Normalization confirmed", style=shape.circle, location=location.absolute, color=normalColor, text="N", textcolor=chart.fg_color, size=size.tiny)
plotshape(showEvents and expiredEvent ? memoryPercent : na, title="Observation expired", style=shape.xcross, location=location.absolute, color=chart.fg_color, text="X", textcolor=chart.fg_color, size=size.tiny)
plot(eventVisible ? recentResidual * 100.0 : na, "Recent raw residual mean (%)", display=display.data_window)
plot(eventVisible ? decayRate * 100.0 : na, "Realized one-bar memory decay (%)", display=display.data_window)
plot(scoreSnapshot, "Rolling robust TR score", display=display.data_window)
plot(eventVisible ? age : na, "Event age (bars)", display=display.data_window)
f_number(float value, string suffix) =>
na(value) ? "n/a" : str.tostring(value, "#.##") + suffix
var table summary = table.new(position.top_right, 2, 9, border_width=0)
if barstate.islast
if showSummary
string phaseName = phase == 0 ? (armed ? "Baseline / armed" : "Baseline / waiting") : phase == 1 ? "Shock" : phase == 2 ? "Cooling" : phase == 3 ? "Persistent" : phase == 4 ? "Normalized" : phase == 5 ? "Expired, unresolved" : "Coverage unavailable"
table.cell(summary, 0, 0, "Shock memory", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 0, phaseName, text_color=phaseColor, bgcolor=chart.bg_color)
table.cell(summary, 0, 1, "Age / limit", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 1, eventVisible ? str.tostring(age) + " / " + str.tostring(observationLimit) : "n/a", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 0, 2, "Memory / raw", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 2, f_number(memoryPercent, "%") + " / " + f_number(rawPercent, "%"), text_color=phaseColor, bgcolor=chart.bg_color)
table.cell(summary, 0, 3, "Recent residual", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 3, f_number(eventVisible ? recentResidual * 100.0 : na, "%"), text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 0, 4, "Decay (+ = lower)", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 4, f_number(eventVisible ? decayRate * 100.0 : na, "%"), text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 0, 5, "Frozen TR / scale", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 5, eventVisible ? f_number(frozenCenter, "") + " / " + f_number(frozenScale, "") : "n/a", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 0, 6, "Initial excess / z", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 6, eventVisible ? f_number(initialExcess, "") + " / " + f_number(initialScore, "") : "n/a", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 0, 7, "Reference only", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 7, "No fitted forecast", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 0, 8, "Updates", text_color=chart.fg_color, bgcolor=chart.bg_color)
table.cell(summary, 1, 8, "Confirmed closes", text_color=chart.fg_color, bgcolor=chart.bg_color)
else
table.clear(summary, 0, 0, 1, 8)
alertcondition(newShock, "Confirmed volatility shock", "New confirmed volatility shock; event baseline and initial excess frozen.")
alertcondition(persistentEvent, "Persistent volatility memory", "Recent residual and smoothed memory confirmed persistent relative to reference decay.")
alertcondition(coolingEvent, "Cooling resumed", "Confirmed persistent volatility memory returned to cooling.")
alertcondition(normalizedEvent, "Volatility normalized", "Raw residual and smoothed memory both stayed below the frozen-baseline recovery gate.")
alertcondition(expiredEvent, "Shock observation expired", "Observation limit reached without confirmed normalization; this is not recovery.")
alertcondition(coverageLost, "True-range coverage lost", "Contiguous valid OHLC / baseline coverage lost; event aborted without a recovery signal.")
alertcondition(coverageRestored, "True-range coverage restored", "Contiguous valid OHLC / baseline coverage restored; rearming still requires a quiet robust score.")