本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Session VWAP Reset Bridge [Pineify]", overlay = true, max_bars_back = 100)
// Independent implementation. Bridge shrinkage alone is never acceptance evidence.
string hours = input.session("0930-1600", "Session hours (exchange timezone)", group = "Session")
string days = input.string("23456", "Session days", options = ["23456", "1234567"], group = "Session")
int maxReferenceHours = input.int(96, "Maximum reference age at next open (hours)", minval = 1, maxval = 168, group = "Session")
int minimumBars = input.int(6, "Minimum current session bars", minval = 2, maxval = 60, group = "Evidence")
float maturityEntry = input.float(0.20, "New volume share to mature", minval = 0.05, maxval = 0.75, step = 0.05, group = "Evidence")
int residenceBars = input.int(6, "Close residence window", minval = 3, maxval = 30, group = "Evidence")
float residenceEntry = input.float(0.70, "Same-side residence to migrate", minval = 0.55, maxval = 1.0, step = 0.05, group = "Evidence")
float migrationEntry = input.float(1.0, "New VWAP displacement to migrate (old sigma)", minval = 0.60, maxval = 4.0, step = 0.10, group = "Evidence")
float oldAnchorEntry = input.float(0.20, "Continued anchor displacement to migrate (old sigma)", minval = 0.05, maxval = 2.0, step = 0.05, group = "Evidence")
float bridgeEntry = input.float(0.35, "Return distance to bridge (old sigma)", minval = 0.10, maxval = 0.50, step = 0.05, group = "Evidence")
int speedBars = input.int(3, "Convergence speed lookback bars", minval = 1, maxval = 20, group = "Evidence")
float minimumSpeed = input.float(0.02, "Minimum return speed (sigma per bar)", minval = 0.001, maxval = 0.50, step = 0.01, group = "Evidence")
int confirmationBars = input.int(2, "Consecutive state candidates", minval = 1, maxval = 5, group = "Evidence")
bool showBridge = input.bool(true, "Maturity-weighted bridge fill", group = "Visuals")
bool showFrozen = input.bool(true, "Frozen prior equilibrium", group = "Visuals")
bool showMarkers = input.bool(true, "Confirmed state markers", group = "Visuals")
bool showPanel = input.bool(true, "Diagnostic panel", group = "Visuals")
int startHour = int(str.tonumber(str.substring(hours, 0, 2)))
int startMinute = int(str.tonumber(str.substring(hours, 2, 4)))
int endHour = int(str.tonumber(str.substring(hours, 5, 7)))
int endMinute = int(str.tonumber(str.substring(hours, 7, 9)))
int startMinuteOfDay = 60 * startHour + startMinute
int endMinuteOfDay = 60 * endHour + endMinute
int nominalMinutes = (endMinuteOfDay - startMinuteOfDay + 1440) % 1440
int durationMinutes = nominalMinutes == 0 ? 1440 : nominalMinutes
int tfSeconds = timeframe.in_seconds()
if barstate.isfirst
if not chart.is_standard or not timeframe.isminutes or tfSeconds < 60 or tfSeconds > 1800
runtime.error("Use standard time-based candles from 1 to 30 minutes.")
if str.length(hours) != 9 or (durationMinutes * 60) % tfSeconds != 0
runtime.error("Use one continuous session with duration divisible by the chart timeframe.")
if bridgeEntry + 0.15 >= 0.70 * migrationEntry
runtime.error("Keep bridge distance + 0.15 below 70% of migration displacement.")
string sessionSpec = hours + ":" + days
int sessionOpenTime = time(timeframe.period, sessionSpec, syminfo.timezone)
int sessionCloseTime = time_close(timeframe.period, sessionSpec, syminfo.timezone)
bool inside = not na(sessionOpenTime)
bool aligned = inside and sessionOpenTime == time and sessionCloseTime == time_close
bool exactStart = inside and hour(time, syminfo.timezone) == startHour and minute(time, syminfo.timezone) == startMinute and second(time, syminfo.timezone) == 0
bool priceOK = not na(open) and not na(high) and not na(low) and not na(close) and high >= math.max(open, close) and low <= math.min(open, close) and high >= low
bool dataOK = priceOK and not na(volume) and volume >= 0
float samplePrice = hlc3
f_update(float w, float m, float m2, float p, float v) =>
float nextWeight = w + v
float nextMean = m
float nextM2 = m2
if v > 0
float delta = w > 0 ? p - m : 0.0
nextMean := w > 0 ? m + v / nextWeight * delta : p
nextM2 := w > 0 ? math.max(0.0, m2 + v * delta * (p - nextMean)) : 0.0
[nextWeight, nextMean, nextM2]
f_number(float x) =>
na(x) ? "--" : str.tostring(x, "#.00")
f_state(int s) =>
switch s
2 => "BRIDGED"
3 => "UP MIGRATION"
-3 => "DOWN MIGRATION"
1 => "UNRESOLVED"
=> "IMMATURE / UNAVAILABLE"
// phase: 0 outside/waiting, 1 valid building, 2 completed, 3 invalid.
var int phase = 0
var int endTime = na
var int lastCloseTime = na
var int bars = 0
var float weight = 0.0
var float mean = na
var float m2 = 0.0
var bool completedEligible = false
var int completedEnd = na
var float completedMean = na
var float completedSigma = na
var float completedWeight = na
var float reference = na
var float referenceScale = na
var float referenceWeight = na
var bool referenceOK = false
var array<float> closeLocations = array.new_float()
var array<float> distances = array.new_float()
var bool separated = false
var bool mature = false
var float newShare = na
var float displacement = na
var float continuedDisplacement = na
var float residence = na
var float speed = na
var int state = 0
var int pending = 0
var int pendingCount = 0
var string diagnostic = "Await one complete observed session"
bool bridgePulse = false
bool upPulse = false
bool downPulse = false
bool maturityLost = false
bool maturityGained = false
bool invalidPulse = false
if barstate.isconfirmed
bool wasMature = mature
int previousPhase = phase
mature := false
if not inside
if phase == 1
completedEligible := false
phase := 0
state := 0
pending := 0
pendingCount := 0
diagnostic := "Outside selected session"
else
if exactStart
referenceOK := completedEligible and not na(completedEnd) and time >= completedEnd and time - completedEnd <= maxReferenceHours * 3600000 and completedWeight > 0 and completedSigma > 0
reference := referenceOK ? completedMean : na
referenceScale := referenceOK ? math.max(completedSigma, syminfo.mintick) : na
referenceWeight := referenceOK ? completedWeight : na
// Consume the candidate: an incomplete intervening session cannot be skipped.
completedEligible := false
endTime := timestamp(syminfo.timezone, year(time, syminfo.timezone), month(time, syminfo.timezone), dayofmonth(time, syminfo.timezone) + (endMinuteOfDay <= startMinuteOfDay ? 1 : 0), endHour, endMinute)
phase := 1
lastCloseTime := time
bars := 0
weight := 0.0
mean := na
m2 := 0.0
separated := false
newShare := na
displacement := na
continuedDisplacement := na
residence := na
speed := na
state := 0
pending := 0
pendingCount := 0
array.clear(closeLocations)
array.clear(distances)
bool validBar = phase == 1 and aligned and dataOK and time == lastCloseTime and time_close <= endTime
if not validBar
phase := 3
completedEligible := false
state := 0
pending := 0
pendingCount := 0
diagnostic := "Invalid: missing start, gap, partial bar or price/volume"
else
[nextWeight, nextMean, nextM2] = f_update(weight, mean, m2, samplePrice, volume)
weight := nextWeight
mean := nextMean
m2 := nextM2
bars += 1
lastCloseTime := time_close
if referenceOK
newShare := weight / (referenceWeight + weight)
displacement := weight > 0 ? (mean - reference) / referenceScale : na
continuedDisplacement := newShare * displacement
array.push(closeLocations, (close - reference) / referenceScale)
array.push(distances, math.abs(displacement))
if array.size(closeLocations) > residenceBars
array.shift(closeLocations)
if array.size(distances) > speedBars + 1
array.shift(distances)
if not na(displacement) and math.abs(displacement) >= migrationEntry
separated := true
speed := na
if array.size(distances) == speedBars + 1
float oldDistance = array.first(distances)
speed := not na(oldDistance) and not na(displacement) ? (oldDistance - math.abs(displacement)) / speedBars : na
int side = not na(displacement) ? (displacement > 0 ? 1 : displacement < 0 ? -1 : 0) : 0
int sameSide = 0
if array.size(closeLocations) == residenceBars
for i = 0 to residenceBars - 1
sameSide += side * array.get(closeLocations, i) > bridgeEntry ? 1 : 0
residence := array.size(closeLocations) == residenceBars ? float(sameSide) / residenceBars : na
mature := bars >= minimumBars and newShare >= maturityEntry and not na(residence) and not na(speed)
int candidate = 0
if mature
candidate := 1
float distanceGate = math.abs(state) == 3 and side == int(math.sign(state)) ? 0.70 * migrationEntry : migrationEntry
float anchorGate = math.abs(state) == 3 and side == int(math.sign(state)) ? 0.70 * oldAnchorEntry : oldAnchorEntry
float residenceGate = math.abs(state) == 3 and side == int(math.sign(state)) ? math.max(0.40, residenceEntry - 0.15) : residenceEntry
bool migrate = math.abs(displacement) >= distanceGate and math.abs(continuedDisplacement) >= anchorGate and residence >= residenceGate
bool bridge = separated and math.abs(displacement) <= (state == 2 ? bridgeEntry + 0.15 : bridgeEntry) and (state == 2 or speed >= minimumSpeed)
candidate := migrate ? 3 * side : bridge ? 2 : 1
if not mature
state := 0
pending := 0
pendingCount := 0
else if candidate == state
pending := candidate
pendingCount := 0
else
pendingCount := candidate == pending ? pendingCount + 1 : 1
pending := candidate
if pendingCount >= confirmationBars
state := candidate
pendingCount := 0
bridgePulse := state == 2
upPulse := state == 3
downPulse := state == -3
diagnostic := mature ? "Confirmed state / developing geometry" : "Await volume, bars and residence/speed coverage"
else
state := 0
diagnostic := "Building reference: no eligible complete prior session"
if time_close == endTime
phase := 2
completedEligible := weight > 0 and bars >= 2 and m2 > 0
completedMean := mean
completedSigma := weight > 0 ? math.sqrt(m2 / weight) : na
completedWeight := weight
completedEnd := endTime
maturityLost := wasMature and not mature
maturityGained := not wasMature and mature
invalidPulse := phase == 3 and previousPhase != 3
// Preview adds the current bar exactly once; persistent accumulation above is close-only.
float liveMean = mean
float liveWeight = weight
bool previewOK = not barstate.isconfirmed and inside and not exactStart and phase == 1 and aligned and dataOK and time == lastCloseTime and time_close <= endTime
if previewOK
[previewWeight, previewMean, previewM2] = f_update(weight, mean, m2, samplePrice, volume)
liveMean := previewMean
liveWeight := previewWeight
bool visible = inside and referenceOK and (phase == 1 or phase == 2) and (barstate.isconfirmed or previewOK) and liveWeight > 0
float liveShare = visible ? liveWeight / (referenceWeight + liveWeight) : na
float continuedMean = visible ? reference + liveShare * (liveMean - reference) : na
float liveDistance = visible ? (liveMean - reference) / referenceScale : na
float liveResetGap = visible ? (liveMean - continuedMean) / referenceScale : na
// Break all three rails on each exact opening bar, including charts without off-session bars.
bool drawRails = visible and not exactStart
color upColor = color.rgb(0, 113, 188)
color downColor = color.rgb(184, 49, 97)
color bridgeColor = color.rgb(0, 123, 107)
color unresolvedColor = color.rgb(161, 96, 0)
color neutralColor = color.rgb(116, 119, 126)
color stateColor = state == 3 ? upColor : state == -3 ? downColor : state == 2 ? bridgeColor : state == 1 ? unresolvedColor : neutralColor
pNew = plot(drawRails ? liveMean : na, "New session VWAP", color = stateColor, linewidth = 3, style = plot.style_linebr)
pContinued = plot(drawRails ? continuedMean : na, "Prior anchor continued VWAP", color = neutralColor, linewidth = 2, style = plot.style_linebr)
plot(drawRails and showFrozen ? reference : na, "Frozen prior equilibrium", color = color.new(neutralColor, 15), linewidth = 1, style = plot.style_linebr)
fill(pNew, pContinued, color = showBridge and drawRails ? color.new(stateColor, int(92 - 50 * liveShare)) : na, title = "Reset bridge / new volume maturity", fillgaps = false)
plot(visible ? 100 * liveShare : na, "New volume share (%)", display = display.data_window)
plot(liveDistance, "New VWAP displacement (old sigma)", display = display.data_window)
plot(visible ? liveShare * liveDistance : na, "Continued anchor displacement (old sigma)", display = display.data_window)
plot(liveResetGap, "Reset gap (old sigma)", display = display.data_window)
plot(visible ? speed : na, "Confirmed convergence speed (sigma/bar)", display = display.data_window)
plot(visible ? 100 * residence : na, "Confirmed same-side residence (%)", display = display.data_window)
plot(visible ? state : na, "Confirmed state code", display = display.data_window)
plotshape(showMarkers and bridgePulse, "Confirmed bridge", shape.diamond, location.belowbar, bridgeColor, text = "B", textcolor = chart.fg_color, size = size.tiny)
plotshape(showMarkers and upPulse, "Confirmed upward migration", shape.triangleup, location.belowbar, upColor, text = "M", textcolor = chart.fg_color, size = size.tiny)
plotshape(showMarkers and downPulse, "Confirmed downward migration", shape.triangledown, location.abovebar, downColor, text = "M", textcolor = chart.fg_color, size = size.tiny)
var table panel = table.new(position.top_right, 2, 7, bgcolor = chart.bg_color, frame_color = neutralColor, frame_width = 1)
if barstate.islast
table.clear(panel, 0, 0, 1, 6)
if showPanel
table.cell(panel, 0, 0, "VWAP RESET BRIDGE", text_color = chart.fg_color)
table.cell(panel, 1, 0, visible ? f_state(state) : "UNAVAILABLE", text_color = visible ? stateColor : chart.fg_color)
table.cell(panel, 0, 1, "New volume %", text_color = chart.fg_color)
table.cell(panel, 1, 1, f_number(100 * liveShare), text_color = chart.fg_color)
table.cell(panel, 0, 2, "New / continued sigma", text_color = chart.fg_color)
table.cell(panel, 1, 2, f_number(liveDistance) + " / " + f_number(liveShare * liveDistance), text_color = chart.fg_color)
table.cell(panel, 0, 3, "Reset gap sigma", text_color = chart.fg_color)
table.cell(panel, 1, 3, f_number(liveResetGap), text_color = chart.fg_color)
table.cell(panel, 0, 4, "Residence % / return speed", text_color = chart.fg_color)
table.cell(panel, 1, 4, visible ? f_number(100 * residence) + " / " + f_number(speed) : "--", text_color = chart.fg_color)
table.cell(panel, 0, 5, "Bars / reference sigma", text_color = chart.fg_color)
table.cell(panel, 1, 5, str.tostring(bars) + " / " + (visible ? f_number(referenceScale) : "--"), text_color = chart.fg_color)
table.cell(panel, 0, 6, "Coverage", text_color = chart.fg_color)
table.cell(panel, 1, 6, previewOK or barstate.isconfirmed ? diagnostic : "Await valid bar close / next exact open", text_color = chart.fg_color)
alertcondition(bridgePulse, "Confirmed reset bridge", "New VWAP returned toward the frozen prior equilibrium with mature volume and confirmed convergence.")
alertcondition(upPulse, "Confirmed upward equilibrium migration", "Mature new and continued VWAPs displaced above the prior equilibrium with same-side close residence.")
alertcondition(downPulse, "Confirmed downward equilibrium migration", "Mature new and continued VWAPs displaced below the prior equilibrium with same-side close residence.")
alertcondition(maturityLost, "Maturity lost", "Confirmed maturity was lost at a session boundary or invalid data bar.")
alertcondition(maturityGained, "Maturity gained", "Confirmed session volume, bar count and evidence coverage are mature.")
alertcondition(invalidPulse, "Session data invalid", "Missing exact start, intra-session gap, partial bar or invalid price/volume blocked the observed session.")