本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SG_Group
//@version=6
indicator("RSI Memory Attribution - Relative Strength Index", overlay = false, precision = 2, max_bars_back = 600, explicit_plot_zorder = true)
// v3.0.0 | Standard RSI plus attribution and sensitivity research.
// No imports, external requests, orders, pivots, future offsets or paid features.
// RSI = 50 + recent contribution + older contribution, with ONE denominator.
// The older base is 50 + older contribution, NOT an independently scaled RSI.
// REMOVE ONE includes age 0. The entry study EXCLUDES age 0 (the trigger).
// Deleting age 0 at a new threshold entry necessarily restores the prior RSI;
// using that test to split new entries would make the resilient group empty.
// PRIOR-RESILIENT/SENSITIVE instead test only ages 1..H-1 at the entry close.
// These words describe an arithmetic test, NOT price stability or trade quality.
// Study labels are frozen at entry; outcomes are evaluated K closes later.
// ORDER reassigns the same signed changes to recency weights; not a forecast.
// No fixed execution-history cap: statistics depend on available chart history.
// Custom H-term scans and sorting run only for the latest snapshot.
const string GC = "01 | RSI"
const string GM = "02 | Attribution and sensitivity"
const string GE = "03 | Confirmed research"
const string GV = "04 | Appearance"
const string GP = "05 | Colors"
const float TOL = 0.000001
const float EPS = 0.00000001
const float EMPTY_LOG = -1e30
float src = input.source(close, "Source", group = GC, display = display.none, tooltip = "Close matches the standard close-based RSI. An external source may repaint upstream. This study cannot prevent that.")
int n = input.int(14, "RSI length", minval = 2, maxval = 300, group = GC, display = display.none)
float upper = input.float(70.0, "Upper threshold", minval = 50.1, maxval = 99.9, step = 0.5, group = GC, display = display.none)
float lower = input.float(30.0, "Lower threshold", minval = 0.1, maxval = 49.9, step = 0.5, group = GC, display = display.none)
bool research = input.bool(true, "Enable research / off = native RSI only", group = GC, display = display.none)
bool closed = input.bool(true, "Hold last closed reading on the open bar", group = GC, display = display.none, tooltip = "Only the open bar holds the previous close. Historical plots are not shifted. Off permits intrabar changes. Episodes, entry samples and alerts always require close.")
int settle = input.int(10, "Research settling: RSI lengths", minval = 2, maxval = 15, group = GC, display = display.none, tooltip = "Wait N times this value plus H consecutive valid changes. This reduces initialization influence; it does not prove infinite-history convergence. Native RSI never waits for research.")
int h = input.int(7, "Recent cohort: H changes", minval = 1, maxval = 200, group = GM, display = display.none, tooltip = "Attribution and REMOVE ONE use ages 0..H-1. The entry study uses ages 1..H-1 and therefore requires H >= 2. Age 0 is the displayed observation.")
float material = input.float(2.0, "Material contribution: RSI points", minval = 0.1, maxval = 20.0, step = 0.1, group = GM, display = display.none)
bool probes = input.bool(true, "Single-term removal analysis", group = GM, display = display.none)
bool orderTest = input.bool(true, "Latest order / concentration analysis", group = GM, display = display.none)
float flagWidth = input.float(3.0, "Wide-range marker threshold: RSI points", minval = 0.1, maxval = 50.0, step = 0.1, group = GM, display = display.none)
bool episodes = input.bool(true, "Completed extreme episodes", group = GE, display = display.none)
int capacity = input.int(60, "Episode completions retained per side", minval = 10, maxval = 300, group = GE, display = display.none)
int minSample = input.int(20, "Minimum observations for a summary", minval = 3, maxval = 100, group = GE, display = display.none)
bool eventStudy = input.bool(true, "Entry study: prior terms only", group = GE, display = display.none, tooltip = "At the entry close, hold the triggering age-0 change fixed and delete any one prior term aged 1..H-1. Freeze that classification before observing outcomes. This is NOT the full REMOVE ONE classification.")
int horizon = input.int(5, "Outcome horizon: K closes after entry", minval = 1, maxval = 200, group = GE, display = display.none)
bool separateWindows = input.bool(true, "Non-overlapping entry windows", group = GE, display = display.none, tooltip = "Across BOTH sides, accept the earliest eligible entry, then skip entries through its +K bar inclusive. Selection does not use its eventual outcome. This does not make observations statistically independent.")
string studySide = input.string("Upper", "Entry-study side", options = ["Upper", "Lower"], group = GE, display = display.none)
bool useDates = input.bool(false, "Restrict research by bar close time", group = GE, display = display.none)
int fromTime = input.time(timestamp("01 Jan 2020 00:00 +0000"), "Sample start", group = GE, display = display.none)
int toTime = input.time(timestamp("31 Dec 2099 23:59 +0000"), "Sample end", group = GE, display = display.none, tooltip = "Dates filter observations, not RSI initialization or history loading. Partial episodes and incomplete/invalid outcome windows are not counted as completed observations.")
bool showMemory = input.bool(true, "Memory base and signed ribbon", group = GV, display = display.none)
bool showEnvelope = input.bool(true, "Single-term removal shading", group = GV, display = display.none)
bool envelopeEdges = input.bool(false, "Also draw removal edges", group = GV, display = display.none)
bool showStrip = input.bool(false, "Cohort strip at 98 / see Legend", group = GV, display = display.none)
string markers = input.string("Off", "Confirmed event markers", options = ["Off", "Classification circles", "Width squares", "Both"], group = GV, display = display.none, tooltip = "Circle = full removal classification became sensitive. Square = removal width crossed its threshold. In Both, a circle takes priority on the same bar. Neither is a trading instruction.")
bool showHalo = input.bool(true, "Subtle RSI halo", group = GV, display = display.none)
int lineWidth = input.int(3, "RSI line width", minval = 1, maxval = 5, group = GV, display = display.none)
int ribbonAlpha = input.int(83, "Memory ribbon transparency", minval = 50, maxval = 98, group = GV, display = display.none)
int envelopeAlpha = input.int(89, "Removal shading transparency", minval = 70, maxval = 98, group = GV, display = display.none)
bool showPanel = input.bool(true, "Compact five-row readout", group = GV, display = display.none)
string page = input.string("Overview", "Readout page", options = ["Overview", "Order and concentration", "Episodes", "Entry study", "Diagnostics", "Legend"], group = GV, display = display.none)
string corner = input.string("Top right", "Readout position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = GV, display = display.none)
int fontSize = input.int(13, "Readout font size", minval = 10, maxval = 18, group = GV, display = display.none)
color cRSI = input.color(#40E9FF, "RSI", group = GP, display = display.none)
color cUp = input.color(#42F5BD, "Positive contribution", group = GP, display = display.none)
color cDown = input.color(#FF985A, "Negative contribution", group = GP, display = display.none)
color cOld = input.color(#B59AFF, "Older contribution base", group = GP, display = display.none)
color cTest = input.color(#FFDA62, "Removal sensitivity", group = GP, display = display.none)
color cOrder = input.color(#FF81D0, "Order analysis / width squares", group = GP, display = display.none)
color cMuted = input.color(#98A6B9, "References and secondary text", group = GP, display = display.none)
color cBg = input.color(#111A29, "Readout background", group = GP, display = display.none)
color cText = input.color(#F1F7FF, "Readout foreground", group = GP, display = display.none)
// Nonnegative mass: bool() avoids rounding small price-unit values to zero.
f_mass(float x) =>
not na(x) and bool(x)
f_num(float x) =>
na(x) ? "n/a" : str.tostring(x, "0.0")
f_sign(float x) =>
na(x) ? "n/a" : (x > 0.0 ? "+" : "") + str.tostring(x, "0.00")
f_clip(float x) =>
math.max(0.0, math.min(100.0, x))
f_side(float x) =>
na(x) ? 0 : x >= upper ? 1 : x <= lower ? -1 : 0
f_name(int s) =>
s == 1 ? "UPPER" : s == -1 ? "LOWER" : "IN RANGE"
f_near(float x) =>
not na(x) and (math.abs(x - upper) <= TOL or math.abs(x - lower) <= TOL)
f_ratio(float g0, float l0) =>
f_mass(g0 + l0) ? f_clip(100.0 * (g0 / (g0 + l0))) : na
f_pair(float x, float y) =>
f_num(x) + " - " + f_num(y)
f_check(float e) =>
na(e) ? "n/a" : (e <= TOL ? "PASS " : "FAIL ") + str.tostring(e, "0.000000000")
f_envelope(float g0, float l0, float pg, float pl) =>
float t = g0 + l0
float lowValue = na
float highValue = na
bool ok = false
if f_mass(t) and f_mass(pg + pl)
float gn = g0 / t
float ln = l0 / t
float xg = pg / t
float xl = pl / t
if xg <= gn + EPS and xl <= ln + EPS
xg := math.max(0.0, math.min(gn, xg))
xl := math.max(0.0, math.min(ln, xl))
if 1.0 - xg > EPS and 1.0 - xl > EPS
lowValue := f_clip(math.min(100.0 * gn, 100.0 * (gn - xg) / (1.0 - xg)))
highValue := f_clip(math.max(100.0 * gn, 100.0 * gn / (1.0 - xl)))
ok := true
[lowValue, highValue, ok]
f_add(array<float> pool, float x) =>
array.push(pool, x)
if array.size(pool) > capacity
array.shift(pool)
array.size(pool)
f_inc(array<int> pool, int ix) =>
array.set(pool, ix, array.get(pool, ix) + 1)
array.get(pool, ix)
f_med(array<float> pool) =>
array.size(pool) >= minSample ? array.median(pool) : na
f_rank(array<float> pool, float x) =>
float result = na
int count = array.size(pool)
if count >= minSample and not na(x)
float totalRank = 0.0
for k = 0 to count - 1
float v = array.get(pool, k)
totalRank += v < x ? 1.0 : v == x ? 0.5 : 0.0
result := 100.0 * totalRank / count
result
f_stats(int count, int ends, int runs) =>
string rates = count >= minSample ? "E " + f_num(100.0 * ends / count) + "% R " + f_num(100.0 * runs / count) + "%" : "E n/a R n/a"
"n " + str.tostring(count) + " | " + rates
f_row(table id, int row, string caption, string value, color ink, string help) =>
table.cell(id, 0, row, caption, text_color = cMuted, bgcolor = cBg, text_size = fontSize, text_halign = text.align_left, text_formatting = text.format_bold, tooltip = help)
table.cell(id, 1, row, value, text_color = ink, bgcolor = cBg, text_size = row == 0 ? fontSize + 1 : fontSize, text_halign = text.align_right, text_formatting = text.format_bold, tooltip = help)
// History-dependent built-ins always execute on every bar.
float delta = ta.change(src)
float gain = math.max(delta, 0.0)
float loss = math.max(-delta, 0.0)
float g = ta.rma(gain, n)
float l = ta.rma(loss, n)
float rsi = ta.rsi(src, n)
float mass = g + l
float a = 1.0 / n
float q = 1.0 - a
float qh = math.pow(q, h)
float oldG = qh * g[h]
float oldL = qh * l[h]
float recG = g - oldG
float recL = l - oldL
var int streak = 0
streak := not na(delta) ? math.min(streak + 1, 1000000) : 0
bool ready = research and chart.is_standard and streak >= n * settle + h and f_mass(mass) and not na(oldG) and not na(oldL) and not na(rsi)
float identityError = ready ? math.abs(rsi - 100.0 * (g / mass)) : na
bool mathOK = ready and identityError <= TOL and recG / mass >= -EPS and recL / mass >= -EPS
float recentPoints = mathOK ? 50.0 * ((recG - recL) / mass) : na
float olderPoints = mathOK ? 50.0 * ((oldG - oldL) / mass) : na
float base = mathOK ? f_clip(50.0 + olderPoints) : na
float recentShare = mathOK ? f_clip(100.0 * ((recG + recL) / mass)) : na
bool rMaterial = mathOK and math.abs(recentPoints) >= material
bool oMaterial = mathOK and math.abs(olderPoints) >= material
bool opposed = rMaterial and oMaterial and recentPoints * olderPoints < 0.0
int relation = opposed ? 2 : rMaterial and oMaterial ? (recentPoints > 0.0 ? 1 : -1) : rMaterial ? 3 : oMaterial ? 4 : 0
// Ranking uses log(change)-bar_index*log(q), but values are recovered from
// the original change and its integer age, avoiding exp(log-log) cancellation.
// The shifted window EXCLUDES age 0. Current + prior maxima give the full test.
float clockLog = -float(bar_index) * math.log(q)
float logG = f_mass(gain) ? math.log(gain) + clockLog : EMPTY_LOG
float logL = f_mass(loss) ? math.log(loss) + clockLog : EMPTY_LOG
int priorLength = math.max(h - 1, 1)
int ageG = 1 + math.abs(nz(ta.highestbars(logG[1], priorLength), 0))
int ageL = 1 + math.abs(nz(ta.highestbars(logL[1], priorLength), 0))
float priorG = h > 1 and f_mass(gain[ageG]) ? a * math.pow(q, ageG) * gain[ageG] : 0.0
float priorL = h > 1 and f_mass(loss[ageL]) ? a * math.pow(q, ageL) * loss[ageL] : 0.0
float peakG = math.max(a * gain, priorG)
float peakL = math.max(a * loss, priorL)
[fullLowRaw, fullHighRaw, fullDefined] = f_envelope(g, l, peakG, peakL)
[priorLowRaw, priorHighRaw, priorDefined] = f_envelope(g, l, priorG, priorL)
bool fullOK = mathOK and probes and fullDefined
bool priorOK = mathOK and probes and h > 1 and priorDefined
float fullLow = fullOK ? fullLowRaw : na
float fullHigh = fullOK ? fullHighRaw : na
float width = fullOK ? fullHigh - fullLow : na
int side = f_side(rsi)
bool sensitive = fullOK and (f_side(fullLow) != side or f_side(fullHigh) != side)
bool priorSensitive = priorOK and (f_side(priorLowRaw) != side or f_side(priorHighRaw) != side)
// Do not let floating-point boundary ambiguity fabricate an entry group.
bool classifiable = priorOK and not f_near(rsi) and not f_near(priorLowRaw) and not f_near(priorHighRaw)
// Latest-snapshot direct audits, concentration and sorted order extrema.
var int snapBar = na
var float orderLow = na
var float orderHigh = na
var float neutralOrder = na
var float orderPosition = na
var float meanAge = na
var float gainMeanAge = na
var float lossMeanAge = na
var float effectiveTerms = na
var float topShare = na
var float directError = na
var float removalError = na
var bool orderAudit = false
var bool orderAttempted = false
bool snapshotTick = barstate.islastconfirmedhistory or (barstate.islast and (barstate.isconfirmed or not closed))
if snapshotTick
snapBar := bar_index
orderLow := na
orderHigh := na
neutralOrder := na
orderPosition := na
meanAge := na
gainMeanAge := na
lossMeanAge := na
effectiveTerms := na
topShare := na
directError := na
removalError := na
orderAudit := false
orderAttempted := false
if mathOK
array<float> moves = array.new_float(0)
float rg = 0.0
float rl = 0.0
float ag = 0.0
float al = 0.0
float squares = 0.0
float biggest = 0.0
float rawG = 0.0
float rawL = 0.0
float dl = rsi
float dh = rsi
float pl = rsi
float ph = rsi
bool directFullOK = true
bool directPriorOK = true
float w = a
for k = 0 to h - 1
float d = delta[k] / mass
float wg = w * math.max(d, 0.0)
float wl = w * math.max(-d, 0.0)
float term = wg + wl
rg += wg
rl += wl
ag += k * wg
al += k * wl
squares += term * term
biggest := math.max(biggest, term)
rawG += math.max(d, 0.0)
rawL += math.max(-d, 0.0)
if probes
if 1.0 - term > EPS
float candidate = f_clip(100.0 * math.max(g / mass - wg, 0.0) / (1.0 - term))
dl := math.min(dl, candidate)
dh := math.max(dh, candidate)
if k > 0
pl := math.min(pl, candidate)
ph := math.max(ph, candidate)
else
directFullOK := false
if k > 0
directPriorOK := false
if orderTest
array.push(moves, d)
w *= q
directError := 100.0 * math.max(math.abs(rg - recG / mass), math.abs(rl - recL / mass))
if fullOK and directFullOK
removalError := math.max(math.abs(dl - fullLow), math.abs(dh - fullHigh))
if priorOK and directPriorOK
float priorError = math.max(math.abs(pl - priorLowRaw), math.abs(ph - priorHighRaw))
removalError := na(removalError) ? priorError : math.max(removalError, priorError)
if (fullOK and not directFullOK) or (priorOK and not directPriorOK)
removalError := 100.0
bool snapshotPass = directError <= TOL and (na(removalError) or removalError <= TOL)
float rm = rg + rl
if snapshotPass and orderTest
orderAttempted := true
if f_mass(rm) and f_mass(squares)
effectiveTerms := math.max(1.0, math.min(float(h), rm * rm / squares))
meanAge := (ag + al) / rm
gainMeanAge := f_mass(rg) ? ag / rg : na
lossMeanAge := f_mass(rl) ? al / rl : na
topShare := f_clip(100.0 * biggest / rm)
array.sort(moves, order.ascending)
float minG = oldG / mass
float minL = oldL / mass
float maxG = minG
float maxL = minL
w := a
for k = 0 to h - 1
float small = array.get(moves, k)
float large = array.get(moves, h - 1 - k)
minG += w * math.max(small, 0.0)
minL += w * math.max(-small, 0.0)
maxG += w * math.max(large, 0.0)
maxL += w * math.max(-large, 0.0)
w *= q
float ol = f_ratio(minG, minL)
float oh = f_ratio(maxG, maxL)
orderAudit := not na(ol) and not na(oh) and ol <= oh + TOL and rsi >= ol - TOL and rsi <= oh + TOL
if orderAudit
orderLow := math.min(ol, rsi)
orderHigh := math.max(oh, rsi)
float equalWeight = (1.0 - qh) / h
neutralOrder := f_ratio(oldG / mass + equalWeight * rawG, oldL / mass + equalWeight * rawL)
orderPosition := orderHigh - orderLow > TOL ? f_clip(100.0 * (rsi - orderLow) / (orderHigh - orderLow)) : na
// A consistent live/closed snapshot. No historical offsets or backdating.
bool hold = closed and not barstate.isconfirmed
float vr = hold ? rsi[1] : rsi
bool vok = hold ? mathOK[1] : mathOK
bool vready = hold ? ready[1] : ready
float vb = hold ? base[1] : base
float vp = hold ? recentPoints[1] : recentPoints
float vo = hold ? olderPoints[1] : olderPoints
float vs = hold ? recentShare[1] : recentShare
bool vdOK = hold ? fullOK[1] : fullOK
float vdLow = hold ? fullLow[1] : fullLow
float vdHigh = hold ? fullHigh[1] : fullHigh
float vdWidth = hold ? width[1] : width
bool vf = hold ? sensitive[1] : sensitive
int vrel = hold ? relation[1] : relation
float vIdentity = hold ? identityError[1] : identityError
bool aligned = snapBar == (hold ? bar_index - 1 : bar_index) and vok
// Confirmed episodes; left-censored and interrupted episodes are not completions.
bool dateOK = not useDates or fromTime <= toTime
bool inDates = not useDates or (not na(time_close) and time_close >= fromTime and time_close <= toTime)
bool sample = mathOK and dateOK and inDates
bool confirmedSample = barstate.isconfirmed ? sample : sample[1]
var int validSampleRun = 0
validSampleRun := sample ? math.min(validSampleRun + 1, 1000000) : 0
bool enterU = barstate.isconfirmed and sample and sample[1] and side == 1 and side[1] != 1
bool enterL = barstate.isconfirmed and sample and sample[1] and side == -1 and side[1] != -1
var array<float> upAges = array.new_float(0)
var array<float> downAges = array.new_float(0)
var array<float> upAreas = array.new_float(0)
var array<float> downAreas = array.new_float(0)
var int epSide = 0
var int epAge = 0
var float epArea = 0.0
var float epPeak = 0.0
var bool partial = false
// Groups: upper resilient, upper sensitive, lower resilient, lower sensitive.
var array<int> counts = array.new_int(4, 0)
var array<int> ends = array.new_int(4, 0)
var array<int> runs = array.new_int(4, 0)
var array<int> pending = array.new_int(2, 0)
var array<int> dropped = array.new_int(2, 0)
var array<int> unclassified = array.new_int(2, 0)
var array<int> overlaps = array.new_int(2, 0)
var int occupiedThrough = na
var int firstSampleTime = na
var int lastSampleTime = na
int entryGroup = -1
bool studyOn = research and probes and eventStudy and h >= 2
if barstate.isconfirmed
if not sample
epSide := 0
epAge := 0
epArea := 0.0
epPeak := 0.0
partial := false
else
firstSampleTime := na(firstSampleTime) ? time_close : firstSampleTime
lastSampleTime := time_close
if side != epSide
if sample[1] and epSide != 0 and not partial and epAge > 0 and episodes
f_add(epSide == 1 ? upAges : downAges, float(epAge))
f_add(epSide == 1 ? upAreas : downAreas, epArea)
epSide := side
epAge := 0
epArea := 0.0
epPeak := 0.0
partial := side != 0 and not sample[1]
if side != 0
float excess = side == 1 ? math.max(rsi - upper, 0.0) : math.max(lower - rsi, 0.0)
epAge += 1
epArea += excess
epPeak := math.max(epPeak, excess)
if studyOn and (enterU or enterL)
int si = enterU ? 0 : 1
if not classifiable
f_inc(unclassified, si)
else if separateWindows and not na(occupiedThrough) and bar_index <= occupiedThrough
f_inc(overlaps, si)
else
entryGroup := si * 2 + (priorSensitive ? 1 : 0)
f_inc(pending, si)
occupiedThrough := bar_index + horizon
int matured = entryGroup[horizon]
if studyOn and not na(matured) and matured >= 0
int si = matured < 2 ? 0 : 1
array.set(pending, si, math.max(0, array.get(pending, si) - 1))
if validSampleRun >= horizon + 1
int initialSide = si == 0 ? 1 : -1
bool sameSide = side == initialSide
f_inc(counts, matured)
if sameSide
f_inc(ends, matured)
if epAge >= horizon + 1
f_inc(runs, matured)
else
f_inc(dropped, si)
// Visual hierarchy: bright RSI; thin memory base; a quiet removal ribbon.
hline(100.0, "100", color = color.new(cMuted, 85))
hline(0.0, "0", color = color.new(cMuted, 85))
hline(upper, "Upper threshold", color = color.new(cDown, 30), linestyle = hline.style_dashed)
hline(lower, "Lower threshold", color = color.new(cUp, 30), linestyle = hline.style_dashed)
hline(50.0, "50 | Balance", color = color.new(cMuted, 55), linestyle = hline.style_dotted)
pDL = plot(showEnvelope and vdOK ? vdLow : na, "All-term removal lower", color = color.new(cTest, envelopeEdges ? 50 : 100), linewidth = 1, style = plot.style_linebr, display = display.pane)
pDH = plot(showEnvelope and vdOK ? vdHigh : na, "All-term removal upper", color = color.new(cTest, envelopeEdges ? 50 : 100), linewidth = 1, style = plot.style_linebr, display = display.pane)
fill(pDL, pDH, color = color.new(cTest, envelopeAlpha), title = "All-term removal range / not a forecast", fillgaps = false)
pB = plot(showMemory and vok ? vb : na, "Older contribution base / not a separate RSI", color = cOld, linewidth = 1, style = plot.style_linebr, display = display.pane + display.data_window)
pA = plot(showMemory and vok ? vr : na, "Recent ribbon anchor", display = display.none, editable = false)
fill(pB, pA, color = color.new(vp >= 0.0 ? cUp : cDown, ribbonAlpha), title = "Recent signed contribution", fillgaps = false)
plot(showHalo ? vr : na, "RSI halo", color = color.new(cRSI, 85), linewidth = lineWidth + 3, style = plot.style_linebr, display = display.pane, editable = false)
plot(vr, "RSI", color = cRSI, linewidth = lineWidth, style = plot.style_linebr, display = display.pane + display.data_window)
color stripInk = vrel == 2 ? cTest : vrel == 1 ? cUp : vrel == -1 ? cDown : vrel == 3 or vrel == 4 ? cOld : color.new(cMuted, 55)
plot(showStrip and vok ? 98.0 : na, "Optional cohort strip / see Legend", color = stripInk, linewidth = 2, style = plot.style_linebr, display = display.pane)
bool newSensitive = barstate.isconfirmed and fullOK and fullOK[1] and sensitive and not sensitive[1]
bool newWide = barstate.isconfirmed and fullOK and fullOK[1] and width >= flagWidth and width[1] < flagWidth
bool circleNow = (markers == "Classification circles" or markers == "Both") and newSensitive
bool squareNow = (markers == "Width squares" or markers == "Both") and newWide and not circleNow
plotshape(circleNow ? rsi : na, "Confirmed full-test sensitivity / circle", style = shape.circle, location = location.absolute, color = cTest, size = size.tiny, display = display.pane)
plotshape(squareNow ? rsi : na, "Confirmed width crossing / square", style = shape.square, location = location.absolute, color = cOrder, size = size.tiny, display = display.pane)
plot(vp, "Recent contribution | RSI points", display = display.data_window)
plot(vo, "Older contribution | RSI points", display = display.data_window)
plot(vs, "Recent mass share | %", display = display.data_window)
plot(vdLow, "All-term removal lower | RSI", display = display.data_window)
plot(vdHigh, "All-term removal upper | RSI", display = display.data_window)
plot(vdWidth, "All-term removal width | RSI points", display = display.data_window)
plot(hold ? (priorOK[1] ? priorLowRaw[1] : na) : (priorOK ? priorLowRaw : na), "Prior-only removal lower | age 0 excluded", display = display.data_window)
plot(hold ? (priorOK[1] ? priorHighRaw[1] : na) : (priorOK ? priorHighRaw : na), "Prior-only removal upper | age 0 excluded", display = display.data_window)
plot(vIdentity, "Native RSI identity error | points", precision = 9, display = display.data_window)
plot(episodes and epSide != 0 ? epAge : na, "Confirmed episode age | bars", display = display.data_window)
plot(episodes and epSide != 0 ? epArea : na, "Confirmed episode area | point-bars", display = display.data_window)
plot(entryGroup >= 0 ? entryGroup : na, "Frozen group | 0 UR,1 US,2 LR,3 LS", display = display.data_window)
string panelPos = switch corner
"Bottom right" => position.bottom_right
"Top left" => position.top_left
"Bottom left" => position.bottom_left
=> position.top_right
var table panel = table.new(panelPos, 2, 5, bgcolor = cBg, frame_color = color.new(cMuted, 65), frame_width = 1, border_width = 0)
if barstate.islast
if not showPanel
table.clear(panel, 0, 0, 1, 4)
else
string issue = not research ? "RSI ONLY" : not chart.is_standard ? "STANDARD CHART ONLY" : not vready ? "SETTLING / INVALID DATA" : not vok ? "STATE AUDIT FAILED" : aligned and (directError > TOL or removalError > TOL or (orderAttempted and not orderAudit)) ? "AUDIT FAILED" : ""
string memoryHelp = "RSI = 50 + recent R + older O, with a common denominator. Violet = 50+O, not an older-only RSI. Rounded contributions can differ slightly from rounded RSI. Recent H=" + str.tostring(h) + "; recent mass share=" + f_num(vs) + "%."
string cutHelp = "REMOVE ONE includes the intact RSI and deletion of any ONE term aged 0..H-1. * means a threshold classification can change. It is not a confidence interval or forecast. The entry study uses a DIFFERENT candidate set, ages 1..H-1."
string orderHelp = "Latest snapshot only: reorder the same H signed changes while holding older RSI state fixed. End source value is unchanged. Bounds are not forecasts or probabilities. Intermediate paths need not be economically feasible."
string sampleHelp = "Chart-history dependent. First valid close UTC: " + (na(firstSampleTime) ? "n/a" : str.format_time(firstSampleTime, "yyyy-MM-dd", "UTC")) + "; last: " + (na(lastSampleTime) ? "n/a" : str.format_time(lastSampleTime, "yyyy-MM-dd", "UTC")) + ". Gaps/date boundaries are excluded; no independence or causal claim."
f_row(panel, 0, hold or barstate.isconfirmed ? "RSI | CLOSED" : "RSI | LIVE", f_num(vr) + " | " + (na(vr) ? "NO DATA" : f_name(f_side(vr))), cRSI, "Native ta.rsi(), independent of research readiness. Closed mode holds only the open bar. v3.0.0.")
if page == "Overview"
f_row(panel, 1, "MEMORY", issue != "" ? issue : "R " + f_sign(vp) + " | O " + f_sign(vo), vrel == 2 ? cTest : cText, memoryHelp)
f_row(panel, 2, "REMOVE ONE", not probes ? "OFF" : vdOK ? f_pair(vdLow, vdHigh) + (vf ? " *" : "") : "n/a", vf ? cTest : cText, cutHelp)
f_row(panel, 3, "ORDER RANGE", not orderTest ? "OFF" : aligned and orderAudit ? f_pair(orderLow, orderHigh) : "n/a", cOrder, orderHelp)
f_row(panel, 4, "RECENT MIX", aligned and orderTest ? "EQ " + f_num(effectiveTerms) + "/" + str.tostring(h) + " | AGE " + f_num(meanAge) + "b" : "n/a", cText, "EQ=(sum weighted absolute changes)^2/sum squares, within H. It is concentration-equivalent terms, NOT independent sample size. AGE is their weighted mean age; newest is zero.")
else if page == "Order and concentration"
f_row(panel, 1, "ORDER RANGE", aligned and orderAudit ? f_pair(orderLow, orderHigh) : "n/a", cOrder, orderHelp)
f_row(panel, 2, "ORDER EFFECT", aligned and orderAudit ? f_sign(vr - neutralOrder) + " | POS " + f_num(orderPosition) : "n/a", cText, "Effect = RSI minus equal-recency-weight baseline. It is NOT the mean RSI of permutations. POS is a 0-100 location inside the bounds, NOT a percentile or probability; n/a when the range is zero.")
f_row(panel, 3, "CONCENTRATION", aligned and orderTest ? "EQ " + f_num(effectiveTerms) + " | TOP " + f_num(topShare) + "%" : "n/a", cText, "TOP is the largest weighted recent term divided by recent mass, not total mass. EQ is not statistical confidence.")
f_row(panel, 4, "GAIN / LOSS AGE", aligned and orderTest ? "G " + f_num(gainMeanAge) + "b | L " + f_num(lossMeanAge) + "b" : "n/a", cText, "Separate weighted mean ages within H. A missing side is n/a; this is not the age of the entire RSI memory.")
else if page == "Episodes"
bool usable = research and episodes and chart.is_standard and dateOK and confirmedSample
string ep = epSide == 0 ? "IN RANGE" : f_name(epSide) + " " + str.tostring(epAge) + "b" + (partial ? "+" : "") + " | A " + f_num(epArea)
f_row(panel, 1, "CONFIRMED", usable ? ep : "OFF / OUTSIDE SAMPLE", partial ? cTest : cText, "A = accumulated threshold excess in RSI-point bars. + means a left-censored episode excluded from completions. Peak excess=" + f_num(epPeak) + ". " + sampleHelp)
f_row(panel, 2, "MEDIAN BARS", usable ? "U " + f_num(f_med(upAges)) + " | L " + f_num(f_med(downAges)) : "n/a", cText, "Completed episodes only; current open episode excluded. Not expected remaining duration. Minimum above pool capacity yields n/a.")
float ageRank = usable and epSide != 0 and not partial ? f_rank(epSide == 1 ? upAges : downAges, float(epAge)) : na
float areaRank = usable and epSide != 0 and not partial ? f_rank(epSide == 1 ? upAreas : downAreas, epArea) : na
f_row(panel, 3, "ACTIVE RANK", "AGE " + f_num(ageRank) + " | AREA " + f_num(areaRank), cText, "0-100 midranks versus retained same-side completed episodes. Ties get half weight. Not a survival or reversal probability.")
f_row(panel, 4, "COMPLETIONS", "U " + str.tostring(array.size(upAges)) + " | L " + str.tostring(array.size(downAges)), minSample > capacity ? cTest : cText, sampleHelp)
else if page == "Entry study"
int si = studySide == "Upper" ? 0 : 1
int ix = si * 2
int nr = array.get(counts, ix)
int ns = array.get(counts, ix + 1)
bool on = studyOn and chart.is_standard and dateOK
string state = h < 2 ? "H >= 2 REQUIRED" : not on ? "OFF / INVALID SAMPLE" : str.upper(studySide) + " | +" + str.tostring(horizon) + "b"
string studyHelp = "At the entry close, delete ONE prior term at ages 1..H-1; NEVER age 0. Freeze the label. E = same extreme side at +K; R = uninterrupted same-side closes through +K. Historical RSI persistence, not P/L or a win rate. Entry margin, prior path and settings can confound group differences."
f_row(panel, 0, "PRIOR-TERM STUDY", state, cRSI, studyHelp)
f_row(panel, 1, "PRIOR-RESILIENT", on ? f_stats(nr, array.get(ends, ix), array.get(runs, ix)) : "n/a", cText, "No tested PRIOR-term deletion changes the entry class. It does not mean price resilience. No percentages below the minimum. " + studyHelp)
f_row(panel, 2, "PRIOR-SENSITIVE", on ? f_stats(ns, array.get(ends, ix + 1), array.get(runs, ix + 1)) : "n/a", cText, "Some tested PRIOR-term deletion changes the entry class. It does not predict a reversal. Either group may naturally have few/no observations. " + studyHelp)
f_row(panel, 3, "POOLED BASELINE", on ? f_stats(nr + ns, array.get(ends, ix) + array.get(ends, ix + 1), array.get(runs, ix) + array.get(runs, ix + 1)) : "n/a", cText, "Same selected, classified, matured observations pooled across both groups of this side. Not all market entries and not a control group. " + sampleHelp)
string exclusions = "P " + str.tostring(array.get(pending, si)) + " D " + str.tostring(array.get(dropped, si)) + " X " + str.tostring(array.get(unclassified, si)) + " O " + str.tostring(array.get(overlaps, si))
f_row(panel, 4, "SAMPLE STATUS", on ? exclusions : "n/a", cMuted, "Selected side: P=pending horizon; D=invalid/missing/date-truncated window; X=unclassifiable prior test or numerical threshold boundary; O=overlap skipped. None is counted as an observed failure. Non-overlap is global across both sides. It does not guarantee independence. " + sampleHelp)
else if page == "Diagnostics"
f_row(panel, 0, "BUILD v3.0.0", issue == "" ? "READY" : issue, issue == "" ? cUp : cTest, "Audits below compare the latest snapshot, not all historical bars. n/a is not a pass. RSI remains independent of these research gates.")
f_row(panel, 1, "RSI IDENTITY", f_check(vIdentity), not na(vIdentity) and vIdentity <= TOL ? cUp : cTest, "Native RSI versus 100*G/(G+L), in RSI points. Tolerance 0.000001. Nine decimals are shown.")
f_row(panel, 2, "DIRECT SUM", aligned ? f_check(directError) : "n/a", aligned and directError <= TOL ? cUp : cTest, "Explicit recent weighted sum versus recurrence partition, as percent of total mass. Same tolerance.")
f_row(panel, 3, "REMOVAL AUDIT", not probes ? "OFF" : aligned ? f_check(removalError) : "n/a", aligned and not na(removalError) and removalError <= TOL ? cUp : cTest, "Maximum discrepancy between direct per-term removal and optimized extrema for every available full/prior test. n/a when neither is defined. Does not certify unavailable residuals.")
f_row(panel, 4, "ORDER AUDIT", not orderTest ? "OFF" : not aligned or not orderAttempted ? "n/a" : orderAudit ? "ACTUAL INSIDE BOUNDS" : "FAIL: OUTSIDE BOUNDS", aligned and orderAudit ? cUp : cTest, "Sorted extrema must contain the actual RSI. A zero-width range is valid but has no defined position. " + sampleHelp)
else
f_row(panel, 0, "LEGEND", "DESCRIPTIVE / NO SIGNALS", cText, "Colors and optional marks describe indicator arithmetic, not trading recommendations.")
f_row(panel, 1, "CYAN / VIOLET", "RSI / OLDER BASE", cOld, memoryHelp)
f_row(panel, 2, "GOLD RANGE", "REMOVE ONE / INCLUDES 0", cTest, cutHelp)
f_row(panel, 3, "CIRCLE / SQUARE", "CLASS CHANGE / WIDTH", cOrder, "Optional confirmed events. Circle = full deletion sensitivity appeared; square = envelope width crossed the configured value. Circle has priority if both occur together. No buy/sell arrows.")
f_row(panel, 4, "OPTIONAL STRIP", "COHORT RELATIONSHIP", cMuted, "At 98: mint=both contributions positive; orange=both negative; gold=material opposition; violet=one material cohort; gray=small/mixed. Off by default. Not confidence or a probability.")
// Native threshold alerts do not depend on the research date/sample filters.
bool validPair = not na(rsi) and not na(rsi[1]) and not na(delta)
alertcondition(barstate.isconfirmed and validPair and side == 1 and side[1] != 1, "RSI entered upper threshold", "Confirmed RSI entered the upper threshold. {{ticker}} {{interval}}. Descriptive observation.")
alertcondition(barstate.isconfirmed and validPair and side == -1 and side[1] != -1, "RSI entered lower threshold", "Confirmed RSI entered the lower threshold. {{ticker}} {{interval}}. Descriptive observation.")
alertcondition(barstate.isconfirmed and validPair and side != 1 and side[1] == 1, "RSI left upper threshold", "Confirmed RSI left the upper threshold. {{ticker}} {{interval}}. Descriptive observation.")
alertcondition(barstate.isconfirmed and validPair and side != -1 and side[1] == -1, "RSI left lower threshold", "Confirmed RSI left the lower threshold. {{ticker}} {{interval}}. Descriptive observation.")
alertcondition(barstate.isconfirmed and mathOK and mathOK[1] and opposed and not opposed[1], "Recent and older contributions opposed", "Confirmed recent and older RSI contributions are materially opposed. {{ticker}} {{interval}}. Not a forecast.")
alertcondition(newSensitive, "All-term removal classification changed", "Confirmed RSI classification is newly sensitive to deleting one recent term, including age 0. {{ticker}} {{interval}}. Not the prior-only entry-study label.")
alertcondition(newWide, "All-term removal range widened", "Confirmed one-term removal width crossed its configured threshold. {{ticker}} {{interval}}. Sensitivity only, not a trade instruction.")