RTH Range Projector + Time-Matched RVOL

gurwinderiitr · study · 426 行 · 点赞 8 · TradingView 原页

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

Pine Script

//@version=6
indicator("RTH Range Projector + Time-Matched RVOL", "RTH Range+RVOL", overlay = true, max_lines_count = 20, max_labels_count = 20)
 
// ================ Inputs ================
g_calc = "Daily range"
rangeMethod  = input.string("High-Low", "Range method", options = ["High-Low", "True Range"], group = g_calc, display = display.data_window,
     tooltip = "High-Low: session high minus session low (average daily range).\nTrue Range: also counts the gap from the prior session's close.")
rangeLength  = input.int(14,    "Range length (days)",       minval = 1,   group = g_calc, display = display.data_window)
innerPct     = input.float(0.8, "Inner line % of range",     minval = 0.0, maxval = 1.0, step = 0.05, group = g_calc, display = display.data_window)
orLookback   = input.int(20,    "Opening-range avg (days)",  minval = 1,   group = g_calc, display = display.data_window)
sessionStr   = input.session("0930-1600", "Regular Trading Hours", group = g_calc, display = display.data_window)
tz           = input.string("America/New_York", "Timezone", group = g_calc, display = display.data_window)
 
g_vol = "Relative volume"
rvolLookback = input.int(20, "Intraday RVOL avg (days)", minval = 1, maxval = 50, group = g_vol, display = display.data_window)
pmLookback   = input.int(20, "Pre-mkt RVOL avg (days)",  minval = 1, maxval = 50, group = g_vol, display = display.data_window)
 
g_disp = "Display"
showLines    = input.bool(true, "Show projection lines",            group = g_disp, display = display.data_window)
show80       = input.bool(true, "  • Show inner line",              group = g_disp, display = display.data_window)
show100      = input.bool(true, "  • Show full-range line",         group = g_disp, display = display.data_window)
show30       = input.bool(true, "  • Show 30m-OR line",             group = g_disp, display = display.data_window)
showLabels   = input.bool(true, "Show price labels on lines",       group = g_disp, display = display.data_window)
showTable    = input.bool(true, "Show info table",                  group = g_disp, display = display.data_window)
tablePosStr  = input.string("top_right", "Table position",
     options = ["top_right", "top_left", "bottom_right", "bottom_left", "middle_right"], group = g_disp, display = display.data_window)
 
g_style = "Style"
color80      = input.color(#f59e0b, "Inner line color", group = g_style, display = display.data_window)
color100     = input.color(#ef4444, "Full-range line color", group = g_style, display = display.data_window)
color30      = input.color(#14b8a6, "30m-OR line color", group = g_style, display = display.data_window)
style80Str   = input.string("dashed", "Inner line style", options = ["solid", "dashed", "dotted"], group = g_style, display = display.data_window)
style100Str  = input.string("solid",  "Full-range line style", options = ["solid", "dashed", "dotted"], group = g_style, display = display.data_window)
style30Str   = input.string("dotted", "30m-OR line style", options = ["solid", "dashed", "dotted"], group = g_style, display = display.data_window)
lineWidth    = input.int(2, "Line width", minval = 1, maxval = 5, group = g_style, display = display.data_window)
 
MAXSLOT       = 1440   // time slots per day kept in the RVOL profiles (one per minute at 1m)
MIN_RVOL_DAYS = 5      // RVOL shows "—" until at least this many days of history exist
 
// ================ Guards ================
if not timeframe.isintraday
    runtime.error("Please apply this indicator on an intraday timeframe (e.g., 1m, 5m).")
 
// ================ Helpers ================
lineStyleFrom(s) =>
    switch s
        "dashed" => line.style_dashed
        "dotted" => line.style_dotted
        =>          line.style_solid
 
rvolColor(x) =>
    na(x) ? color.gray : x >= 1.5 ? color.red : x >= 1.0 ? color.orange : x >= 0.5 ? color.yellow : #22c55e
 
tablePos = switch tablePosStr
    "top_right"    => position.top_right
    "top_left"     => position.top_left
    "bottom_right" => position.bottom_right
    "bottom_left"  => position.bottom_left
    "middle_right" => position.middle_right
    =>                position.top_right
 
tfMin   = math.max(1, int(timeframe.in_seconds() / 60))
openMin = int(str.tonumber(str.substring(sessionStr, 0, 2))) * 60 + int(str.tonumber(str.substring(sessionStr, 2, 4)))
 
minuteOfDay(t) => hour(t, tz) * 60 + minute(t, tz)
 
// Slots are measured from the scheduled RTH open (not from the first bar that printed),
// so days with missing bars still line up by clock time.
rthSlot(t) =>
    d = minuteOfDay(t) - openMin
    int((d < 0 ? d + 1440 : d) / tfMin)
 
pmSlot(t) => int(minuteOfDay(t) / tfMin)
 
// ================ Time-of-day volume profile ================
// Keeps, for each of the last N days, cumulative volume at every time slot.
// RVOL at slot k = today's cumulative volume / average of past days' cumulative volume at slot k.
type Profile
    matrix<float> hist              // [day][slot] cumulative volume through that slot
    array<int>    lastSlot          // last slot reached by each stored day (-1 = empty row)
    array<float>  total             // final cumulative volume of each stored day
    array<float>  today             // today's cumulative volume by slot (forward-filled over missing bars)
    int           cur   = -1        // highest slot written today
    float         cum   = 0.0
    int           row   = -1
    bool          valid = false     // false for the partial first day on the chart
 
newProfile(int days) =>
    Profile.new(matrix.new<float>(days, MAXSLOT, na), array.new<int>(days, -1), array.new<float>(days, na), array.new<float>(MAXSLOT, na))
 
method startDay(Profile p, bool valid) =>
    array.fill(p.today, na)
    p.cur   := -1
    p.cum   := 0.0
    p.valid := valid
 
method addBar(Profile p, int slot, float vol) =>
    p.cum := p.cum + nz(vol)
    if slot >= 0 and slot < MAXSLOT
        if p.cur >= 0 and slot > p.cur + 1
            for k = p.cur + 1 to slot - 1
                array.set(p.today, k, p.cum - nz(vol))
        array.set(p.today, slot, p.cum)
        p.cur := math.max(p.cur, slot)
 
method closeDay(Profile p) =>
    if p.valid and p.cur >= 0
        p.row := (p.row + 1) % matrix.rows(p.hist)
        for k = 0 to MAXSLOT - 1
            matrix.set(p.hist, p.row, k, array.get(p.today, k))
        array.set(p.lastSlot, p.row, p.cur)
        array.set(p.total, p.row, p.cum)
 
// Average past cumulative volume at `slot`, over stored days that reached it. Returns [avg, days].
method expectedAt(Profile p, int slot) =>
    float s = 0.0
    int   c = 0
    if slot >= 0 and slot < MAXSLOT
        for r = 0 to matrix.rows(p.hist) - 1
            if array.get(p.lastSlot, r) >= slot
                s += nz(matrix.get(p.hist, r, slot))   // na = no volume yet that day
                c += 1
    [c > 0 ? s / c : na, c]
 
// Average full-day volume over stored days. Returns [avg, days].
method avgTotal(Profile p) =>
    float s = 0.0
    int   c = 0
    for r = 0 to array.size(p.total) - 1
        v = array.get(p.total, r)
        if not na(v)
            s += v
            c += 1
    [c > 0 ? s / c : na, c]
 
// ================ Session detection ================
inSession = not na(time(timeframe.period, sessionStr, tz))
var bool prevInSession = false
var int  lastSessDay   = na
// A trading-day change while still "in session" is also a new session: with extended hours
// off, 15:59 is followed directly by the next day's 09:30.
sessionStart  = inSession and (not prevInSession or time_tradingday != lastSessDay)
sessionClosed = prevInSession and (not inSession or sessionStart)   // bar [1] was the last bar of a session
prevInSession := inSession
if inSession
    lastSessDay := time_tradingday
 
pmNow = session.ispremarket
var bool prevPm    = false
var int  lastPmDay = na
pmStart = pmNow and (not prevPm or time_tradingday != lastPmDay)
pmEnd   = prevPm and (not pmNow or pmStart)
prevPm := pmNow
if pmNow
    lastPmDay := time_tradingday
 
orTfOk = timeframe.in_seconds() <= 1800
var float sessOpenTime = na
orActive = inSession and orTfOk and (sessionStart or time - sessOpenTime < 30 * 60 * 1000)
var bool prevOrActive = false
orEnd = prevOrActive and (not orActive or sessionStart)
prevOrActive := orActive
 
// ================ State ================
var bool  sessValid    = false   // false for the partial first session on the chart
var float sessHigh     = na
var float sessLow      = na
var float orHigh       = na
var float orLow        = na
var float todayOR      = na      // today's first-30-min range (na until 30 min elapse)
var float prevRthClose = na
var float gapR         = na      // today's gap in units of the average range
var float rthRvolFinal = na      // last completed session: total volume / average total
var float pmRvolFinal  = na      // last completed pre-market: total volume / average total
 
var array<float> dailyRanges = array.new<float>()
var array<float> orRanges    = array.new<float>()
var Profile      rthP        = newProfile(rvolLookback)
var Profile      pmP         = newProfile(pmLookback)
 
// ================ 1) Close out whatever just ended ================
// Runs before the resets below, so it still sees the finished session's values.
if sessionClosed
    if sessValid
        dr = rangeMethod == "True Range" and not na(prevRthClose) ?
             math.max(sessHigh, prevRthClose) - math.min(sessLow, prevRthClose) : sessHigh - sessLow
        if not na(dr) and dr > 0
            array.push(dailyRanges, dr)
            while array.size(dailyRanges) > rangeLength
                array.shift(dailyRanges)
    [avgT, nT] = rthP.avgTotal()
    rthRvolFinal := nT >= math.min(MIN_RVOL_DAYS, rvolLookback) and avgT > 0 ? rthP.cum / avgT : na
    rthP.closeDay()
    prevRthClose := close[1]
 
if orEnd and sessValid
    rng = orHigh - orLow
    if not na(rng) and rng > 0
        todayOR := rng
        array.push(orRanges, rng)
        while array.size(orRanges) > orLookback
            array.shift(orRanges)
 
if pmEnd
    [avgT, nT] = pmP.avgTotal()
    pmRvolFinal := nT >= math.min(MIN_RVOL_DAYS, pmLookback) and avgT > 0 ? pmP.cum / avgT : na
    pmP.closeDay()
 
rangeReady  = array.size(dailyRanges) == rangeLength
rangeAvg    = rangeReady ? array.avg(dailyRanges) : na
orReady     = array.size(orRanges) == orLookback
avg30mRange = array.size(orRanges) > 0 ? array.avg(orRanges) : na
 
// ================ 2) Start / update the current session ================
if sessionStart
    sessValid    := bar_index > 0
    sessHigh     := high
    sessLow      := low
    sessOpenTime := time
    todayOR      := na
    gapR         := not na(prevRthClose) and rangeReady and rangeAvg > 0 ? (open - prevRthClose) / rangeAvg : na
    rthP.startDay(sessValid)
else if inSession
    sessHigh := math.max(sessHigh, high)
    sessLow  := math.min(sessLow,  low)
 
if orActive
    orHigh := sessionStart ? high : math.max(orHigh, high)
    orLow  := sessionStart ? low  : math.min(orLow,  low)
 
if inSession
    rthP.addBar(rthSlot(time), volume)
 
if pmStart
    pmP.startDay(bar_index > 0)
if pmNow
    pmP.addBar(pmSlot(time), volume)
 
// ================ Level calculations ================
projectionActive = inSession and rangeReady and not na(sessLow)
level80      = projectionActive ? sessLow + rangeAvg * innerPct : na
level100     = projectionActive ? sessLow + rangeAvg            : na
level30      = projectionActive and orReady ? sessLow + avg30mRange : na
rangeUsedPct = projectionActive and rangeAvg > 0 ? (sessHigh - sessLow) / rangeAvg * 100.0 : na
innerTag     = str.tostring(innerPct * 100, "#") + "%"
 
// ================ Line / label objects ================
var line  lineObj80   = na
var line  lineObj100  = na
var line  lineObj30   = na
var label labelObj80  = na
var label labelObj100 = na
var label labelObj30  = na
 
// Clear last session's artifacts on a new session
if sessionStart
    line.delete(lineObj80)
    lineObj80  := na
    line.delete(lineObj100)
    lineObj100 := na
    line.delete(lineObj30)
    lineObj30  := na
    label.delete(labelObj80)
    labelObj80 := na
    label.delete(labelObj100)
    labelObj100 := na
    label.delete(labelObj30)
    labelObj30 := na
 
// Create-or-update while in session
if projectionActive and showLines
    if show80
        if na(lineObj80)
            lineObj80 := line.new(bar_index, level80, bar_index + 1, level80,
                 extend = extend.right, color = color80, style = lineStyleFrom(style80Str), width = lineWidth)
        else
            line.set_y1(lineObj80, level80)
            line.set_y2(lineObj80, level80)
            line.set_x2(lineObj80, bar_index)
        if showLabels
            txt80 = str.tostring(level80, format.mintick) + "  " + innerTag
            if na(labelObj80)
                labelObj80 := label.new(bar_index, level80, txt80,
                     style = label.style_label_left, color = color.new(color80, 70),
                     textcolor = color.white, size = size.small)
            else
                label.set_xy(labelObj80, bar_index, level80)
                label.set_text(labelObj80, txt80)
 
    if show100
        if na(lineObj100)
            lineObj100 := line.new(bar_index, level100, bar_index + 1, level100,
                 extend = extend.right, color = color100, style = lineStyleFrom(style100Str), width = lineWidth)
        else
            line.set_y1(lineObj100, level100)
            line.set_y2(lineObj100, level100)
            line.set_x2(lineObj100, bar_index)
        if showLabels
            txt100 = str.tostring(level100, format.mintick) + "  100%"
            if na(labelObj100)
                labelObj100 := label.new(bar_index, level100, txt100,
                     style = label.style_label_left, color = color.new(color100, 70),
                     textcolor = color.white, size = size.small)
            else
                label.set_xy(labelObj100, bar_index, level100)
                label.set_text(labelObj100, txt100)
 
    if show30 and not na(level30)
        if na(lineObj30)
            lineObj30 := line.new(bar_index, level30, bar_index + 1, level30,
                 extend = extend.right, color = color30, style = lineStyleFrom(style30Str), width = lineWidth)
        else
            line.set_y1(lineObj30, level30)
            line.set_y2(lineObj30, level30)
            line.set_x2(lineObj30, bar_index)
        if showLabels
            txt30 = str.tostring(level30, format.mintick) + "  30mOR"
            if na(labelObj30)
                labelObj30 := label.new(bar_index, level30, txt30,
                     style = label.style_label_left, color = color.new(color30, 70),
                     textcolor = color.white, size = size.small)
            else
                label.set_xy(labelObj30, bar_index, level30)
                label.set_text(labelObj30, txt30)
 
// ================ Info table ================
var table tbl = na
 
if showTable and na(tbl)
    tbl := table.new(tablePos, 2, 6,
         bgcolor = color.new(color.black, 75),
         frame_color = color.new(color.gray, 50), frame_width = 1,
         border_color = color.new(color.gray, 70), border_width = 1)
 
if showTable and barstate.islast and not na(tbl)
    labelCol = color.new(color.white, 35)
    valueCol = color.white
    rangeTag = rangeMethod == "True Range" ? "ATR" : "ADR"
 
    // Intraday RVOL: time-matched while the session runs, full-session total after the close
    string cumText = "—"
    float  cumVal  = na
    if inSession
        [e, n] = rthP.expectedAt(rthSlot(time))
        minD = math.min(MIN_RVOL_DAYS, rvolLookback)
        if n >= minD and e > 0
            cumVal  := rthP.cum / e
            cumText := str.tostring(cumVal, "0.00") + "x"
        else
            cumText := "— (" + str.tostring(n) + "/" + str.tostring(minD) + ")"
    else if lastSessDay == time_tradingday and not na(rthRvolFinal)
        cumVal  := rthRvolFinal
        cumText := str.tostring(cumVal, "0.00") + "x final"
 
    // Pre-market RVOL: time-matched while the pre-market runs, full pre-market total afterwards
    string pmText = "—"
    float  pmVal  = na
    if syminfo.session == session.regular
        pmText := "ETH off"
    else if pmNow
        [e, n] = pmP.expectedAt(pmSlot(time))
        minD = math.min(MIN_RVOL_DAYS, pmLookback)
        if n >= minD and e > 0
            pmVal  := pmP.cum / e
            pmText := str.tostring(pmVal, "0.00") + "x live"
        else
            pmText := "— (" + str.tostring(n) + "/" + str.tostring(minD) + ")"
    else if lastPmDay == time_tradingday and not na(pmRvolFinal)
        pmVal  := pmRvolFinal
        pmText := str.tostring(pmVal, "0.00") + "x"
 
    // --- Row text + colors ---
    rangeCellText = rangeReady ? str.tostring(rangeAvg, format.mintick)
         : "— (" + str.tostring(array.size(dailyRanges)) + "/" + str.tostring(rangeLength) + ")"
 
    usedColor = na(rangeUsedPct) ? color.gray :
                 rangeUsedPct >= 100 ? color.red :
                 rangeUsedPct >= 80  ? color.orange :
                 rangeUsedPct >= 50  ? color.yellow : #22c55e
 
    orCellText = not orTfOk ? "TF > 30m" : orReady ? str.tostring(avg30mRange, format.mintick)
         : "— (" + str.tostring(array.size(orRanges)) + "/" + str.tostring(orLookback) + ")"
    orColor = (na(todayOR) or na(avg30mRange)) ? valueCol : (todayOR > avg30mRange ? color.orange : #22c55e)
 
    gapText  = na(gapR) ? "—" : (gapR >= 0 ? "+" : "") + str.tostring(gapR, "0.00") + " " + rangeTag
    gapColor = na(gapR) ? color.gray : (gapR >= 0 ? #22c55e : color.red)
 
    // --- Cells ---
    table.cell(tbl, 0, 0, rangeTag + "(" + str.tostring(rangeLength) + ")",
         text_color = labelCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 0, rangeCellText,
         text_color = valueCol, text_size = size.small, text_halign = text.align_right)
 
    table.cell(tbl, 0, 1, "Range used",
         text_color = labelCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 1, na(rangeUsedPct) ? "—" : str.tostring(rangeUsedPct, "#.#") + "%",
         text_color = usedColor, text_size = size.small, text_halign = text.align_right)
 
    table.cell(tbl, 0, 2, "30m OR (" + str.tostring(orLookback) + "d)",
         text_color = labelCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 2, orCellText,
         text_color = orColor, text_size = size.small, text_halign = text.align_right)
 
    table.cell(tbl, 0, 3, "Gap (" + rangeTag + ")",
         text_color = labelCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 3, gapText,
         text_color = gapColor, text_size = size.small, text_halign = text.align_right)
 
    table.cell(tbl, 0, 4, "Pre-mkt RVOL",
         text_color = labelCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 4, pmText,
         text_color = rvolColor(pmVal), text_size = size.small, text_halign = text.align_right)
 
    table.cell(tbl, 0, 5, "RVOL (cum)",
         text_color = labelCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 5, cumText,
         text_color = rvolColor(cumVal), text_size = size.small, text_halign = text.align_right)
 
// ================ Alerts ================
// ta.crossover must run every bar to keep its internal state, so compute first then gate.
cross80Raw  = ta.crossover(high, level80)
cross100Raw = ta.crossover(high, level100)
cross80  = projectionActive and cross80Raw
cross100 = projectionActive and cross100Raw
alertcondition(cross80,  title = "Crossed inner range line", message = "{{ticker}} crossed the inner daily-range projection")
alertcondition(cross100, title = "Crossed full range line",  message = "{{ticker}} crossed the full daily-range projection")

← 返回列表