Kernel Flow [OrbitOne]

orbitonetv · study · 158 行 · 点赞 304 · 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/
// © orbitonetv
//@version=6
indicator("Kernel Flow [OrbitOne]", "Kernel Flow [OrbitOne]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_bars_back = 500)
 
// ════════ KERNEL ════════
gK     = "Kernel"
src    = input.source(close, "Source", group = gK)
kType  = input.string("Gaussian", "Kernel", options = ["Gaussian", "Rational Quadratic", "Epanechnikov"], group = gK, tooltip = "Gaussian: classic Nadaraya-Watson smoothing.\nRational Quadratic: keeps more of the long-term shape (alpha controls the mix).\nEpanechnikov: uses only the last 3 x bandwidth bars, reacts faster.")
bw     = input.float(8.0, "Bandwidth", minval = 0.5, step = 0.5, group = gK, tooltip = "Higher = smoother and slower line. Lower = faster line, more turns.")
alpha  = input.float(1.0, "Rational Quadratic alpha", minval = 0.1, step = 0.1, group = gK)
win    = input.int(100, "Window (bars)", minval = 10, maxval = 499, group = gK, tooltip = "How many past bars the estimate uses.")
 
// ════════ SIGNALS ════════
gS      = "Signals"
confirm = input.bool(true, "Wait for bar close", group = gS, tooltip = "When enabled, turn signals appear only on closed bars and never repaint. While a bar is still open the line color can still flip back.")
sigSty  = input.string("Arrows", "Signal style", options = ["Arrows", "Labels", "None"], group = gS)
useHtf  = input.bool(false, "Only signal when timeframe 1 agrees", group = gS, tooltip = "Filters out turns that go against the trend of 'Timeframe 1' in the dashboard settings.")
 
// ════════ ENVELOPE ════════
gE      = "Envelope"
showEnv = input.bool(false, "Show envelope bands", group = gE)
mult    = input.float(3.0, "Band multiplier", minval = 0.1, step = 0.1, group = gE, tooltip = "Bands = kernel line +/- mean absolute error of price around the line x multiplier.")
showTch = input.bool(true, "Mark band rejections", group = gE, tooltip = "A small circle when price closes back inside a band after leaving it.")
 
// ════════ REPAINTING PREVIEW ════════
gR     = "Repainting preview"
showRp = input.bool(false, "Show repainting preview curve", group = gR, tooltip = "Draws the classic two-sided kernel curve over recent bars. It is smoother but REDRAWS as new bars arrive, so it is for visual study only. Signals and alerts never use it.")
rpN    = input.int(150, "Preview length (bars)", minval = 20, maxval = 400, group = gR)
 
// ════════ DASHBOARD ════════
gD      = "Dashboard"
showDb  = input.bool(true, "Show trend dashboard", group = gD)
tf1     = input.timeframe("60", "Timeframe 1", group = gD)
tf2     = input.timeframe("240", "Timeframe 2", group = gD)
tf3     = input.timeframe("D", "Timeframe 3", group = gD)
dbPos   = input.string("Bottom right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gD)
 
// ════════ STYLE ════════
gG      = "Style"
upCol   = input.color(#089981, "Bullish color", group = gG)
dnCol   = input.color(#F23645, "Bearish color", group = gG)
lnW     = input.int(2, "Line width", minval = 1, maxval = 5, group = gG)
glow    = input.bool(true, "Glow effect", group = gG)
barCol  = input.bool(false, "Color bars by kernel direction", group = gG)
 
// ════════ CALCULATION ════════
f_w(float d) =>
    kType == "Gaussian" ? math.exp(-(d * d) / (2.0 * bw * bw)) : kType == "Rational Quadratic" ? math.pow(1.0 + (d * d) / (2.0 * alpha * bw * bw), -alpha) : (d < 3.0 * bw ? 1.0 - math.pow(d / (3.0 * bw), 2) : 0.0)
 
// endpoint estimate: uses only the current and past bars, so it never repaints
f_nw(float s) =>
    float num = 0.0
    float den = 0.0
    for i = 0 to win - 1
        v = s[i]
        if not na(v)
            w = f_w(i)
            num += v * w
            den += w
    den > 0 ? num / den : s
 
f_dir() =>
    v = f_nw(src)
    v > v[1] ? 1 : -1
 
nw = f_nw(src)
var int dir = 0
dir := nw > nw[1] ? 1 : nw < nw[1] ? -1 : dir
 
okBar  = not confirm or barstate.isconfirmed
d1     = request.security(syminfo.tickerid, tf1, f_dir())
d2     = request.security(syminfo.tickerid, tf2, f_dir())
d3     = request.security(syminfo.tickerid, tf3, f_dir())
htfOkL = not useHtf or d1 == 1
htfOkS = not useHtf or d1 == -1
 
turnUp = dir == 1 and dir[1] == -1
turnDn = dir == -1 and dir[1] == 1
bullSig = turnUp and okBar and htfOkL
bearSig = turnDn and okBar and htfOkS
 
// envelope
mae    = ta.sma(math.abs(src - nw), win) * mult
upper  = nw + mae
lower  = nw - mae
xDn    = ta.crossunder(close, upper)
xUp    = ta.crossover(close, lower)
rejTop = showEnv and xDn and okBar
rejBot = showEnv and xUp and okBar
 
// ════════ PLOTS ════════
lCol = dir == 1 ? upCol : dir == -1 ? dnCol : color.gray
plot(glow ? nw : na, "Glow", color = color.new(lCol, 82), linewidth = lnW + 5, display = display.pane)
plot(nw, "Kernel line", color = lCol, linewidth = lnW)
pU = plot(showEnv ? upper : na, "Upper band", color = color.new(dnCol, 30), linewidth = 1, display = display.all - display.status_line)
pL = plot(showEnv ? lower : na, "Lower band", color = color.new(upCol, 30), linewidth = 1, display = display.all - display.status_line)
pM = plot(showEnv ? nw : na, "Mid (hidden)", display = display.none)
fill(pU, pM, color = showEnv ? color.new(dnCol, 94) : na, title = "Upper zone")
fill(pL, pM, color = showEnv ? color.new(upCol, 94) : na, title = "Lower zone")
 
plotshape(sigSty == "Arrows" and bullSig, "Bullish turn (arrow)", shape.triangleup, location.belowbar, upCol, size = size.tiny, display = display.all - display.status_line)
plotshape(sigSty == "Arrows" and bearSig, "Bearish turn (arrow)", shape.triangledown, location.abovebar, dnCol, size = size.tiny, display = display.all - display.status_line)
plotshape(sigSty == "Labels" and bullSig, "Bullish turn (label)", shape.labelup, location.belowbar, upCol, text = "LONG", textcolor = color.white, size = size.small, display = display.all - display.status_line)
plotshape(sigSty == "Labels" and bearSig, "Bearish turn (label)", shape.labeldown, location.abovebar, dnCol, text = "SHORT", textcolor = color.white, size = size.small, display = display.all - display.status_line)
plotshape(rejTop and showTch, "Upper band rejection", shape.circle, location.abovebar, color.new(dnCol, 20), size = size.tiny, display = display.all - display.status_line)
plotshape(rejBot and showTch, "Lower band rejection", shape.circle, location.belowbar, color.new(upCol, 20), size = size.tiny, display = display.all - display.status_line)
 
barcolor(barCol ? lCol : na)
 
// ════════ REPAINTING PREVIEW (display only) ════════
var array<line> rpL = array.new<line>()
if showRp and barstate.islast
    while array.size(rpL) > 0
        line.delete(array.shift(rpL))
    float prevY = na
    for i = 0 to rpN - 1
        float num = 0.0
        float den = 0.0
        for j = 0 to rpN - 1
            v = src[j]
            if not na(v)
                w = f_w(math.abs(i - j))
                num += v * w
                den += w
        y = den > 0 ? num / den : na
        if i > 0 and not na(prevY) and not na(y)
            c = prevY >= y ? upCol : dnCol
            array.push(rpL, line.new(bar_index - i, y, bar_index - i + 1, prevY, color = color.new(c, 30), width = lnW, style = line.style_dotted))
        prevY := y
 
// ════════ DASHBOARD ════════
var table db = table.new(dbPos == "Top right" ? position.top_right : dbPos == "Bottom right" ? position.bottom_right : dbPos == "Top left" ? position.top_left : position.bottom_left, 2, 5, border_width = 1)
 
f_tf(string tf) =>
    tf == "D" or tf == "1D" ? "1D" : tf == "W" or tf == "1W" ? "1W" : tf == "M" or tf == "1M" ? "1M" : str.endswith(tf, "S") ? tf : timeframe.in_seconds(tf) >= 3600 ? str.tostring(timeframe.in_seconds(tf) / 3600) + "H" : tf + "m"
 
f_cell(int row, string name, int d) =>
    table.cell(db, 0, row, name, bgcolor = color.new(color.gray, 35), text_color = color.white, text_size = size.tiny)
    table.cell(db, 1, row, d == 1 ? "▲ UP" : d == -1 ? "▼ DOWN" : "—", bgcolor = d == 1 ? upCol : d == -1 ? dnCol : color.gray, text_color = color.white, text_size = size.tiny)
 
if showDb and barstate.isfirst
    table.merge_cells(db, 0, 0, 1, 0)
 
if showDb and barstate.islast
    table.cell(db, 0, 0, "Kernel Flow", bgcolor = color.new(color.black, 30), text_color = color.white, text_size = size.tiny)
    f_cell(1, "Chart", dir)
    f_cell(2, f_tf(tf1), d1)
    f_cell(3, f_tf(tf2), d2)
    f_cell(4, f_tf(tf3), d3)
 
// ════════ ALERTS ════════
alertcondition(bullSig, "Bullish turn", "Kernel Flow bullish turn | {{ticker}} | {{interval}} | {{close}}")
alertcondition(bearSig, "Bearish turn", "Kernel Flow bearish turn | {{ticker}} | {{interval}} | {{close}}")
alertcondition(rejTop, "Upper band rejection", "Kernel Flow upper band rejection | {{ticker}} | {{interval}} | {{close}}")
alertcondition(rejBot, "Lower band rejection", "Kernel Flow lower band rejection | {{ticker}} | {{interval}} | {{close}}")
alertcondition(dir == 1 and d1 == 1 and d2 == 1 and d3 == 1 and okBar and not (dir[1] == 1 and d1[1] == 1 and d2[1] == 1 and d3[1] == 1), "All timeframes bullish", "Kernel Flow: all timeframes bullish | {{ticker}} | {{close}}")
alertcondition(dir == -1 and d1 == -1 and d2 == -1 and d3 == -1 and okBar and not (dir[1] == -1 and d1[1] == -1 and d2[1] == -1 and d3[1] == -1), "All timeframes bearish", "Kernel Flow: all timeframes bearish | {{ticker}} | {{close}}")

← 返回列表