本页源码来自 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 (MPL 2.0).
// (c) Unbroke - free & open-source. Not financial advice. For educational purposes only.
// signal grader knn 0.1.1 (Research review fixes; build, not compiled in TradingView yet)
//@version=6
indicator("Unbroke Signal Grader (kNN)", shorttitle = "UB Grader", overlay = true, max_labels_count = 500, max_bars_back = 1000)
// SELF-CHECK TOOL. Simple, open signals (trend breakouts and RSI reversals), each given a similarity grade
// 1-4 at bar close by a k-nearest-neighbors count: of the k most similar past signals whose 24-bar outcome
// window had fully closed, how many moved 1 ATR their way before 1 ATR against. A similarity count, not a
// forecast or a signal. Model: kNN, k = 15, L1 distance, 5 features, no trained weights; fit window = the
// last 500 signals on this chart. Python mirror: knn_grader_ref.py. Leakage rules: LEAKAGE_NOTES.md.
// Idea credit: graded signals are a public idea (made popular by LuxAlgo Signals & Overlays). Original code.
//==============================================================================
// INPUTS
//==============================================================================
G_SIG = "1. Signals"
useTrend = input.bool(true, "Trend signals", group = G_SIG, tooltip = "Fires the first bar that closes above the highest high of the last N bars while the 50 EMA is rising (short: mirror).", display = display.none)
useRev = input.bool(true, "Reversal signals", group = G_SIG, tooltip = "Fires when RSI(14) closes back above 30 (long) or back below 70 (short).", display = display.none)
brkLen = input.int(20, "Breakout lookback (bars)", minval = 5, maxval = 200, group = G_SIG, tooltip = "Pre-registered: 20. How many past bars the trend breakout must clear.", display = display.none)
G_KNN = "2. Grader (kNN)"
kNb = input.int(15, "Neighbors (k)", minval = 3, maxval = 50, group = G_KNN, tooltip = "Pre-registered: 15. Model: k-nearest neighbors (kNN), L1 distance, no trained weights. The grade counts how many of the k most similar closed past signals of the same type moved +1 ATR before -1 ATR within the horizon: 4 = 75%+, 3 = 50-74%, 2 = 25-49%, 1 = under 25%. A similarity count, not a forecast or a signal.", display = display.none)
memCap = input.int(500, "Memory (signals kept)", minval = 50, maxval = 500, group = G_KNN, tooltip = "Pre-registered: 500. Fit window: only the most recent N signals on this chart (trend and reversal together) can be neighbors. Nothing is fitted outside your chart.", display = display.none)
minNb = input.int(30, "Signals needed before grading", minval = 5, maxval = 200, group = G_KNN, tooltip = "Pre-registered: 30. Until this many past signals of the same kind have a finished outcome, new signals show '-' (not graded).", display = display.none)
prkLen = input.int(300, "Feature window (bars)", minval = 50, maxval = 500, group = G_KNN, tooltip = "Pre-registered: 300 (max 500). Features (5): RSI(14), distance from the 50 EMA in ATRs, ATR as % of price, volume vs its 20-bar average, 50 EMA 5-bar slope in ATRs. Each is ranked 0-1 against its own previous N bars only. RSI, distance and slope are flipped for shorts.", display = display.none)
hzBars = input.int(24, "Outcome horizon (bars)", minval = 2, maxval = 200, group = G_KNN, tooltip = "Pre-registered: 24. Label: a signal wins if price moves 1 ATR its way before 1 ATR against within this many bars. Both on one bar = loss. Time out = loss. A past signal is used only after its full outcome window has closed.", display = display.none)
minShow = input.int(1, "Show labels from grade", minval = 1, maxval = 4, group = G_KNN, tooltip = "1 = show every graded signal. 3 = show only grades 3 and 4. Ungraded signals follow 'Show ungraded'.", display = display.none)
showUng = input.bool(true, "Show ungraded signals", group = G_KNN, display = display.none)
G_PRF = "3. Stats panel"
showPanel = input.bool(true, "Show panel", inline = "pp", group = G_PRF, tooltip = "Default Bottom Left. Move it if another Unbroke panel sits there.", display = display.none)
panelPos = input.string("Bottom Left", "", options = ["Bottom Left", "Bottom Right", "Top Right", "Middle Left", "Middle Right"], inline = "pp", group = G_PRF, display = display.none)
panelLift = input.int(6, "Panel offset (% of chart height)", minval = 0, maxval = 60, group = G_PRF, tooltip = "Empty space between the panel and its chart border.", display = display.none)
detailed = input.bool(false, "Detailed panel", group = G_PRF, tooltip = "Adds trend vs reversal rows, the grade 3-4 minus grade 1-2 row and the settings row. The verdict line is always shown.", display = display.none)
dashSize = input.string("Small", "Panel text size", options = ["Tiny", "Small", "Normal"], group = G_PRF, display = display.none)
pRand = input.float(0.05, "Random entry rate (per bar)", minval = 0.005, maxval = 0.5, step = 0.005, group = G_PRF, tooltip = "Share of bars that get a random entry (50/50 long or short), scored with the same 1 ATR rule. This is the baseline row.", display = display.none)
seed = input.int(7, "Random seed", group = G_PRF, tooltip = "Same seed = same random entries every time. The symbol is mixed into the seed, so NQ and ES get different random bars.", display = display.none)
G_DSP = "4. Style"
ubThemeMode = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = G_DSP, tooltip = "Auto follows the chart background.", display = display.none)
showTrend = input.bool(true, "Trend line and cloud", group = G_DSP, tooltip = "50 EMA with glow and a gradient cloud to the 21 EMA. Context only, not part of the grade.", display = display.none)
glowOn = input.bool(true, "Glow on the trend line", group = G_DSP, display = display.none)
lblSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = G_DSP, display = display.none)
G_MC = "5. Match check (Pine vs Python)"
mcOn = input.bool(false, "Match check", group = G_MC, tooltip = "OFF by default. Shows a table of integer checksums and a page of individual signals, computed on confirmed bars only, for the free Pine vs Python match (MATCH_FREE_PLAN.md). Does not change any signal or grade.", display = display.none)
mcPage = input.int(0, "Match page", minval = 0, group = G_MC, tooltip = "0 = the last 15 compared signals. 1 = compared signals 1-15, 2 = 16-30, and so on.", display = display.none)
mcWarm = input.int(1000, "Match warm-up bars", minval = 0, group = G_MC, tooltip = "Signals on bars before this bar index are not compared.", display = display.none)
mcSkip = input.int(0, "Match skip signals after warm-up", minval = 0, group = G_MC, tooltip = "Also skip this many signals after the warm-up bars (old export plan used 500).", display = display.none)
mcSize = input.string("Large", "Match text size", options = ["Normal", "Large", "Huge"], group = G_MC, display = display.none)
//==============================================================================
// UNBROKE STYLE KIT for Pine v6 - paste this block into every Unbroke script.
// (c) Unbroke - MPL 2.0. Original code. ASCII only.
// Paste it AFTER the inputs. The script must declare, before this block:
// string ubThemeMode = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], ...)
// Libraries need publishing, so for now this is pasted, not imported.
// Version: style kit 1.3 (2026-10-24: all table colors opaque; T_BG follows chart.bg_color in Auto). Keep every copy identical.
//==============================================================================
// ---- 1. Palette (fixed brand constants) -------------------------------------
UB_GREEN_DEEP = #1B7A5A // brand green (light-theme frame, deep fills)
UB_GREEN = #3FBF8F // brand green bright (dark-theme frame, bull)
UB_INK = #141210 // dark background / text on light
UB_PAPER = #F6F3EC // light background / text on dark
UB_BULL = #3FBF8F // up / safe / reacted
UB_BEAR = #E5534B // down / danger / broke
UB_NEUTRAL = #8C8A85 // mid lines, neutral state, muted marks
UB_AMBER = #F2A93B // caution, opening range
UB_SKY = #4C9AFF // info levels (previous day), entries
UB_VIOLET = #8B5CF6 // secondary info (London, previous week)
UB_PINK = #E0559A // Asia session
UB_CYAN = #14B8C4 // overnight session
// ---- 2. Theme detection -----------------------------------------------------
ub_lum(color c) =>
0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)
ub_isLight() =>
ub_lum(chart.bg_color) > 128
bool UB_LIGHT = ubThemeMode == "Light" or (ubThemeMode == "Auto" and ub_isLight())
color T_BG = color.new(ubThemeMode == "Auto" ? chart.bg_color : UB_LIGHT ? UB_PAPER : UB_INK, 0)
color T_ROW = color.new(UB_LIGHT ? #FFFFFF : #1E1C19, 0)
color T_HEAD = color.new(UB_LIGHT ? #E3F1EA : #0F2A20, 0)
color T_TEXT = UB_LIGHT ? UB_INK : UB_PAPER
color T_MUTED = UB_LIGHT ? #5C574F : #A8A39A
color T_FRAME = color.new(UB_LIGHT ? UB_GREEN_DEEP : UB_GREEN, 0)
color T_BORDER = color.new(UB_LIGHT ? #E2DCCF : #2A2723, 0)
color T_TRACK = color.new(UB_LIGHT ? #E2DCCF : #2E2B27, 0)
// Readable text on any fill color.
ub_txtOn(color c) =>
ub_lum(c) > 150 ? UB_INK : #FFFFFF
// ---- 3. Sizes and positions -------------------------------------------------
ub_size(string s) =>
s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Large" ? size.large : size.normal
ub_sizeUp(string s) =>
s == "Tiny" ? size.small : s == "Small" ? size.normal : s == "Large" ? size.huge : size.large
ub_pos(string s) =>
s == "Top Right" ? position.top_right : s == "Bottom Right" ? position.bottom_right : s == "Top Left" ? position.top_left : s == "Middle Left" ? position.middle_left : s == "Middle Right" ? position.middle_right : s == "Bottom Center" ? position.bottom_center : s == "Top Center" ? position.top_center : position.bottom_left
// ---- 4. Gradient colors -----------------------------------------------------
// Strength color: bear at lo, neutral at the midpoint, bull at hi.
ub_strength(float v, float lo, float hi) =>
float mid = (lo + hi) / 2.0
v >= mid ? color.from_gradient(v, mid, hi, UB_NEUTRAL, UB_BULL) : color.from_gradient(v, lo, mid, UB_BEAR, UB_NEUTRAL)
// Room color: 0 = red, 50 = amber, 100 = green (risk meters).
ub_room(float pct) =>
pct >= 50 ? color.from_gradient(pct, 50, 100, UB_AMBER, UB_BULL) : color.from_gradient(pct, 0, 50, UB_BEAR, UB_AMBER)
// ---- 5. Glow for drawn lines (plots: see DESIGN_SYSTEM.md, plot() is global-only) --
// g = a var array<line> owned by the caller (created empty). Two halo lines are
// created once, then moved. Call on barstate.islast. x1 = start bar, y = price.
ub_glow(array<line> g, int x1, float y, color c, int baseW, bool on) =>
if array.size(g) == 0
array.push(g, line.new(na, na, na, na, xloc = xloc.bar_index, extend = extend.right, color = color.new(c, 88), width = baseW + 6))
array.push(g, line.new(na, na, na, na, xloc = xloc.bar_index, extend = extend.right, color = color.new(c, 72), width = baseW + 3))
bool ok = on and not na(y) and not na(x1)
for i = 0 to 1
line gl = array.get(g, i)
line.set_x1(gl, ok ? x1 : na)
line.set_x2(gl, ok ? x1 + 1 : na)
line.set_y1(gl, ok ? y : na)
line.set_y2(gl, ok ? y : na)
line.set_color(gl, color.new(c, i == 0 ? 88 : 72))
// ---- 6. Dashboard builder ---------------------------------------------------
// Header row: "UNBROKE" | title (merged) | subtitle. ncols >= 2.
ub_header(table t, int ncols, string title, string sub, hsz) =>
table.cell(t, 0, 0, "UNBROKE", text_color = T_FRAME, bgcolor = T_HEAD, text_size = hsz, text_halign = text.align_left, text_formatting = text.format_bold)
if ncols == 2
table.cell(t, 1, 0, title, text_color = T_TEXT, bgcolor = T_HEAD, text_size = hsz, text_halign = text.align_right, text_formatting = text.format_bold, tooltip = sub)
else
table.cell(t, 1, 0, title, text_color = T_TEXT, bgcolor = T_HEAD, text_size = hsz, text_halign = text.align_left, text_formatting = text.format_bold)
table.cell(t, ncols - 1, 0, sub, text_color = T_MUTED, bgcolor = T_HEAD, text_size = hsz, text_halign = text.align_right)
if ncols > 3
table.merge_cells(t, 1, 0, ncols - 2, 0)
// Footer note across all columns (tiny, muted).
ub_footer(table t, int ncols, int row, string txt) =>
table.cell(t, 0, row, txt, text_color = T_MUTED, bgcolor = T_BG, text_size = size.tiny, text_halign = text.align_left)
if ncols > 1
table.merge_cells(t, 0, row, ncols - 1, row)
// Segmented progress bar in table cells c0 .. c0+segs-1 of one row.
// Each lit segment takes the room color of its own position (red -> amber -> green).
ub_bar(table t, int c0, int row, int segs, float pct, string tip) =>
for i = 0 to segs - 1
float mark = (i + 0.5) * 100.0 / segs
bool lit = not na(pct) and pct >= mark
table.cell(t, c0 + i, row, "", bgcolor = lit ? ub_room(mark) : T_TRACK, width = 1.4, height = 1.6, tooltip = tip)
// ASCII meter, e.g. "######...." for 60% with n = 10.
ub_meter(float pct, int n) =>
int k = na(pct) ? 0 : int(math.round(math.max(0.0, math.min(100.0, pct)) / 100.0 * n))
str.repeat("#", k) + str.repeat(".", n - k)
// ---- 7. PROOF panel (signature element of every Unbroke indicator) ----------
// Percent helper: a of b, as 0-100 float, na when b = 0.
ub_pct(int a, int b) =>
b > 0 ? a * 100.0 / b : na
// Verdict vs random: two-sample 95% margin (normal approximation).
// Returns [text, color]. Below minN samples on either side -> "Not enough data".
ub_verdict(float rate, int n, float base, int nBase, int minN) =>
string txt = "Not enough data"
color col = T_MUTED
if n >= minN and nBase >= minN and not na(rate) and not na(base)
float p1 = rate / 100.0
float p0 = base / 100.0
float m = 196.0 * math.sqrt(p1 * (1 - p1) / n + p0 * (1 - p0) / nBase)
float dlt = rate - base
string tail = " (" + (dlt >= 0 ? "+" : "") + str.tostring(dlt, "0.0") + " pts, 95% CI " + str.tostring(dlt - m, "0.0") + " to " + str.tostring(dlt + m, "0.0") + ", n " + str.tostring(n) + ")"
txt := (dlt - m > 0 ? "Above random" : dlt + m < 0 ? "Below random" : "Inside noise") + tail
col := T_TEXT
[txt, col]
// Proof column headers (5 columns): Signal | n | Win % | vs random | Verdict.
ub_proofHead(table t, int row, string c0, tsz) =>
table.cell(t, 0, row, c0, text_color = T_MUTED, bgcolor = T_BG, text_size = tsz, text_halign = text.align_left)
table.cell(t, 1, row, "n", text_color = T_MUTED, bgcolor = T_BG, text_size = tsz)
table.cell(t, 2, row, "Win %", text_color = T_MUTED, bgcolor = T_BG, text_size = tsz)
table.cell(t, 3, row, "vs random", text_color = T_MUTED, bgcolor = T_BG, text_size = tsz)
table.cell(t, 4, row, "Verdict", text_color = T_MUTED, bgcolor = T_BG, text_size = tsz)
// One proof row. hits/n = this signal, baseRate/nBase = the random baseline.
ub_proofRow(table t, int row, string name, color c, int hits, int n, float baseRate, int nBase, int minN, tsz) =>
float rate = ub_pct(hits, n)
[vTxt, vCol] = ub_verdict(rate, n, baseRate, nBase, minN)
float dlt = na(rate) or na(baseRate) ? na : rate - baseRate
string eTxt = na(dlt) ? "-" : (dlt >= 0 ? "+" : "") + str.tostring(dlt, "#") + " pts"
table.cell(t, 0, row, name, text_color = T_TEXT, bgcolor = color.from_gradient(UB_LIGHT ? 72 : 55, 0, 100, color.new(c, 0), T_ROW), text_size = tsz, text_halign = text.align_left)
table.cell(t, 1, row, str.tostring(n), text_color = n >= minN ? T_TEXT : T_MUTED, bgcolor = T_ROW, text_size = tsz)
color hitBg = T_ROW // neutral: no red/green on win %
table.cell(t, 2, row, na(rate) ? "-" : str.tostring(rate, "#") + "%", text_color = na(rate) ? T_MUTED : T_TEXT, bgcolor = hitBg, text_size = tsz, text_formatting = text.format_bold, tooltip = "Win %: share that moved 1 ATR their way before 1 ATR against.")
table.cell(t, 3, row, eTxt, text_color = na(dlt) ? T_MUTED : T_TEXT, bgcolor = T_ROW, text_size = tsz)
table.cell(t, 4, row, vTxt, text_color = vCol, bgcolor = T_ROW, text_size = tsz, text_formatting = text.format_bold, tooltip = "95% margin test vs the random baseline. Needs at least " + str.tostring(minN) + " samples on both sides.")
//==================================== END UNBROKE STYLE KIT ===================
//==============================================================================
// CORE SERIES (all ta.* calls on every bar, global scope)
//==============================================================================
color C_UP = UB_LIGHT ? #0FA86E : #2EF0A6
color C_DN = UB_LIGHT ? #E0352B : #FF5C52
color T_MUT = UB_LIGHT ? #5A544B : T_MUTED
// Grade colors: ONE hue (blue), intensity only. No green/red, so a grade never reads as buy/avoid.
color G4C = UB_LIGHT ? #1F5FB8 : #9CC4FF
color G3C = UB_LIGHT ? #4F86D6 : #6E9FE6
color G2C = UB_LIGHT ? #8DB0E6 : #4A74B3
color G1C = UB_LIGHT ? #C3D5F2 : #2F4B78
f_gcol(int g) =>
g == 4 ? G4C : g == 3 ? G3C : g == 2 ? G2C : g == 1 ? G1C : UB_NEUTRAL
// Start-up and na rules copy knn_grader_ref.py exactly (pinned reference).
// RMA: skip na, seed with the mean of the first n values, then (s*(n-1)+v)/n.
f_rma(float x, int n) =>
var float s = na
var float acc = 0.0
var int cnt = 0
float out = na
if not na(x)
if na(s)
acc += x
cnt += 1
if cnt == n
s := acc / n
out := s
else
s := (s * (n - 1) + x) / n
out := s
out
// EMA: seed with the mean of the first n values, then s + a*(v-s).
f_ema(float x, int n) =>
var float s = na
var float acc = 0.0
var int cnt = 0
float a = 2.0 / (n + 1)
float out = na
if na(s)
acc += x
cnt += 1
if cnt == n
s := acc / n
out := s
else
s := s + a * (x - s)
out := s
out
// Percent rank: share of the previous n values <= current. na if the current value
// or ANY value in the window is na (the feature then falls back to 0.5).
f_prank(float src, int n) =>
float out = na
if not na(src) and bar_index >= n
int c = 0
bool bad = false
for i = 1 to n
float w = src[i]
if na(w)
bad := true
break
// exact compare (Pine float compares are tolerant)
if (w - src) * 1e20 <= 0
c += 1
out := bad ? na : c * 100.0 / n
out
float pc = close[1]
float trV = na(pc) ? high - low : math.max(high - low, math.abs(high - pc), math.abs(low - pc))
float A = f_rma(trV, 14)
float e21 = f_ema(close, 21)
float e50 = f_ema(close, 50)
float dCh = close - close[1]
float upR = f_rma(na(dCh) ? na : math.max(dCh, 0.0), 14)
float dnR = f_rma(na(dCh) ? na : math.max(-dCh, 0.0), 14)
float rsiV = na(upR) or na(dnR) ? na : dnR == 0 ? 100.0 : upR == 0 ? 0.0 : 100.0 - 100.0 / (1.0 + upR / dnR)
float vAvg = ta.sma(volume, 20)
float volr = vAvg > 0 ? volume / vAvg : na
float slope = bar_index >= 5 ? (e50 - e50[5]) / A : na
float dist = (close - e50) / A
float natr = A / close
float hh = ta.highest(high, brkLen)[1]
float ll = ta.lowest(low, brkLen)[1]
// Past-only feature scaling: percent rank of the current value against its own previous prkLen values.
float fRsi = f_prank(rsiV, prkLen) / 100.0
float fDist = f_prank(dist, prkLen) / 100.0
float fVol = f_prank(natr, prkLen) / 100.0
float fVolr = f_prank(volr, prkLen) / 100.0
float fSlp = f_prank(slope, prkLen) / 100.0
bool conf = barstate.isconfirmed
bool okA = not na(A)
bool brkUp = close > hh
bool brkDn = close < ll
bool tL = useTrend and brkUp and not brkUp[1] and slope > 0
bool tS = useTrend and brkDn and not brkDn[1] and slope < 0
bool rL = useRev and rsiV > 30 and rsiV[1] <= 30
bool rS = useRev and rsiV < 70 and rsiV[1] >= 70
// Ticker hash so different symbols get different random bars (mirrored in knn_grader_ref.py tk_hash).
string TK_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!_:.-&/abcdefghijklmnopqrstuvwxyz"
f_tkHash(string s) =>
int h = 0
int len = str.length(s)
if len > 0
for i = 0 to len - 1
int p = str.pos(TK_ALPHA, str.substring(s, i, i + 1))
h := (h * 31 + (na(p) ? 0 : p + 1)) % 1000003
h
var int tkH = f_tkHash(syminfo.prefix + ":" + syminfo.ticker) % 9973
f_hash(float k) =>
int m = int(math.floor(time / 60000.0)) % 100003
float x = math.sin(m * 12.9898 + seed * 4.1414 + tkH * 0.7071 + k) * 43758.5453
x - math.floor(x)
//==============================================================================
// MEMORY (one row per signal, capped) AND STATS
//==============================================================================
var array<int> mI = array.new<int>() // bar_index of the signal
var array<int> mT = array.new<int>() // 0 trend, 1 reversal
var array<int> mD = array.new<int>() // +1 long, -1 short
var array<int> mG = array.new<int>() // grade given WHEN it fired (0 = ungraded); never changed
var array<int> mW = array.new<int>() // -1 open, 0 loss, 1 win
var array<float> mC = array.new<float>() // entry close
var array<float> mA = array.new<float>() // ATR at entry
var array<float> mF = array.new<float>() // 5 features per signal, flat
// random baseline (pending only)
var array<int> qI = array.new<int>()
var array<int> qD = array.new<int>()
var array<float> qC = array.new<float>()
var array<float> qA = array.new<float>()
// counters: index g*2 (n) and g*2+1 (wins) for g = 0..4; 10/11 random; 12/13 trend; 14/15 reversal
var array<int> cnt = array.new<int>(16, 0)
// closed graded signals, for the block (cluster) CI of the verdict line: block id, group (1 = grade 3-4), win
var array<int> zB = array.new<int>()
var array<int> zH = array.new<int>()
var array<int> zW = array.new<int>()
f_add(int q, int v) =>
cnt.set(q, cnt.get(q) + v)
// Outcome rule shared by signals and random entries. Returns -1 still open, 0 loss, 1 win.
f_res(int i0, int d, float c0, float a0) =>
bool stp = d > 0 ? low <= c0 - a0 : high >= c0 + a0
bool run = d > 0 ? high >= c0 + a0 : low <= c0 - a0
stp ? 0 : run ? 1 : bar_index - i0 >= hzBars ? 0 : -1
//==============================================================================
// 1. RESOLVE OPEN OUTCOMES (bars after the entry only), on confirmed bars
//==============================================================================
if conf and mI.size() > 0
for j = 0 to mI.size() - 1
if mW.get(j) == -1 and bar_index > mI.get(j)
int dec = f_res(mI.get(j), mD.get(j), mC.get(j), mA.get(j))
if dec >= 0
mW.set(j, dec)
int g = mG.get(j)
f_add(g * 2, 1)
f_add(g * 2 + 1, dec)
int tq = mT.get(j) == 0 ? 12 : 14
f_add(tq, 1)
f_add(tq + 1, dec)
if g > 0
zB.push(int(math.floor(mI.get(j) / hzBars)))
zH.push(g >= 3 ? 1 : 0)
zW.push(dec)
// Cap corner case: past 90,000 closed graded signals the oldest are dropped here, but the cnt totals
// still include them, so the verdict CI (from zB/zH/zW) and the point estimate (from cnt) would
// describe slightly different samples. Unreachable in practice (TradingView history gives far fewer).
if zB.size() > 90000
zB.shift()
zH.shift()
zW.shift()
if conf and qI.size() > 0
for j = qI.size() - 1 to 0
if bar_index > qI.get(j)
int dec = f_res(qI.get(j), qD.get(j), qC.get(j), qA.get(j))
if dec >= 0
f_add(10, 1)
f_add(11, dec)
qI.remove(j)
qD.remove(j)
qC.remove(j)
qA.remove(j)
//==============================================================================
// 2. kNN GRADE for a new signal (only neighbors whose window fully closed)
//==============================================================================
f_feat(int d) =>
float a0 = na(fRsi) ? 0.5 : fRsi
float a1 = na(fDist) ? 0.5 : fDist
float a2 = na(fVol) ? 0.5 : fVol
float a3 = na(fVolr) ? 0.5 : fVolr
float a4 = na(fSlp) ? 0.5 : fSlp
array<float> v = array.from(d > 0 ? a0 : 1 - a0, d > 0 ? a1 : 1 - a1, a2, a3, d > 0 ? a4 : 1 - a4)
v
// Returns [grade, share of winning neighbors, eligible count]
f_grade(int typ, array<float> v) =>
array<float> cd = array.new<float>()
array<int> ci = array.new<int>()
array<int> cw = array.new<int>()
int n = mI.size()
if n > 0
for j = 0 to n - 1
// LEAKAGE GUARD: same kind, outcome window fully closed before this bar, outcome known
if mT.get(j) == typ and mI.get(j) + hzBars < bar_index and mW.get(j) >= 0
float s = 0.0
for f = 0 to 4
s += math.abs(mF.get(j * 5 + f) - v.get(f))
cd.push(s)
ci.push(mI.get(j))
cw.push(mW.get(j))
int ne = cd.size()
int g = 0
float p = na
if ne >= minNb
int kk = math.min(kNb, ne)
int wins = 0
for t = 1 to kk
int best = -1
for j = 0 to ne - 1
float dj = cd.get(j)
if dj < 1e9
if best == -1
best := j
else
// Pine float compares are tolerant; scale the exact difference so ulp-level
// ties order exactly like the Python reference (np.lexsort on raw floats).
float dd = (dj - cd.get(best)) * 1e20
if dd < 0 or (dd == 0 and ci.get(j) > ci.get(best))
best := j
wins += cw.get(best)
cd.set(best, 1e9)
p := wins / float(kk)
g := p >= 0.75 ? 4 : p >= 0.5 ? 3 : p >= 0.25 ? 2 : 1
[g, p, ne]
f_push(int typ, int d, int g, array<float> v) =>
mI.push(bar_index)
mT.push(typ)
mD.push(d)
mG.push(g)
mW.push(-1)
mC.push(close)
mA.push(A)
for f = 0 to 4
mF.push(v.get(f))
if mI.size() > memCap
mI.shift()
mT.shift()
mD.shift()
mG.shift()
mW.shift()
mC.shift()
mA.shift()
for f = 0 to 4
mF.shift()
//==============================================================================
// 3. NEW SIGNALS (bar close only), LABELS, ALERTS
//==============================================================================
int lastG = -1
// Export values for the Pine <-> Python match (Data Window / chart-data CSV): code = dir * (10 + grade), share in %.
float exT = na
float exR = na
float exTp = na
float exRp = na
var int shG = -1
var int shD = 0
var int shT = 0
var float shP = na
var int shNe = 0
f_label(int typ, int d, int g, float p, int ne) =>
bool show = g == 0 ? showUng : g >= minShow
if show
color c = f_gcol(g)
string txt = (typ == 0 ? "T" : "R") + (g == 0 ? "-" : str.tostring(g))
string tip = (typ == 0 ? "Trend " : "Reversal ") + (d > 0 ? "long" : "short") + " | entry " + str.tostring(close, format.mintick) + " | " + (g == 0 ? "grade - (warming up: " + str.tostring(ne) + " of " + str.tostring(minNb) + " closed past signals)" : "grade " + str.tostring(g) + ": " + str.tostring(p * 100, "0") + "% of the " + str.tostring(math.min(kNb, ne)) + " most similar closed past signals moved 1 ATR their way first. Description only, not a forecast.")
label.new(bar_index, close, txt, yloc = d > 0 ? yloc.belowbar : yloc.abovebar, style = d > 0 ? label.style_label_up : label.style_label_down, color = color.new(c, 8), textcolor = ub_txtOn(c), size = ub_size(lblSize), tooltip = tip)
f_signal(int typ, int d) =>
array<float> v = f_feat(d)
[g, p, ne] = f_grade(typ, v)
f_push(typ, d, g, v)
f_label(typ, d, g, p, ne)
[g, p, ne]
if conf and okA
if tL
[g, p, ne] = f_signal(0, 1)
lastG := g
exT := 1 * (10 + g)
exTp := na(p) ? -1 : p * 100
shG := g
shD := 1
shT := 0
shP := p
shNe := ne
if tS
[g, p, ne] = f_signal(0, -1)
lastG := g
exT := -1 * (10 + g)
exTp := na(p) ? -1 : p * 100
shG := g
shD := -1
shT := 0
shP := p
shNe := ne
if rL
[g, p, ne] = f_signal(1, 1)
lastG := g
exR := 1 * (10 + g)
exRp := na(p) ? -1 : p * 100
shG := g
shD := 1
shT := 1
shP := p
shNe := ne
if rS
[g, p, ne] = f_signal(1, -1)
lastG := g
exR := -1 * (10 + g)
exRp := na(p) ? -1 : p * 100
shG := g
shD := -1
shT := 1
shP := p
shNe := ne
if bar_index > prkLen and f_hash(0.0) < pRand
qI.push(bar_index)
qD.push(f_hash(78.233) < 0.5 ? 1 : -1)
qC.push(close)
qA.push(A)
// MATCH CHECK record (confirmed bars only; integers only; read-only use of exT / exR)
var int mcFirstT = time
var int mcN = 0
var int mcLastT = na
var int mcSeen = 0
var int mcH1 = 0
var int mcH2 = 0
var array<int> mcCnt = array.new<int>(10, 0)
var array<int> mcTm = array.new<int>()
var array<int> mcCd = array.new<int>()
var array<int> mcBi = array.new<int>()
if mcOn and conf
mcN := bar_index + 1
mcLastT := time
for typ = 0 to 1
float code = typ == 0 ? exT : exR
if not na(code) and bar_index >= mcWarm
mcSeen += 1
if mcSeen > mcSkip
int d = code > 0 ? 1 : -1
int g = int(math.abs(code)) - 10
int k = typ * 20 + (d > 0 ? 0 : 10) + g + 1
mcCnt.set(typ * 5 + g, mcCnt.get(typ * 5 + g) + 1)
mcH1 := (mcH1 + (bar_index + 1) * k) % 1000003
mcH2 := (mcH2 * 131 + bar_index * 37 + k) % 1000003
mcTm.push(time)
mcCd.push(k)
mcBi.push(bar_index)
bool newSig = lastG >= 0
// One alert only. No grade-filtered alerts: grades are a description, not a trade tier.
alertcondition(newSig, "Any new signal", "Unbroke Signal Grader: new signal at bar close (similarity grade on label; not a trade signal)")
plot(exT, "Export trend code", color = UB_NEUTRAL, display = display.data_window)
plot(exTp, "Export trend share %", color = UB_NEUTRAL, display = display.data_window)
plot(exR, "Export reversal code", color = UB_NEUTRAL, display = display.data_window)
plot(exRp, "Export reversal share %", color = UB_NEUTRAL, display = display.data_window)
//==============================================================================
// 4. TREND CONTEXT VISUALS (glow line + gradient cloud)
//==============================================================================
color tc = slope > 0 ? C_UP : slope < 0 ? C_DN : UB_NEUTRAL
p21 = plot(showTrend ? e21 : na, "EMA 21", color = color.new(tc, 70), linewidth = 1, display = display.pane)
p50 = plot(showTrend ? e50 : na, "Trend line (EMA 50)", color = tc, linewidth = 2, display = display.pane)
plot(showTrend and glowOn ? e50 : na, "Glow 1", color = color.new(tc, 72), linewidth = 5, display = display.pane)
plot(showTrend and glowOn ? e50 : na, "Glow 2", color = color.new(tc, 88), linewidth = 8, display = display.pane)
fill(p21, p50, math.max(e21, e50), math.min(e21, e50), color.new(tc, UB_LIGHT ? 70 : 62), color.new(tc, 94), "Trend cloud")
//==============================================================================
// 5. STATS PANEL (descriptive; each signal counted with the grade it got when it fired)
//==============================================================================
var table panel = na
f_cell(int c, int r, string t, color tcol, string tip = "") =>
panel.cell(c, r, t, text_color = tcol, bgcolor = T_ROW, text_size = ub_size(dashSize), text_halign = c == 0 ? text.align_left : text.align_center, tooltip = tip)
f_rt(int h, int n) => n > 0 ? str.tostring(100.0 * h / n, "0") + "%" : "-"
f_ci(int h, int n) =>
string out = "-"
if n > 0
float z = 1.96
float p = h / float(n)
float d = 1 + z * z / n
float m = (p + z * z / (2 * n)) / d
float w = z * math.sqrt(p * (1 - p) / n + z * z / (4.0 * n * n)) / d
out := str.tostring(100 * (m - w), "0") + "-" + str.tostring(100 * (m + w), "0") + "%"
out
f_row(int r, string name, color nc, int h, int n, string tip) =>
panel.cell(0, r, name, text_color = T_TEXT, bgcolor = color.from_gradient(UB_LIGHT ? 72 : 55, 0, 100, nc, T_ROW), text_size = ub_size(dashSize), text_halign = text.align_left, tooltip = tip)
f_cell(1, r, str.tostring(n) + (n >= 30 and n < 100 ? " preview" : ""), n >= 30 ? T_TEXT : T_MUT, "Closed signals in this group. Under 30 = too few to read; under 100 = preview.")
bool few = n < 30
color bg = T_ROW // neutral row color, same idea as the single-hue grade scale
panel.cell(2, r, few ? (n > 0 ? "too few" : "-") : f_rt(h, n), text_color = few ? T_MUT : T_TEXT, bgcolor = bg, text_size = ub_size(dashSize), text_formatting = few ? text.format_none : text.format_bold, tooltip = "Win %: share that moved 1 ATR their way before 1 ATR against. Needs 30 closed signals. Plain cell color on purpose: compare the numbers, not colors.")
f_cell(3, r, few ? "-" : f_ci(h, n), T_MUT, "Wilson 95% interval. Overlapping trades make it look tighter than it really is.")
int nb = cnt.get(10)
string vs = "-"
if not few and nb >= 30
float dd = 100.0 * h / n - 100.0 * cnt.get(11) / nb
vs := (dd >= 0 ? "+" : "") + str.tostring(dd, "0") + " pts"
f_cell(4, r, vs, T_TEXT, "Win % minus the random-entry win %. Shown only with 30+ closed trades on both sides. Descriptive, not a verdict.")
// Grade 3-4 vs grade 1-2 win % on closed signals, with a block (cluster-robust) 95% CI:
// signals are grouped into blocks of hzBars bars so overlapping outcome windows are not counted as independent.
f_sep() =>
int nH = cnt.get(6) + cnt.get(8)
int hH = cnt.get(7) + cnt.get(9)
int nL = cnt.get(2) + cnt.get(4)
int hL = cnt.get(3) + cnt.get(5)
float d = na
float lo = na
float hi = na
if nH > 0 and nL > 0
float pH = hH / float(nH)
float pL = hL / float(nL)
d := 100.0 * (pH - pL)
map<int, float> u = map.new<int, float>()
int nz = zB.size()
if nz > 0
for k = 0 to nz - 1
int b = zB.get(k)
float w = zW.get(k)
float infl = zH.get(k) == 1 ? (w - pH) / nH : -(w - pL) / nL
float prev = u.contains(b) ? u.get(b) : 0.0
u.put(b, prev + infl)
int nb = u.size()
if nb > 1
float ss = 0.0
for val in u.values()
ss += val * val
float se = 100.0 * math.sqrt(ss * nb / (nb - 1))
lo := d - 1.96 * se
hi := d + 1.96 * se
[nH, nL, d, lo, hi]
f_verdict(int nH, int nL, float lo, float hi) =>
int nMin = math.min(nH, nL)
string v = not na(lo) and lo > 0 ? "Higher grades did better so far. Could be chance; not a forecast." : not na(hi) and hi < 0 ? "Grades on this chart: higher grades did worse so far." : "No difference between grades so far. Treat grades as noise here."
nMin < 30 ? "Too few closed signals to judge (need 30 in each group)." : nMin < 100 ? "Preview (under 100 in a group): " + v : v
if barstate.islast and showPanel
bool topSide = panelPos == "Top Right"
if na(panel)
panel := table.new(ub_pos(panelPos), 5, 22, bgcolor = na, frame_color = na, frame_width = 0, border_color = T_BORDER, border_width = 1)
panel.clear(0, 0, 4, 21)
int r = 0
if panelLift > 0 and topSide
panel.cell(0, r, "", bgcolor = color.new(T_BG, 100), height = panelLift)
panel.merge_cells(0, r, 4, r)
r += 1
panel.cell(0, r, "UNBROKE", text_color = T_FRAME, bgcolor = T_HEAD, text_size = ub_size(dashSize), text_halign = text.align_left, text_formatting = text.format_bold)
panel.cell(1, r, "Signal Grader (kNN) - self-check tool", text_color = T_TEXT, bgcolor = T_HEAD, text_size = ub_size(dashSize), text_halign = text.align_left, text_formatting = text.format_bold)
panel.cell(4, r, timeframe.period + " | " + str.tostring(hzBars) + " bars", text_color = T_MUT, bgcolor = T_HEAD, text_size = ub_size(dashSize), text_halign = text.align_right)
panel.merge_cells(1, r, 3, r)
r += 1
// Always-visible verdict line (not tied to the Detailed toggle)
[vH, vL, vD, vLo, vHi] = f_sep()
string vTxt = f_verdict(vH, vL, vLo, vHi)
string vSub = "Grades 3-4 vs 1-2, closed signals: n " + str.tostring(vH) + " vs " + str.tostring(vL) + (na(vD) ? "" : " | " + (vD >= 0 ? "+" : "") + str.tostring(vD, "0.0") + " pts" + (na(vLo) ? "" : ", 95% CI " + str.tostring(vLo, "0.0") + " to " + str.tostring(vHi, "0.0")))
panel.cell(0, r, vTxt + "\n" + vSub, text_color = T_TEXT, bgcolor = T_HEAD, text_size = ub_size(dashSize), text_halign = text.align_left, text_formatting = text.format_bold, tooltip = "Verdict on this chart: win % of grade 3-4 signals vs grade 1-2 signals, with a 95% range that treats each " + str.tostring(hzBars) + "-bar block as one unit (overlapping trades). Under 30 in either group = too few; under 100 = preview. Even a difference can be chance.")
panel.merge_cells(0, r, 4, r)
r += 1
panel.cell(0, r, "Closed trades only", text_color = T_MUT, bgcolor = T_BG, text_size = ub_size(dashSize), text_halign = text.align_left, tooltip = "Each signal keeps the grade it got when it fired. Only finished outcomes are counted.")
panel.cell(1, r, "n", text_color = T_MUT, bgcolor = T_BG, text_size = ub_size(dashSize))
panel.cell(2, r, "Win %", text_color = T_MUT, bgcolor = T_BG, text_size = ub_size(dashSize))
panel.cell(3, r, "95% CI", text_color = T_MUT, bgcolor = T_BG, text_size = ub_size(dashSize))
panel.cell(4, r, "vs random", text_color = T_MUT, bgcolor = T_BG, text_size = ub_size(dashSize))
r += 1
f_row(r, "Random entries", UB_NEUTRAL, cnt.get(11), cnt.get(10), "Baseline: seeded random bars (" + str.tostring(pRand * 100, "0.0") + "% of bars, 50/50 long or short), same 1 ATR rule.")
r += 1
for g = 4 to 1
f_row(r, "Grade " + str.tostring(g), f_gcol(g), cnt.get(g * 2 + 1), cnt.get(g * 2), "Signals that got grade " + str.tostring(g) + " when they fired.")
r += 1
f_row(r, "Not graded (warm-up)", UB_NEUTRAL, cnt.get(1), cnt.get(0), "Signals that fired before " + str.tostring(minNb) + " closed past signals of the same kind existed.")
r += 1
if detailed
f_row(r, "Trend signals", UB_SKY, cnt.get(13), cnt.get(12), "All trend breakout signals, any grade.")
r += 1
f_row(r, "Reversal signals", UB_VIOLET, cnt.get(15), cnt.get(14), "All RSI reversal signals, any grade.")
r += 1
f_cell(0, r, "Grade 3-4 minus 1-2", T_TEXT, "Does a higher grade line up with a higher win %? 95% range with " + str.tostring(hzBars) + "-bar blocks (overlapping trades).")
if math.min(vH, vL) >= 30 and not na(vLo)
f_cell(1, r, str.tostring(vH + vL), T_MUT)
f_cell(2, r, (vD >= 0 ? "+" : "") + str.tostring(vD, "0.0") + " pts", T_TEXT)
f_cell(3, r, str.tostring(vLo, "0.0") + " to " + str.tostring(vHi, "0.0"), T_MUT)
f_cell(4, r, vLo > 0 ? "higher" : vHi < 0 ? "lower" : "inside noise", T_MUT)
else
f_cell(1, r, str.tostring(vH + vL), T_MUT)
f_cell(2, r, "-", T_MUT)
f_cell(3, r, "-", T_MUT)
f_cell(4, r, "too few", T_MUT)
r += 1
f_cell(0, r, "kNN, k " + str.tostring(kNb) + ", L1 | fit window: last " + str.tostring(memCap) + " signals | min " + str.tostring(minNb) + " | 5 features over " + str.tostring(prkLen) + " bars | seed " + str.tostring(seed) + " | bar close only", T_MUT)
panel.merge_cells(0, r, 4, r)
r += 1
f_cell(0, r, "Last signal", T_TEXT, "The most recent signal and the grade it got at its close.")
color lc = f_gcol(shG)
string gtxt = shG < 0 ? "-" : shG == 0 ? "not graded" : "Grade " + str.tostring(shG)
panel.cell(1, r, shG < 0 ? "-" : (shT == 0 ? "Trend " : "Reversal ") + (shD > 0 ? "long" : "short"), text_color = T_TEXT, bgcolor = T_ROW, text_size = ub_size(dashSize))
panel.merge_cells(1, r, 2, r)
panel.cell(3, r, gtxt, text_color = shG < 0 ? T_MUT : ub_txtOn(lc), bgcolor = shG < 0 ? T_ROW : lc, text_size = ub_size(dashSize), text_formatting = text.format_bold)
f_cell(4, r, na(shP) ? "-" : str.tostring(shP * 100, "0") + "% of k", T_MUT, "Share of the k most similar closed past signals that moved 1 ATR their way first. Description only, not a forecast.")
r += 1
string disc = "signal grader knn 0.1.1 | Grades count how similar past signals on this chart played out; they are not a forecast or a signal. A past signal is used only after its full 24-bar outcome window has closed. Grades are set at bar close and never change. Outcomes, which need the next 24 bars, are used only to score signals that have already finished. Educational, not financial advice. Past results don't predict future results."
panel.cell(0, r, "A similarity count, not a forecast or a signal.", text_color = T_MUT, bgcolor = T_BG, text_size = ub_size(dashSize), text_halign = text.align_left, tooltip = disc)
panel.merge_cells(0, r, 4, r)
r += 1
panel.cell(0, r, "Educational, not financial advice. Past results don't predict future results.", text_color = T_MUT, bgcolor = T_BG, text_size = ub_size(dashSize), text_halign = text.align_left, tooltip = disc)
panel.merge_cells(0, r, 4, r)
r += 1
if panelLift > 0 and not topSide
panel.cell(0, r, "", bgcolor = color.new(T_BG, 100), height = panelLift)
panel.merge_cells(0, r, 4, r)
//==============================================================================
// MATCH CHECK TABLE (Match check input; off by default)
//==============================================================================
var table mcTab = na
f_iso(int t) => na(t) ? "-" : str.format_time(t, "yyyy-MM-dd'T'HH:mm'Z'", "UTC")
f_mcCode(int k) =>
int typ = int(math.floor((k - 1) / 20.0))
int r = (k - 1) % 20
int d = r >= 10 ? -1 : 1
int g = r % 10
(typ == 0 ? "T" : "R") + (d > 0 ? " L " : " S ") + (g == 0 ? "-" : str.tostring(g)) + " (k" + str.tostring(k) + ")"
f_mcLine(int r, string s) =>
mcTab.cell(0, r, s, text_color = T_TEXT, bgcolor = T_ROW, text_size = mcSize == "Huge" ? size.huge : mcSize == "Large" ? size.large : size.normal, text_halign = text.align_left, text_font_family = font.family_monospace)
0 // explicit return (CE10235)
if mcOn and barstate.islast
if na(mcTab)
mcTab := table.new(position.top_right, 1, 24, bgcolor = T_ROW, frame_color = T_FRAME, frame_width = 1, border_color = T_BORDER, border_width = 0)
mcTab.clear(0, 0, 0, 23)
string tk1 = syminfo.prefix + ":" + syminfo.ticker
int nC = mcTm.size()
f_mcLine(0, "MATCH kNN 0.1.1 | " + syminfo.tickerid + " | " + timeframe.period)
f_mcLine(1, "seed str " + tk1 + " | tkhash " + str.tostring(f_tkHash(tk1)) + " | mod9973 " + str.tostring(tkH))
f_mcLine(2, "first " + f_iso(mcFirstT) + " | bars " + str.tostring(mcN) + " | last " + f_iso(mcLastT))
f_mcLine(3, "warm " + str.tostring(mcWarm) + " skip " + str.tostring(mcSkip) + " | compared " + str.tostring(nC) + " | H1 " + str.tostring(mcH1) + " | H2 " + str.tostring(mcH2))
f_mcLine(4, "trend g0-4: " + str.tostring(mcCnt.get(0)) + " " + str.tostring(mcCnt.get(1)) + " " + str.tostring(mcCnt.get(2)) + " " + str.tostring(mcCnt.get(3)) + " " + str.tostring(mcCnt.get(4)))
f_mcLine(5, "rev g0-4: " + str.tostring(mcCnt.get(5)) + " " + str.tostring(mcCnt.get(6)) + " " + str.tostring(mcCnt.get(7)) + " " + str.tostring(mcCnt.get(8)) + " " + str.tostring(mcCnt.get(9)))
int a = mcPage == 0 ? math.max(0, nC - 15) : (mcPage - 1) * 15
int b = math.min(nC, a + 15)
int nP = int(math.ceil(nC / 15.0))
f_mcLine(6, "page " + (mcPage == 0 ? "last" : str.tostring(mcPage)) + " of " + str.tostring(nP) + " | signals " + str.tostring(a + 1) + "-" + str.tostring(b))
int r = 7
if b > a
for q = a to b - 1
f_mcLine(r, str.format("{0,number,000}", q + 1) + " " + f_iso(mcTm.get(q)) + " bar " + str.tostring(mcBi.get(q)) + " " + f_mcCode(mcCd.get(q)))
r += 1