本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) Unbroke - free & open-source. Not financial advice. For educational purposes only.
// reversal signals + kernel bands 1.0.4
//@version=6
indicator("Unbroke Reversal Signals + Kernel Bands", shorttitle = "UB Kernel", overlay = true, max_bars_back = 500)
// A Gaussian-kernel (Nadaraya-Watson style) smoothing line with ATR bands, and reversal marks when price
// pokes outside a band and closes back inside. ENDPOINT version only: each bar's kernel value uses only that bar
// and older bars, so past values never change (no repaint). This is smoother-lagging than the redrawing
// "full window" versions, by design. Proof panel: reversals and kernel turns vs seeded random bars.
// Python port: tools/kernel_bands_mirror.py. Spec: specs/kernel_bands_spec.md. Original code.
//==============================================================================
// INPUTS
//==============================================================================
G_K = "Kernel"
kH = input.float(8.0, "Bandwidth", minval = 1, maxval = 100, step = 0.5, group = G_K, tooltip = "Gaussian kernel bandwidth in bars. Higher = smoother, more lag.", display = display.none)
kN = input.int(50, "Lookback (bars)", minval = 5, maxval = 300, group = G_K, tooltip = "How many past bars the kernel averages. Endpoint only: no future bars are used.", display = display.none)
bandK = input.float(2.0, "Band width x ATR(50)", minval = 0.5, maxval = 10, step = 0.1, group = G_K, display = display.none)
G_S = "Reversal marks"
showRev = input.bool(true, "Show reversal marks", group = G_S, tooltip = "Bull: the previous bar's low was below the lower band and this bar closes back above it. Bear: the mirror at the upper band. Marked at bar close.", display = display.none)
showTurn = input.bool(false, "Show kernel turns", group = G_S, tooltip = "Small dot where the kernel line changes direction.", display = display.none)
lblGap = input.int(10, "Min bars between markers", minval = 0, maxval = 200, group = G_S, tooltip = "Display only: a same-direction reversal within this many bars of the last drawn mark is not drawn, so choppy stretches stay readable. It still counts in the Proof panel and still fires its alert.", display = display.none)
G_PRF = "Proof panel"
showPanel = input.bool(true, "Show Proof panel", inline = "pp", group = G_PRF, tooltip = "How often each signal ran 1 ATR(14) its way before 1 ATR against, compared with random bars scored the same way.", display = display.none)
panelPos = input.string("Top Right", "", options = ["Top Right", "Bottom Left", "Middle Left", "Top Left", "Bottom Right", "Middle Right"], inline = "pp", group = G_PRF, display = display.none)
hzBars = input.int(24, "Horizon (bars)", minval = 2, maxval = 500, group = G_PRF, tooltip = "A signal is a hit when price runs 1 ATR(14) its way before 1 ATR against within this many bars, from the signal bar close. Both on one bar = against.", display = display.none)
minN = input.int(20, "Minimum cases for a verdict", minval = 5, maxval = 500, 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, seeded so it is the same every time.", display = display.none)
seed = input.int(7, "Random seed", group = G_PRF, display = display.none)
G_DSP = "Style"
ubThemeMode = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = G_DSP, tooltip = "Auto follows the chart background.", display = display.none)
dashSize = input.string("Small", "Panel text size", options = ["Tiny", "Small", "Normal"], group = G_DSP, display = display.none)
xpOn = input.bool(false, "Export mode (port check)", group = G_DSP, tooltip = "Adds 'KRB XP' columns to the Data Window and Export chart data, for tools/kernel_bands_mirror.py.", display = display.none)
//==============================================================================
// UNBROKE STYLE KIT for Pine v6 (style kit 1.3, pasted unchanged below the header). Original code. ASCII only.
//==============================================================================
// ---- 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 or ub_lum(chart.fg_color) < 100
bool UB_LIGHT = ubThemeMode == "Light" or (ubThemeMode == "Auto" and ub_isLight())
color T_BG = color.new(UB_LIGHT ? UB_PAPER : ubThemeMode == "Auto" ? chart.bg_color : 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.small, 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 = UB_LIGHT ? color.from_gradient(45, 0, 100, T_MUTED, UB_INK) : 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 edge = rate - base
if edge > m
txt := "Beats random"
col := UB_LIGHT ? color.from_gradient(45, 0, 100, UB_BULL, UB_INK) : UB_BULL
else if edge < -m
txt := "Worse than random"
col := UB_LIGHT ? color.from_gradient(35, 0, 100, UB_BEAR, UB_INK) : UB_BEAR
else
txt := "Inside noise"
col := UB_LIGHT ? color.from_gradient(55, 0, 100, UB_AMBER, UB_INK) : UB_AMBER
[txt, col]
// Proof column headers (5 columns): Signal | n | Hit % | 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, "Hit %", 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 edge = na(rate) or na(baseRate) ? na : rate - baseRate
string eTxt = na(edge) ? "-" : (edge >= 0 ? "+" : "") + str.tostring(edge, "#") + " 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 = na(rate) ? T_ROW : UB_LIGHT ? color.from_gradient(35, 0, 100, ub_strength(rate, 0, 100), #FFFFFF) : ub_strength(rate, 0, 100)
table.cell(t, 2, row, na(rate) ? "-" : str.tostring(rate, "#") + "%", text_color = na(rate) ? T_MUTED : ub_txtOn(hitBg), bgcolor = hitBg, text_size = tsz, text_formatting = text.format_bold, tooltip = "Hit rate. Cell color: red = low, grey = 50%, green = high.")
table.cell(t, 3, row, eTxt, text_color = na(edge) ? T_MUTED : edge >= 0 ? UB_BULL : UB_BEAR, 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.")
//==============================================================================
// CALCULATIONS
//==============================================================================
float A = ta.atr(14)
float AW = ta.atr(50)
int WARM = 300
bool ok = bar_index >= WARM and not na(A) and not na(AW)
// Endpoint Gaussian kernel: weights exp(-i^2 / (2 h^2)) on close[i], i = 0 .. n-1 (current and past bars only).
f_kernel(float src, float h, int n) =>
float num = 0.0
float den = 0.0
for i = 0 to n - 1
float w = math.exp(-(i * i) / (2.0 * h * h))
num += w * src[i]
den += w
bar_index < n ? na : num / den
float kv = f_kernel(close, kH, kN)
float bUp = kv + bandK * AW
float bDn = kv - bandK * AW
var int kd = 0
kd := na(kv) or na(kv[1]) ? 0 : kv > kv[1] ? 1 : kv < kv[1] ? -1 : kd
bool turn = kd != 0 and nz(kd[1]) != 0 and kd != kd[1]
bool revUp = not na(bDn[1]) and low[1] < bDn[1] and close > bDn and barstate.isconfirmed
bool revDn = not na(bUp[1]) and high[1] > bUp[1] and close < bUp and barstate.isconfirmed
int rev = revUp and not revDn ? 1 : revDn and not revUp ? -1 : 0
//==============================================================================
// PROOF ENGINE: pending entries scored from the next bar on (1 ATR its way before 1 ATR against)
//==============================================================================
var array<int> pI = array.new<int>()
var array<int> pD = array.new<int>()
var array<float> pC = array.new<float>()
var array<float> pA = array.new<float>()
var array<int> pK = array.new<int>()
var array<int> cN = array.new<int>(5, 0)
var array<int> cH = array.new<int>(5, 0)
array<int> xr = array.new<int>(2, 0) // resolved, hits on this bar (all kinds)
f_hash(float k) =>
int m = int(math.floor(time / 60000.0)) % 100003
float x = math.sin(m * 12.9898 + seed * 4.1414 + k) * 43758.5453
x - math.floor(x)
if pI.size() > 0
for j = pI.size() - 1 to 0
int d = pD.get(j)
float cE = pC.get(j)
float aE = pA.get(j)
bool stp = d > 0 ? low <= cE - aE : high >= cE + aE
bool run = d > 0 ? high >= cE + aE : low <= cE - aE
int dec = stp ? 0 : run ? 1 : bar_index - pI.get(j) >= hzBars ? 0 : -1
if dec >= 0
int k = pK.get(j)
cN.set(k, cN.get(k) + 1)
cH.set(k, cH.get(k) + dec)
xr.set(0, xr.get(0) + 1)
xr.set(1, xr.get(1) + dec)
pI.remove(j)
pD.remove(j)
pC.remove(j)
pA.remove(j)
pK.remove(j)
f_pend(int d, int k) =>
pI.push(bar_index)
pD.push(d)
pC.push(close)
pA.push(A)
pK.push(k)
// kinds: 0 random, 1 all reversals, 2 reversal with kernel slope, 3 reversal against kernel slope, 4 kernel turn
int xRnd = 0
if ok
if rev != 0
f_pend(rev, 1)
f_pend(rev, kd == rev ? 2 : 3)
if turn and barstate.isconfirmed
f_pend(kd, 4)
if f_hash(0.0) < pRand
xRnd := f_hash(78.233) < 0.5 ? 1 : -1
f_pend(xRnd, 0)
//==============================================================================
// DRAWING
//==============================================================================
color C_UP = UB_LIGHT ? #0FA86E : #2EF0A6
color C_DN = UB_LIGHT ? #E0352B : #FF5C52
color kc = kd == 1 ? C_UP : kd == -1 ? C_DN : UB_NEUTRAL
plot(kv, "Kernel glow", color.new(kc, UB_LIGHT ? 80 : 75), 6, display = display.pane)
pK0 = plot(kv, "Kernel", kc, 2, display = display.pane + display.price_scale)
pBu = plot(bUp, "Upper band", color.new(C_DN, 45), 1, display = display.pane)
pBd = plot(bDn, "Lower band", color.new(C_UP, 45), 1, display = display.pane)
fill(pBu, pK0, bUp, kv, color.new(C_DN, UB_LIGHT ? 80 : 74), color.new(C_DN, 97), "Upper zone")
fill(pK0, pBd, kv, bDn, color.new(C_UP, 97), color.new(C_UP, UB_LIGHT ? 80 : 74), "Lower zone")
// Display-only marker spacing (stats and alerts use rev, not these).
var int lastUpMk = -100000
var int lastDnMk = -100000
bool drawUp = rev == 1 and bar_index - lastUpMk > lblGap
bool drawDn = rev == -1 and bar_index - lastDnMk > lblGap
if drawUp and barstate.isconfirmed
lastUpMk := bar_index
if drawDn and barstate.isconfirmed
lastDnMk := bar_index
plotshape(showRev and drawUp, "Bull reversal", shape.triangleup, location.belowbar, C_UP, size = size.small, display = display.pane)
plotshape(showRev and drawDn, "Bear reversal", shape.triangledown, location.abovebar, C_DN, size = size.small, display = display.pane)
plotshape(showTurn and turn and barstate.isconfirmed ? kv : na, "Kernel turn", shape.circle, location.absolute, color.new(kc, 10), size = size.tiny, display = display.pane)
alertcondition(rev == 1, "Bull reversal", "Unbroke Kernel Bands: bull reversal at the lower band (bar close)")
alertcondition(rev == -1, "Bear reversal", "Unbroke Kernel Bands: bear reversal at the upper band (bar close)")
alertcondition(turn and barstate.isconfirmed, "Kernel turn", "Unbroke Kernel Bands: kernel line changed direction")
plot(xpOn ? 100 : na, "KRB XP ver", display = display.data_window)
plot(xpOn ? kv : na, "KRB XP kernel", display = display.data_window)
plot(xpOn ? rev : na, "KRB XP rev", display = display.data_window)
plot(xpOn ? kd : na, "KRB XP slope", display = display.data_window)
plot(xpOn ? xRnd : na, "KRB XP rnd", display = display.data_window)
//==============================================================================
// PROOF PANEL
//==============================================================================
var table panel = na
if barstate.islast and showPanel
if na(panel)
panel := table.new(ub_pos(panelPos), 5, 9, bgcolor = na, frame_color = T_FRAME, frame_width = 1, border_color = T_BORDER, border_width = 1)
panel.clear(0, 0, 4, 8)
tsz = ub_size(dashSize)
ub_header(panel, 5, "Kernel Bands Proof", timeframe.period + " | " + str.tostring(hzBars) + " bars", tsz)
ub_proofHead(panel, 1, "Signal (history)", tsz)
float base = ub_pct(cH.get(0), cN.get(0))
int nB = cN.get(0)
panel.cell(0, 2, "Random bars", text_color = T_TEXT, bgcolor = T_ROW, text_size = tsz, text_halign = text.align_left, tooltip = "Seeded random bars, " + str.tostring(pRand * 100, "0.0") + "% of bars, 50/50 long or short, scored with the same rule. This is the line to beat.")
panel.cell(1, 2, str.tostring(nB), text_color = T_TEXT, bgcolor = T_ROW, text_size = tsz)
panel.cell(2, 2, na(base) ? "-" : str.tostring(base, "#") + "%", text_color = T_TEXT, bgcolor = T_ROW, text_size = tsz, text_formatting = text.format_bold)
panel.cell(3, 2, "baseline", text_color = T_MUTED, bgcolor = T_ROW, text_size = tsz)
panel.cell(4, 2, "-", text_color = T_MUTED, bgcolor = T_ROW, text_size = tsz)
ub_proofRow(panel, 3, "All reversals", UB_GREEN, cH.get(1), cN.get(1), base, nB, minN, tsz)
ub_proofRow(panel, 4, "With kernel slope", UB_SKY, cH.get(2), cN.get(2), base, nB, minN, tsz)
ub_proofRow(panel, 5, "Against kernel slope", UB_NEUTRAL, cH.get(3), cN.get(3), base, nB, minN, tsz)
ub_proofRow(panel, 6, "Kernel turns", UB_VIOLET, cH.get(4), cN.get(4), base, nB, minN, tsz)
ub_footer(panel, 5, 7, "Hit = 1 ATR(14) its way before 1 ATR against within " + str.tostring(hzBars) + " bars. Closed bars, loaded history only.")
ub_footer(panel, 5, 8, "Endpoint kernel (no repaint). Past results do not guarantee future results.")