Unbroke Oscillator Matrix

bryanhulinsky23 · study · 345 行 · 点赞 25 · TradingView 原页

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

Pine Script

// 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.
// oscillator matrix 1.0.3
//@version=6
indicator("Unbroke Oscillator Matrix", shorttitle = "UB Osc Mtx", overlay = false, max_lines_count = 100, max_labels_count = 100, max_bars_back = 500)
// One pane with momentum (RSI centered on 0), money flow (MFI centered on 0, needs volume) and regular
// divergences between price and momentum. Divergences are confirmed: they show when the momentum pivot is
// confirmed, N bars after it, at a bar close. Nothing repaints. Proof panel: divergences and momentum crosses
// vs seeded random bars. Python port: tools/oscillator_matrix_mirror.py. Original code.
 
//==============================================================================
// INPUTS
//==============================================================================
G_O = "Oscillators"
momLen = input.int(14, "Momentum (RSI) length", minval = 2, maxval = 100, group = G_O, display = display.none)
mfLen  = input.int(14, "Money flow (MFI) length", minval = 2, maxval = 100, group = G_O, tooltip = "MFI uses volume. On symbols with no volume the money flow line is empty and its rows read 'Not enough data'.", display = display.none)
mfSm   = input.int(3, "Money flow smoothing", minval = 1, maxval = 20, group = G_O, display = display.none)
obLvl  = input.float(20, "Zone line (+/-)", minval = 5, maxval = 45, group = G_O, display = display.none)
G_DV = "Divergences"
dvN    = input.int(5, "Pivot strength (bars each side)", minval = 1, maxval = 30, group = G_DV, tooltip = "A momentum pivot needs this many bars on each side; the divergence shows this many bars after the pivot.", display = display.none)
dvMax  = input.int(60, "Max bars between pivots", minval = 10, maxval = 300, group = G_DV, display = display.none)
showDv = input.bool(true, "Show divergence lines", group = G_DV, display = display.none)
keepN  = input.int(30, "Divergences kept", minval = 5, maxval = 90, group = G_DV, 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)
// Proof panel always draws on the main price chart (force_overlay needs a const bool), so it never covers the oscillator.
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 'OSM XP' columns to the Data Window and Export chart data, for tools/oscillator_matrix_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.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 = 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(45, 0, 100, ub_strength(rate, 0, 100), T_ROW) : 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)
int WARM = 300
bool ok = bar_index >= WARM and not na(A)
float mom = ta.rsi(close, momLen) - 50
float mfRaw = ta.mfi(hlc3, mfLen)
float mf = ta.ema(mfRaw - 50, mfSm)
bool hasMf = not na(mf)
color C_UP = UB_LIGHT ? #0FA86E : #2EF0A6
color C_DN = UB_LIGHT ? #E0352B : #FF5C52
 
// Regular divergence on momentum pivots (confirmed dvN bars after the pivot).
float mpl = ta.pivotlow(mom, dvN, dvN)
float mph = ta.pivothigh(mom, dvN, dvN)
var float lM = na
var float lP = na
var int   lB = na
var float hM = na
var float hP = na
var int   hB = na
int dv = 0
var array<line>  dLn = array.new<line>()
var array<label> dLb = array.new<label>()
if not na(mpl)
    float pLow = low[dvN]
    int b = bar_index - dvN
    if not na(lB) and b - lB <= dvMax and pLow < lP and mpl > lM
        dv := 1
        if showDv
            dLn.push(line.new(lB, lM, b, mpl, color = C_UP, width = 2))
            dLb.push(label.new(b, mpl, "Bull div", style = label.style_label_up, color = color.new(C_UP, 100), textcolor = C_UP, size = size.small))
    lM := mpl
    lP := pLow
    lB := b
if not na(mph)
    float pHigh = high[dvN]
    int b = bar_index - dvN
    if not na(hB) and b - hB <= dvMax and pHigh > hP and mph < hM
        dv := dv == 1 ? 0 : -1
        if showDv
            dLn.push(line.new(hB, hM, b, mph, color = C_DN, width = 2))
            dLb.push(label.new(b, mph, "Bear div", style = label.style_label_down, color = color.new(C_DN, 100), textcolor = C_DN, size = size.small))
    hM := mph
    hP := pHigh
    hB := b
while dLn.size() > keepN
    line.delete(dLn.shift())
while dLb.size() > keepN
    label.delete(dLb.shift())
int mx = mom > 0 and mom[1] <= 0 ? 1 : mom < 0 and mom[1] >= 0 ? -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 divergences, 2 divergence with money flow, 3 momentum cross 0, 4 momentum cross with money flow
int xRnd = 0
if ok and barstate.isconfirmed
    if dv != 0
        f_pend(dv, 1)
        if hasMf and math.sign(mf) == dv
            f_pend(dv, 2)
    if mx != 0
        f_pend(mx, 3)
        if hasMf and math.sign(mf) == mx
            f_pend(mx, 4)
    if f_hash(0.0) < pRand
        xRnd := f_hash(78.233) < 0.5 ? 1 : -1
        f_pend(xRnd, 0)
 
//==============================================================================
// DRAWING
//==============================================================================
hline(0, "Zero", color.new(UB_NEUTRAL, 50), hline.style_solid)
hline(obLvl, "Upper zone", color.new(UB_NEUTRAL, 70), hline.style_dotted)
hline(-obLvl, "Lower zone", color.new(UB_NEUTRAL, 70), hline.style_dotted)
plot(mf, "Money flow", color.new(mf >= 0 ? C_UP : C_DN, UB_LIGHT ? 55 : 60), style = plot.style_columns)
color mc = color.from_gradient(mom, -30, 30, C_DN, C_UP)
plot(mom, "Momentum glow", color.new(mc, UB_LIGHT ? 78 : 72), 6)
plot(mom, "Momentum", mc, 2)
plotshape(mx == 1 and barstate.isconfirmed, "Momentum up", shape.circle, location.bottom, C_UP, size = size.tiny)
plotshape(mx == -1 and barstate.isconfirmed, "Momentum down", shape.circle, location.top, C_DN, size = size.tiny)
 
alertcondition(dv == 1, "Bull divergence", "Unbroke Oscillator Matrix: bullish divergence confirmed")
alertcondition(dv == -1, "Bear divergence", "Unbroke Oscillator Matrix: bearish divergence confirmed")
alertcondition(mx == 1, "Momentum up", "Unbroke Oscillator Matrix: momentum crossed above 0")
alertcondition(mx == -1, "Momentum down", "Unbroke Oscillator Matrix: momentum crossed below 0")
 
plot(xpOn ? 100 : na, "OSM XP ver", display = display.data_window)
plot(xpOn ? mom : na, "OSM XP mom", display = display.data_window)
plot(xpOn ? mf : na, "OSM XP mf", display = display.data_window)
plot(xpOn ? dv : na, "OSM XP div", display = display.data_window)
plot(xpOn ? xRnd : na, "OSM XP rnd", display = display.data_window)
 
//==============================================================================
// PROOF PANEL + MATRIX ROW
//==============================================================================
var table panel = na
if barstate.islast and showPanel
    if na(panel)
        panel := table.new(ub_pos(panelPos), 5, 10, bgcolor = na, frame_color = T_FRAME, frame_width = 1, border_color = T_BORDER, border_width = 1, force_overlay = true)
    panel.clear(0, 0, 4, 9)
    tsz = ub_size(dashSize)
    ub_header(panel, 5, "Oscillator Matrix", 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, "Divergences", UB_GREEN, cH.get(1), cN.get(1), base, nB, minN, tsz)
    ub_proofRow(panel, 4, "Divergence + money flow", UB_SKY, cH.get(2), cN.get(2), base, nB, minN, tsz)
    ub_proofRow(panel, 5, "Momentum cross 0", UB_NEUTRAL, cH.get(3), cN.get(3), base, nB, minN, tsz)
    ub_proofRow(panel, 6, "Cross + money flow", UB_VIOLET, cH.get(4), cN.get(4), base, nB, minN, tsz)
    string nowTx = "Now: momentum " + (mom >= 0 ? "+" : "") + str.tostring(mom, "0.0") + " | money flow " + (hasMf ? (mf >= 0 ? "+" : "") + str.tostring(mf, "0.0") : "n/a (no volume)")
    ub_footer(panel, 5, 7, nowTx)
    ub_footer(panel, 5, 8, "Hit = 1 ATR(14) its way before 1 ATR against within " + str.tostring(hzBars) + " bars. Divergences show " + str.tostring(dvN) + " bars after the pivot.")
    ub_footer(panel, 5, 9, "Past results do not guarantee future results.")

← 返回列表