Session Volume Pace Curve [Pineify]

Pineify · study · 163 行 · 点赞 18 · TradingView 原页

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

Pine Script

//@version=6
indicator("Session Volume Pace Curve [Pineify]", shorttitle="Session Volume Pace", overlay=false, max_bars_back=5000)
 
// All historical curves are formed from complete, contiguous sessions only.
string sessionHours = input.session("0930-1600", "Session (exchange time)")
string sessionDays = input.string("23456", "Session days", options=["23456", "1234567"])
int historyLimit = input.int(12, "Complete sessions retained", minval=5, maxval=30)
int minHistory = input.int(5, "Minimum complete sessions", minval=3, maxval=30)
int recentSlots = input.int(3, "Recent interval (bars)", minval=1, maxval=20)
float leadEntry = input.float(1.15, "Ahead entry ratio", minval=1.01, maxval=3.0, step=0.05)
float lagEntry = input.float(0.85, "Behind entry ratio", minval=0.1, maxval=0.99, step=0.05)
float impulseEntry = input.float(0.10, "Pace change entry", minval=0.01, maxval=1.0, step=0.01)
bool showCorridor = input.bool(true, "Show interquartile corridor")
bool showImpulse = input.bool(true, "Show recent pace contribution")
bool showBackground = input.bool(false, "Show state background")
bool showTable = input.bool(true, "Show status table")
 
int startHour = int(str.tonumber(str.substring(sessionHours, 0, 2)))
int startMinute = int(str.tonumber(str.substring(sessionHours, 2, 4)))
int endHour = int(str.tonumber(str.substring(sessionHours, 5, 7)))
int endMinute = int(str.tonumber(str.substring(sessionHours, 7, 9)))
int sessionMins = (endHour * 60 + endMinute) - (startHour * 60 + startMinute)
int chartMins = timeframe.isminutes ? timeframe.multiplier : 0
bool configOK = chartMins >= 1 and chartMins <= 30 and sessionMins > 0 and sessionMins <= 1440 and sessionMins % math.max(chartMins, 1) == 0 and minHistory <= historyLimit
int slots = configOK ? int(sessionMins / chartMins) : 0
int slotMs = chartMins * 60000
bool inSession = configOK and not na(time(timeframe.period, sessionHours + ":" + sessionDays, syminfo.timezone))
int startTime = timestamp(syminfo.timezone, year, month, dayofmonth, startHour, startMinute)
int slot = inSession ? int(math.floor((time - startTime) / slotMs)) : -1
bool aligned = inSession and slot >= 0 and slot < slots and time == startTime + slot * slotMs and time_close == startTime + (slot + 1) * slotMs
 
var array<float> completed = array.new_float()
var array<float> current = array.new_float()
var int count = 0
var int writeIndex = 0
var int activeStart = na
var int lastSlot = -1
var float committed = 0.0
var bool intact = false
// States: 0 unavailable, 1 in line, 2 ahead, 3 behind, 4 fading, 5 reaccelerating.
var int state = 0
var bool sawFade = false
if barstate.isfirst and configOK
    completed := array.new_float(historyLimit * slots, na)
    current := array.new_float(slots, na)
 
bool newSession = inSession and (na(activeStart) or startTime != activeStart)
if newSession
    activeStart := startTime
    lastSlot := -1
    committed := 0.0
    intact := slot == 0 and aligned
    state := 0
    sawFade := false
    array.fill(current, na)
 
int previousState = state
bool contiguous = inSession and intact and aligned and slot == lastSlot + 1 and not na(volume) and volume >= 0
float liveCumulative = contiguous ? committed + volume : na
array<float> cumulativeSamples = array.new_float()
array<float> recentSamples = array.new_float()
if contiguous and count > 0
    for h = 0 to count - 1
        float hNow = array.get(completed, h * slots + slot)
        array.push(cumulativeSamples, hNow)
        if slot >= recentSlots
            float hPast = array.get(completed, h * slots + slot - recentSlots)
            array.push(recentSamples, hNow - hPast)
if array.size(cumulativeSamples) > 1
    array.sort(cumulativeSamples, order.ascending)
if array.size(recentSamples) > 1
    array.sort(recentSamples, order.ascending)
float medianCumulative = array.size(cumulativeSamples) > 0 ? array.median(cumulativeSamples) : na
float lowerCumulative = array.size(cumulativeSamples) > 0 ? array.percentile_linear_interpolation(cumulativeSamples, 25) : na
float upperCumulative = array.size(cumulativeSamples) > 0 ? array.percentile_linear_interpolation(cumulativeSamples, 75) : na
float expectedRecent = array.size(recentSamples) > 0 ? array.median(recentSamples) : na
float earlier = contiguous and slot >= recentSlots ? array.get(current, slot - recentSlots) : na
float actualRecent = not na(earlier) ? liveCumulative - earlier : na
bool supported = contiguous and count >= minHistory and slot >= recentSlots and not na(medianCumulative) and medianCumulative > 0 and not na(expectedRecent) and expectedRecent > 0 and not na(actualRecent)
float cumulativeRatio = supported ? liveCumulative / medianCumulative : na
float recentRatio = supported ? actualRecent / expectedRecent : na
float remaining = supported ? float(slots - slot - 1) / slots : na
float impulse = supported ? (recentRatio - cumulativeRatio) * remaining : na
float leadExit = 1.0 + (leadEntry - 1.0) * 0.4
float lagExit = 1.0 - (1.0 - lagEntry) * 0.4
float impulseExit = impulseEntry * 0.3
bool enteredAhead = false
bool enteredFading = false
bool enteredReaccel = false
bool lostSupport = false
 
if barstate.isconfirmed and inSession
    if supported
        bool fading = (impulse <= -impulseEntry and cumulativeRatio >= leadExit) or (state == 4 and impulse < -impulseExit and cumulativeRatio >= 1.0)
        bool reaccelerating = (sawFade and impulse >= impulseEntry) or (state == 5 and impulse > impulseExit)
        if fading
            state := 4
            sawFade := true
        else if reaccelerating
            state := 5
            sawFade := false
        else if cumulativeRatio >= leadEntry or (state == 2 and cumulativeRatio >= leadExit)
            state := 2
        else if cumulativeRatio <= lagEntry or (state == 3 and cumulativeRatio <= lagExit)
            state := 3
        else
            state := 1
    else
        state := 0
    enteredAhead := state == 2 and previousState != 2
    enteredFading := state == 4 and previousState != 4
    enteredReaccel := state == 5 and previousState != 5
    lostSupport := previousState != 0 and state == 0
    if contiguous
        committed := liveCumulative
        lastSlot := slot
        array.set(current, slot, committed)
        if slot == slots - 1
            for s = 0 to slots - 1
                array.set(completed, writeIndex * slots + s, array.get(current, s))
            writeIndex := (writeIndex + 1) % historyLimit
            count := math.min(count + 1, historyLimit)
    else
        intact := false
 
color stateColor = switch state
    2 => color.rgb(0, 148, 138)
    3 => color.rgb(190, 90, 30)
    4 => color.rgb(196, 111, 0)
    5 => color.rgb(38, 110, 210)
    => color.rgb(106, 110, 121)
int alpha = supported ? int(math.round(35.0 * (1.0 - float(count) / historyLimit))) : 0
float currentPercent = supported ? 100.0 * cumulativeRatio : na
float lowerPercent = supported and showCorridor ? 100.0 * lowerCumulative / medianCumulative : na
float upperPercent = supported and showCorridor ? 100.0 * upperCumulative / medianCumulative : na
pCurrent = plot(currentPercent, "Current cumulative / median (%)", color=color.new(stateColor, alpha), linewidth=3, style=plot.style_linebr)
plot(supported ? 100.0 : na, "Historical median (%)", color=color.rgb(99, 103, 113), linewidth=2, style=plot.style_linebr)
pLow = plot(lowerPercent, "Historical 25th percentile (%)", color=color.new(color.rgb(110, 118, 128), 75), style=plot.style_linebr)
pHigh = plot(upperPercent, "Historical 75th percentile (%)", color=color.new(color.rgb(110, 118, 128), 75), style=plot.style_linebr)
fill(pLow, pHigh, color=color.new(color.rgb(110, 118, 128), 87), title="Historical interquartile corridor")
plot(showImpulse and supported ? impulse * 100.0 : na, "Remaining-weighted recent pace (percentage points)", style=plot.style_columns, color=color.new(impulse >= 0 ? color.rgb(0, 148, 138) : color.rgb(190, 90, 30), 35))
hline(0, "Zero recent contribution", color=color.new(color.gray, 75))
bgcolor(showBackground and supported ? color.new(stateColor, 93) : na, title="Confirmed pace state")
 
var table dashboard = table.new(position.top_right, 2, 4, bgcolor=color.new(color.rgb(20, 24, 31), 8), frame_color=color.new(color.gray, 50), frame_width=1)
if barstate.islast
    string stateText = not configOK ? "Check session / timeframe" : not inSession ? "Outside session" : not contiguous ? "Incomplete session" : not supported ? "Building history / interval" : state == 2 ? "Ahead" : state == 3 ? "Behind" : state == 4 ? "Fading" : state == 5 ? "Reaccelerating" : "In line"
    if showTable
        table.cell(dashboard, 0, 0, "SESSION PACE", text_color=color.white, text_size=size.small)
        table.cell(dashboard, 1, 0, stateText, text_color=color.white, text_size=size.small)
        table.cell(dashboard, 0, 1, "Complete sessions", text_color=color.silver, text_size=size.small)
        table.cell(dashboard, 1, 1, str.tostring(count) + " / " + str.tostring(historyLimit), text_color=color.white, text_size=size.small)
        table.cell(dashboard, 0, 2, "Current / median", text_color=color.silver, text_size=size.small)
        table.cell(dashboard, 1, 2, supported ? str.tostring(currentPercent, "#.0") + "%" : "--", text_color=color.white, text_size=size.small)
        table.cell(dashboard, 0, 3, "Remaining / pace", text_color=color.silver, text_size=size.small)
        table.cell(dashboard, 1, 3, supported ? str.tostring(remaining * 100.0, "#.0") + "% / " + str.tostring(impulse * 100.0, "#.0") : "--", text_color=color.white, text_size=size.small)
    else
        table.clear(dashboard, 0, 0, 1, 3)
 
alertcondition(enteredAhead, "Session pace ahead", "Confirmed session volume pace entered the ahead state.")
alertcondition(enteredFading, "Session pace fading", "Confirmed session volume pace entered the fading state.")
alertcondition(enteredReaccel, "Session pace reaccelerating", "Confirmed session volume pace reaccelerated after fading.")
alertcondition(lostSupport, "Session pace support lost", "A confirmed session pace reading lost valid data support.")

← 返回列表