Nambou SMT Odds: Do SMT Divergences Really Reverse?

Nambou_Signals · study · 328 行 · 点赞 50 · 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/
// © Nambou_Signals
//@version=6
indicator("Nambou SMT Odds", "SMT Odds", overlay = true, max_labels_count = 500, max_lines_count = 500, max_polylines_count = 2, max_bars_back = 1000)
 
gP = "Pair"
pairIn  = input.string("Auto", "Compare with", options = ["Auto", "Custom"], group = gP, tooltip = "Auto pairs NQ with ES, MNQ with MES, YM and RTY with ES, EURUSD with GBPUSD, BTC with ETH, XAUUSD with XAGUSD and SPY with QQQ (and back). Pick Custom to choose any symbol.")
custom  = input.symbol("CME_MINI:ES1!", "Custom symbol", group = gP)
 
gS = "Swings"
pivLen   = input.int(3, "Swing length", minval = 2, maxval = 20, group = gS, tooltip = "A swing high is the highest high of this many bars on each side. It is confirmed that many bars later.")
revAtr   = input.float(1.0, "A reversal is a move of this many ATR", minval = 0.2, maxval = 5.0, step = 0.1, group = gS, tooltip = "Measured from the close of the bar that confirms the swing, before any bar trades beyond the swing's extreme.")
waitBars = input.int(20, "Bars a reversal has to happen in", minval = 2, maxval = 200, group = gS)
 
gD = "Display"
maxDrawn   = input.int(40, "SMT divergences drawn", minval = 1, maxval = 120, group = gD, tooltip = "The newest ones are drawn. Older ones are still counted in the table.")
showPlain  = input.bool(true, "Mark ordinary swings too", group = gD, tooltip = "Small dots on the swings where both markets agreed, the comparison group in the table.")
showGhost  = input.bool(true, "Draw the other market over the chart", group = gD, tooltip = "The paired market's closes as a faint line, rescaled to the visible part of your chart, so you can see the two split at each divergence. It is redrawn when you scroll or zoom.")
cGhost     = input.color(#B39DDB, "Other market line", group = gD)
showTable  = input.bool(true, "Show the odds table", group = gD)
tablePosIn = input.string("Auto", "Table position", options = ["Auto", "Top center", "Bottom center", "Top right", "Bottom right", "Bottom left", "Top left"], group = gD, tooltip = "Auto looks at the left, middle and right of the visible chart and puts the table where the candles leave the most room. It never picks the bottom left, where TradingView puts its logo.")
txtSizeIn  = input.string("Normal", "Chart text size", options = ["Tiny", "Small", "Normal", "Large"], group = gD)
tblSizeIn  = input.string("Normal", "Table text size", options = ["Tiny", "Small", "Normal", "Large"], group = gD)
cBear  = input.color(#FF3D71, "Bearish SMT", group = gD)
cBull  = input.color(#00E5A0, "Bullish SMT", group = gD)
cMiss  = input.color(#787B86, "Did not reverse", group = gD)
cTxt   = input.color(#D1D4DC, "Neutral text", group = gD)
 
gA = "Alerts"
aSmt = input.bool(true, "Alert when an SMT divergence is confirmed", group = gA)
aRev = input.bool(true, "Alert when it reverses", group = gA)
 
txtSize = txtSizeIn == "Tiny" ? size.tiny : txtSizeIn == "Small" ? size.small : txtSizeIn == "Large" ? size.large : size.normal
outSize = txtSizeIn == "Large" ? size.normal : txtSizeIn == "Normal" ? size.small : size.tiny
tblSize = tblSizeIn == "Tiny" ? size.tiny : tblSizeIn == "Small" ? size.small : tblSizeIn == "Large" ? size.large : size.normal
 
autoPair() =>
    string root = syminfo.root
    string tk = syminfo.ticker
    string px = syminfo.prefix
    string out = ""
    if root == "NQ"
        out := "CME_MINI:ES1!"
    else if root == "ES"
        out := "CME_MINI:NQ1!"
    else if root == "MNQ"
        out := "CME_MINI:MES1!"
    else if root == "MES"
        out := "CME_MINI:MNQ1!"
    else if root == "YM" or root == "MYM" or root == "RTY" or root == "M2K"
        out := "CME_MINI:ES1!"
    else if tk == "EURUSD"
        out := px + ":GBPUSD"
    else if tk == "GBPUSD"
        out := px + ":EURUSD"
    else if tk == "XAUUSD"
        out := px + ":XAGUSD"
    else if tk == "XAGUSD"
        out := px + ":XAUUSD"
    else if tk == "SPY"
        out := "NASDAQ:QQQ"
    else if tk == "QQQ"
        out := "AMEX:SPY"
    else if str.startswith(tk, "BTC")
        out := px + ":" + str.replace(tk, "BTC", "ETH")
    else if str.startswith(tk, "ETH")
        out := px + ":" + str.replace(tk, "ETH", "BTC")
    out
 
string other = pairIn == "Custom" ? custom : autoPair()
bool hasPair = other != ""
[bHigh, bLow, bClose] = request.security(hasPair ? other : syminfo.tickerid, timeframe.period, [high, low, close], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
string otherName = hasPair ? str.substring(other, str.pos(other, ":") + 1) : ""
 
type Trial
    int   side
    float extreme
    float ref
    float atr
    int   start
    int   kind      // 0 SMT, 1 ordinary swing, 2 any bar
    label lb
    line  ln
    line  lv
 
var trials = array.new<Trial>()
// SMT highs: n, reversed; SMT lows; ordinary highs; ordinary lows; any bar
var tally = array.new_int(10, 0)
var drawnL = array.new_label()
var drawnN = array.new_line()
var drawnO = array.new_label()
var polyline ghost = na
var label ghostTag = na
 
// Hides the text of a label that would sit on top of a newer one (its line stays).
declutter(array<label> labs, array<float> keptX, array<float> keptY, float gap, int bars) =>
    if labs.size() > 0
        for i = labs.size() - 1 to 0
            label lb = labs.get(i)
            float x = label.get_x(lb)
            float y = label.get_y(lb)
            bool clash = false
            if keptX.size() > 0
                for j = 0 to keptX.size() - 1
                    if math.abs(x - keptX.get(j)) <= bars and math.abs(y - keptY.get(j)) < gap
                        clash := true
            if clash
                label.set_text(lb, "")
            else
                keptX.push(x)
                keptY.push(y)
 
float atrNow = ta.atr(14)
 
addTrial(int side, float extreme, int kind, label lb, line ln, line lv) =>
    trials.push(Trial.new(side, extreme, close, atrNow, bar_index, kind, lb, ln, lv))
 
slot(Trial t) => t.kind == 2 ? 8 : t.kind == 0 ? (t.side > 0 ? 0 : 2) : (t.side > 0 ? 4 : 6)
 
// resolve open trials on this bar
if trials.size() > 0
    for i = trials.size() - 1 to 0
        Trial t = trials.get(i)
        if bar_index > t.start
            bool broke = t.side > 0 ? high > t.extreme : low < t.extreme
            bool moved = t.side > 0 ? t.ref - low >= revAtr * t.atr : high - t.ref >= revAtr * t.atr
            bool timeUp = bar_index - t.start >= waitBars
            if broke or moved or timeUp
                bool ok = moved and not broke
                int k = slot(t)
                tally.set(k, tally.get(k) + 1)
                tally.set(k + 1, tally.get(k + 1) + (ok ? 1 : 0))
                if not na(t.lb)
                    color c = ok ? (t.side > 0 ? cBear : cBull) : cMiss
                    label.set_textcolor(t.lb, c)
                    label.set_text(t.lb, str.replace(label.get_text(t.lb), "SMT ▼", "SMT ▼ " + (ok ? "✓" : "✗")))
                    label.set_text(t.lb, str.replace(label.get_text(t.lb), "SMT ▲", "SMT ▲ " + (ok ? "✓" : "✗")))
                    line.set_color(t.ln, color.new(c, 20))
                    line.set_x2(t.lv, bar_index)
                    line.set_color(t.lv, color.new(c, 30))
                    drawnO.push(label.new(bar_index, t.side > 0 ? low : high, ok ? "✓ " + str.tostring(revAtr) + " ATR" : (broke ? "✗ broke" : "✗ no move"), style = t.side > 0 ? label.style_label_up : label.style_label_down, color = color(na), textcolor = color.new(c, 10), size = outSize))
                    if drawnO.size() > maxDrawn
                        label.delete(drawnO.shift())
                    if ok and aRev and barstate.isconfirmed
                        alert("SMT Odds: " + syminfo.ticker + (t.side > 0 ? " bearish" : " bullish") + " SMT reversed " + str.tostring(revAtr) + " ATR", alert.freq_once_per_bar_close)
                trials.remove(i)
 
// swings confirmed on this bar
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
float bWinHi = ta.highest(bHigh, 2 * pivLen + 1)
float bWinLo = ta.lowest(bLow, 2 * pivLen + 1)
 
var float prevPH = na
var float prevBH = na
var int   prevPHx = na
var float prevPL = na
var float prevBL = na
var int   prevPLx = na
 
swing(int side, float val, float bval, float pval, float pbval, int px) =>
    // returns nothing; draws and opens the trial
    bool newExt = side > 0 ? val > pval : val < pval
    if newExt and not na(atrNow) and not na(bval) and not na(pbval)
        bool agreed = side > 0 ? bval > pbval : bval < pbval
        int x = bar_index - pivLen
        if agreed
            label lb = showPlain ? label.new(x, val, "•", style = side > 0 ? label.style_label_down : label.style_label_up, color = color(na), textcolor = color.new(cTxt, 25), size = size.normal, tooltip = "Ordinary swing: " + otherName + " agreed") : na
            addTrial(side, val, 1, label(na), line(na), line(na))
        else
            color c = side > 0 ? cBear : cBull
            line ln = line.new(px, pval, x, val, color = color.new(c, 30), width = 2)
            line lv = line.new(x, val, bar_index + waitBars, val, color = color.new(c, 50), style = line.style_dotted, width = 1)
            string t = side > 0 ? "SMT ▼\n" + otherName + " lower high" : otherName + " higher low\nSMT ▲"
            string tip = syminfo.ticker + (side > 0 ? " made a higher high and " : " made a lower low and ") + otherName + " did not"
            label lb = label.new(x, val, t, style = side > 0 ? label.style_label_down : label.style_label_up, color = color(na), textcolor = color.new(c, 10), size = txtSize, tooltip = tip)
            addTrial(side, val, 0, lb, ln, lv)
            drawnL.push(lb)
            drawnN.push(ln)
            drawnN.push(lv)
            if drawnL.size() > maxDrawn
                label.delete(drawnL.shift())
                line.delete(drawnN.shift())
                line.delete(drawnN.shift())
            if aSmt and barstate.isconfirmed
                alert("SMT Odds: " + syminfo.ticker + (side > 0 ? " bearish SMT, higher high not confirmed by " : " bullish SMT, lower low not confirmed by ") + otherName, alert.freq_once_per_bar_close)
 
if hasPair and not na(ph)
    if not na(prevPH)
        swing(1, ph, bWinHi, prevPH, prevBH, prevPHx)
    prevPH  := ph
    prevBH  := bWinHi
    prevPHx := bar_index - pivLen
 
if hasPair and not na(pl)
    if not na(prevPL)
        swing(-1, pl, bWinLo, prevPL, prevBL, prevPLx)
    prevPL  := pl
    prevBL  := bWinLo
    prevPLx := bar_index - pivLen
 
// the any-bar baseline: the same test started every third bar from the recent extreme
float recentHi = ta.highest(high, pivLen + 1)
float recentLo = ta.lowest(low, pivLen + 1)
if hasPair and bar_index % 3 == 0 and not na(atrNow) and trials.size() < 400
    addTrial(1, recentHi, 2, label(na), line(na), line(na))
    addTrial(-1, recentLo, 2, label(na), line(na), line(na))
 
meter(float pct) =>
    int n = int(math.round(math.max(0.0, math.min(100.0, pct)) / 10.0))
    string s = ""
    for k = 1 to 10
        s += k <= n ? "▰" : "▱"
    s
 
tPos = switch tablePosIn
    "Top center"    => position.top_center
    "Bottom center" => position.bottom_center
    "Top right"     => position.top_right
    "Bottom right"  => position.bottom_right
    "Bottom left"   => position.bottom_left
    "Top left"      => position.top_left
    => position.top_center
 
tblBg = color.new(#131722, 8)
 
var table odds = table.new(tPos, 3, 12, border_width = 0, frame_width = 0)
 
tcell(int c, int r, string v, color tc) =>
    table.cell(odds, c, r, v, text_color = tc, text_halign = text.align_left, text_size = tblSize, bgcolor = tblBg)
 
rateText(int k) =>
    int n = tally.get(k)
    n < 5 ? "too few yet (" + str.tostring(n) + ")" : str.tostring(math.round(tally.get(k + 1) * 100.0 / n)) + "%  (" + str.tostring(tally.get(k + 1)) + " of " + str.tostring(n) + ")"
 
rateOf(int k) => tally.get(k) < 5 ? na : tally.get(k + 1) * 100.0 / tally.get(k)
 
row(int r, string name, int k, color c) =>
    tcell(0, r, name, c)
    float p = rateOf(k)
    tcell(1, r, na(p) ? meter(0) : meter(p), na(p) ? color.new(c, 60) : c)
    tcell(2, r, rateText(k), #FFFFFF)
 
note(int r, string v, color tc) =>
    table.cell(odds, 0, r, v, text_color = tc, text_halign = text.align_left, text_size = size.small, bgcolor = tblBg)
    table.merge_cells(odds, 0, r, 2, r)
 
edgeText(int smt, int plain) =>
    float a = rateOf(smt)
    float b = rateOf(plain)
    na(a) or na(b) ? "—" : (a - b >= 0 ? "+" : "") + str.tostring(math.round(a - b)) + " pts"
 
if barstate.islast
    float vHi = high
    float vLo = low
    int vj = 0
    while vj < 999 and time[vj] >= chart.left_visible_bar_time
        vHi := math.max(vHi, high[vj])
        vLo := math.min(vLo, low[vj])
        vj += 1
    polyline.delete(ghost)
    label.delete(ghostTag)
    if showGhost and hasPair and vj > 2
        float gHi = na
        float gLo = na
        for j = 0 to vj - 1
            gHi := na(bClose[j]) ? gHi : math.max(nz(gHi, bClose[j]), bClose[j])
            gLo := na(bClose[j]) ? gLo : math.min(nz(gLo, bClose[j]), bClose[j])
        if not na(gHi) and gHi > gLo
            pts = array.new<chart.point>()
            for j = vj - 1 to 0
                if not na(bClose[j])
                    pts.push(chart.point.from_index(bar_index - j, vLo + (bClose[j] - gLo) / (gHi - gLo) * (vHi - vLo)))
            ghost := polyline.new(pts, line_color = color.new(cGhost, 45), line_width = 2)
            float lastY = vLo + (bClose - gLo) / (gHi - gLo) * (vHi - vLo)
            ghostTag := label.new(bar_index + 2, lastY, otherName + " (scaled)", style = label.style_label_left, color = color(na), textcolor = color.new(cGhost, 15), size = outSize)
    float gapY = math.max(vHi - vLo, syminfo.mintick) * (txtSizeIn == "Large" ? 0.07 : txtSizeIn == "Normal" ? 0.055 : 0.04)
    keptX = array.new_float()
    keptY = array.new_float()
    declutter(drawnL, keptX, keptY, gapY, 12)
    declutter(drawnO, keptX, keptY, gapY * 0.6, 8)
    table.clear(odds, 0, 0, 2, 11)
    bool atTop = tablePosIn == "Top center" or tablePosIn == "Top left"
    if tablePosIn == "Auto"
        float span = math.max(vHi - vLo, syminfo.mintick)
        float best = -1.0
        string spot = position.top_center
        for part = 0 to 2
            int a = int(vj * part / 3.0)
            int b = math.max(a, math.min(999, int(vj * (part + 1) / 3.0) - 1))
            float sHi = high[a]
            float sLo = low[a]
            for j = a to b
                sHi := math.max(sHi, high[j])
                sLo := math.min(sLo, low[j])
            float bonus = part == 1 ? 0.03 : 0.0
            float upRoom = (vHi - sHi) / span + bonus
            float dnRoom = (sLo - vLo) / span + bonus
            if upRoom > best
                best := upRoom
                spot := part == 0 ? position.top_right : part == 1 ? position.top_center : position.top_left
            if dnRoom > best and part < 2
                best := dnRoom
                spot := part == 0 ? position.bottom_right : part == 1 ? position.bottom_center : position.bottom_left
        atTop := spot == position.top_center or spot == position.top_left
        table.set_position(odds, spot)
 
    if showTable
        int off = atTop ? 2 : 0
        if off > 0
            for k = 0 to off - 1
                table.cell(odds, 0, k, " ", text_size = tblSize)
                table.merge_cells(odds, 0, k, 2, k)
        table.cell(odds, 0, off, "◆  NAMBOU SMT ODDS  ·  " + syminfo.ticker + " vs " + (hasPair ? otherName : "?"), text_color = #FFFFFF, text_halign = text.align_left, text_size = tblSize, bgcolor = tblBg)
        table.merge_cells(odds, 0, off, 2, off)
        if not hasPair
            note(off + 1, "No automatic pair for this symbol: choose Custom and a symbol to compare with", cTxt)
        else
            tcell(0, off + 1, "Reversed " + str.tostring(revAtr) + " ATR", color.new(cTxt, 40))
            tcell(1, off + 1, "", cTxt)
            tcell(2, off + 1, "", cTxt)
            row(off + 2, "SMT highs ▼", 0, cBear)
            row(off + 3, "SMT lows ▲", 2, cBull)
            row(off + 4, "Ordinary swing highs", 4, color.new(cTxt, 15))
            row(off + 5, "Ordinary swing lows", 6, color.new(cTxt, 15))
            row(off + 6, "Any bar", 8, color.new(cTxt, 35))
            note(off + 7, "SMT edge over ordinary swings:  highs " + edgeText(0, 4) + "  ·  lows " + edgeText(2, 6), #FFFFFF)
            note(off + 8, "reversed = moved " + str.tostring(revAtr) + " ATR away before trading beyond the swing, within " + str.tostring(waitBars) + " bars", color.new(cTxt, 35))

← 返回列表