Record Close Breadth

BY_Tse · study · 195 行 · 点赞 4 · TradingView 原页

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

Pine Script

//@version=6
indicator("Record Close Breadth", shorttitle = "RCB", overlay = false, precision = 1)
 
// ── Inputs ───────────────────────────────────────────────────────────────────
string GRP_S = "Sources"
string idxSym = input.symbol("SP:SPX",     "Index",                             group = GRP_S)
string s5Sym  = input.symbol("INDEX:S5TH", "Percent of members above 200-day",  group = GRP_S)
string ewSym  = input.symbol("SP:SPW",     "Equal-weight index (table only)",   group = GRP_S)
string nhSym  = input.symbol("INDEX:MAHP", "New 52-week highs (table only)",    group = GRP_S)
 
string GRP_L = "Logic"
float thr       = input.float(96.15, "Narrow record threshold, breadth rank", minval = 0, maxval = 100, step = 0.01, group = GRP_L,
     tooltip = "A record close whose breadth rank is at or above this value is classed as narrow.")
int   gapSess   = input.int(20,  "Episode gap, sessions", minval = 1, group = GRP_L,
     tooltip = "A record close that comes this many index sessions or more after the previous record close starts a new episode.")
int   staleSess = input.int(5,   "Stale source limit, sessions", minval = 0, group = GRP_L,
     tooltip = "A breadth source whose latest bar is older than this many index sessions is treated as missing.")
int   ewLen     = input.int(504, "Equal-weight high lookback, sessions", minval = 20, group = GRP_L)
int   minPrior  = input.int(50,  "Minimum prior records for ranking", minval = 1, group = GRP_L)
int   histStart = input.time(timestamp("2007-01-01T00:00:00+00:00"), "Ranking history start", group = GRP_L,
     tooltip = "Record closes before this date neither enter the ranking history nor receive a rank.")
bool  useSeed   = input.bool(true, "Seed the 2000 closing high when history is short", group = GRP_L,
     tooltip = "For SP:SPX only. If the loaded history starts between 2000-03-24 and 2007-05-30, the running closing high starts at the 2000-03-24 close of 1527.46.")
 
string GRP_D = "Display"
bool  showTable = input.bool(false, "Show status table", group = GRP_D)
bool  debug     = input.bool(false, "Debug: plot raw source values", group = GRP_D)
 
if not (timeframe.isdaily and timeframe.multiplier == 1)
    runtime.error("Record Close Breadth runs on the 1D timeframe only.")
 
// ── Constants ────────────────────────────────────────────────────────────────
float SEED_HIGH  = 1527.46
int   SEED_START = timestamp("2000-03-25T00:00:00+00:00")
int   SEED_END   = timestamp("2007-05-31T00:00:00+00:00")
 
// ── Requests (4 calls) ───────────────────────────────────────────────────────
[idxC, idxT]          = request.security(idxSym, "D", [close, time], lookahead = barmerge.lookahead_off)
[s5C, s5T]            = request.security(s5Sym,  "D", [close, time], lookahead = barmerge.lookahead_off)
// The equal-weight feed stamps each daily bar at the prior evening UTC, so lookahead_off would return the previous
// session. lookahead_on returns the bar whose period contains the chart bar's open, which is the same trading session and never a later one.
[ewC, ewDD, ewT]      = request.security(ewSym,  "D", [close, close / ta.highest(close, ewLen) - 1.0, time], lookahead = barmerge.lookahead_on)
[nhC, nhT]            = request.security(nhSym,  "D", [close, time], lookahead = barmerge.lookahead_off)
 
// ── Functions ────────────────────────────────────────────────────────────────
// Index sessions since the source last printed a new bar.
f_age(float srcT, bool newBar) =>
    var float lastT = na
    var int   age   = na
    if newBar
        if na(srcT)
            age := na
        else if na(lastT) or srcT != lastT
            lastT := srcT
            age   := 0
        else
            age   += 1
    age
 
// Share of prior record-day readings that were broader than x, ties counted half.
f_narrowPct(array<float> hist, float x, int minN) =>
    float res = na
    int   n   = hist.size()
    if n >= minN and not na(x)
        float score = 0.0
        for v in hist
            score += v > x ? 1.0 : v == x ? 0.5 : 0.0
        res := 100.0 * score / n
    res
 
f_row(table tb, int r, string k, string v, color vc) =>
    tb.cell(0, r, k, text_color = chart.fg_color, text_size = size.small, text_halign = text.align_left)
    tb.cell(1, r, v, text_color = vc, text_size = size.small, text_halign = text.align_right)
 
f_fmt(float x, string f) =>
    na(x) ? "n/a" : str.tostring(x, f)
 
// ── Source validity ──────────────────────────────────────────────────────────
bool newIdx = not na(idxT) and (na(idxT[1]) or idxT != idxT[1])
int  s5Age  = f_age(s5T, newIdx)
int  ewAge  = f_age(ewT, newIdx)
int  nhAge  = f_age(nhT, newIdx)
float c1 = not na(s5Age) and s5Age <= staleSess ? s5C  : na
float c2 = not na(ewAge) and ewAge <= staleSess ? ewDD : na
float nh = not na(nhAge) and nhAge <= staleSess ? nhC  : na
 
// ── Record logic ─────────────────────────────────────────────────────────────
var array<float> h1 = array.new<float>()
var array<float> h2 = array.new<float>()
var int   sess           = 0
var int   lastRecSess    = na
var float runMax         = na
var float heldComp       = na
var float prevEpLastComp = na
var float curEpLastComp  = na
var bool  shortHistory   = false
 
var int   lrTime   = na
var float lrS5     = na
var float lrEW     = na
var float lrP1     = na
var float lrP2     = na
var float lrComp   = na
var float lrNH     = na
var float lrPrev   = na
var bool  lrNarrow = false
 
if barstate.isfirst
    bool isSpx = idxSym == "SP:SPX" or idxSym == "TVC:SPX"
    if isSpx and useSeed and time >= SEED_START and time < SEED_END
        runMax := SEED_HIGH
    shortHistory := isSpx and time >= SEED_END
 
bool  isRec        = false
float recP1        = na
float recP2        = na
float recComp      = na
bool  narrowingRec = false
 
if newIdx and not na(idxC)
    sess += 1
    isRec  := na(runMax) or idxC > runMax
    runMax := na(runMax) ? idxC : math.max(runMax, idxC)
    if isRec
        if na(lastRecSess) or sess - lastRecSess >= gapSess
            prevEpLastComp := curEpLastComp
        bool inHist = time >= histStart
        recP1   := inHist ? f_narrowPct(h1, c1, minPrior) : na
        recP2   := inHist ? f_narrowPct(h2, c2, minPrior) : na
        recComp := recP1
        narrowingRec := not na(recComp) and not na(prevEpLastComp) and recComp > prevEpLastComp
        if inHist and not na(c1)
            h1.push(c1)
        if inHist and not na(c2)
            h2.push(c2)
        curEpLastComp := recComp
        lastRecSess   := sess
        heldComp      := recComp
        lrTime   := time
        lrS5     := c1
        lrEW     := c2
        lrP1     := recP1
        lrP2     := recP2
        lrComp   := recComp
        lrNH     := nh
        lrPrev   := prevEpLastComp
        lrNarrow := narrowingRec
 
bool narrowRec = isRec and not na(recComp) and recComp >= thr
 
// ── Plots ────────────────────────────────────────────────────────────────────
color recColor = na(recComp) ? color.gray : recComp >= thr ? color.red : recComp >= 75 ? color.orange : color.gray
hline(thr, "Narrow threshold", color = color.new(color.red, 30), linestyle = hline.style_dashed)
hline(50,  "Midline", color = color.new(color.gray, 60), linestyle = hline.style_dotted)
bgcolor(not na(heldComp) and heldComp >= thr ? color.new(color.red, 85) : na, title = "Narrow state")
plot(heldComp, "Breadth rank", color = color.purple, linewidth = 2, style = plot.style_stepline)
plot(isRec ? recComp : na, "Record close", color = recColor, style = plot.style_circles, linewidth = 4)
 
plot(isRec ? 1 : na,                          "Record flag",                  display = display.data_window)
plot(isRec ? c1 : na,                         "S5TH at record",               display = display.data_window, precision = 4)
plot(isRec ? c2 * 100 : na,                   "EW drawdown at record, %",     display = display.data_window, precision = 4)
plot(isRec ? recP1 : na,                      "S5TH percentile",              display = display.data_window, precision = 4)
plot(isRec ? recP2 : na,                      "EW percentile",                display = display.data_window, precision = 4)
plot(isRec ? recComp : na,                    "Breadth rank at record",       display = display.data_window, precision = 4)
plot(isRec ? nh : na,                         "New 52-week highs at record",  display = display.data_window)
plot(isRec ? (narrowingRec ? 1 : 0) : na,     "Narrowing flag",               display = display.data_window)
 
plot(debug ? c1 : na,         "Debug S5TH",            color = color.teal,   precision = 2)
plot(debug ? c2 * 100 : na,   "Debug EW drawdown, %",  color = color.blue,   precision = 2)
plot(debug ? ewC : na,        "Debug EW close",        display = display.data_window, precision = 2)
 
// ── Alerts ───────────────────────────────────────────────────────────────────
alertcondition(narrowRec,    "Narrow record close",       "Record Close Breadth: narrow record close")
alertcondition(narrowingRec, "Narrowing record sequence", "Record Close Breadth: record breadth rank above the prior episode's last record")
 
// ── Status table ─────────────────────────────────────────────────────────────
var table tb = table.new(position.top_right, 2, 11, bgcolor = chart.bg_color,
     border_color = color.new(chart.fg_color, 80), border_width = 1, frame_color = color.new(chart.fg_color, 60), frame_width = 1)
 
if showTable and barstate.islast
    tb.cell(0, 0, "Record Close Breadth", text_color = chart.fg_color, text_size = size.small)
    tb.merge_cells(0, 0, 1, 0)
    color compCol = na(lrComp) ? chart.fg_color : lrComp >= thr ? color.red : lrComp >= 75 ? color.orange : chart.fg_color
    string state  = na(lrComp) ? "" : lrComp >= thr ? "  narrow" : "  ordinary"
    f_row(tb, 1, "Last record close",       na(lrTime) ? "none" : str.format_time(lrTime, "yyyy-MM-dd", syminfo.timezone), chart.fg_color)
    f_row(tb, 2, "Breadth rank",            f_fmt(lrComp, "#.0") + state, compCol)
    f_row(tb, 3, "Above 200-day",           f_fmt(lrS5, "#.0") + "%", chart.fg_color)
    f_row(tb, 4, "Equal-weight off high",   f_fmt(na(lrEW) ? na : lrEW * 100, "#.0") + "%  rank " + f_fmt(lrP2, "#"), chart.fg_color)
    f_row(tb, 5, "New 52-week highs",       f_fmt(lrNH, "#"), chart.fg_color)
    f_row(tb, 6, "Prior episode rank",      f_fmt(lrPrev, "#.0"), chart.fg_color)
    f_row(tb, 7, "Sequence",                na(lrComp) or na(lrPrev) ? "n/a" : lrNarrow ? "narrowing" : "not narrowing", lrNarrow ? color.red : chart.fg_color)
    f_row(tb, 8, "Ranked records",          str.tostring(h1.size()) + " / " + str.tostring(h2.size()), chart.fg_color)
    f_row(tb, 9, "Sessions since record",   na(lastRecSess) ? "n/a" : str.tostring(sess - lastRecSess), chart.fg_color)
    if shortHistory
        f_row(tb, 10, "Warning", "history starts after 2007-05-30", color.orange)

← 返回列表