Relative Range Position

hasanaksoy199264 · study · 210 行 · 点赞 17 · TradingView 原页

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

Pine Script

//@version=6
// Relative Range Position
// Shows where price sits inside the rolling range (0% = bottom, 100% = top)
// for the chart symbol and BTC. LONG/SHORT = symbol crosses its range midpoint.
indicator("Relative Range Position", overlay=false, max_labels_count=100)
 
// ── INPUTS ──
btcSym    = input.symbol("BINANCE:BTCUSD", "BTC Symbol")
period    = input.string("4H", "HTF Period", options=["1H","2H","4H","D"])
rangeLen  = input.int(1000, "Range Window (bars)", minval=20, maxval=5000)
showPanel = input.bool(true,  "Info Panel")
showTags  = input.bool(true,  "Line-End Name Labels",
     tooltip="ONE label per series for its whole life: created on the last bar, then only its position is updated — no pile-up of overlapping labels")
showDist  = input.bool(false, "Raw Distance Lines (large scale)")
confirmB  = input.bool(true,  "Signal on Closed Bar Only (repaint protection)")
 
// ── APPEARANCE INPUTS (visual only) ──
showZones = input.bool(true, "Zone Shading (lower/upper)", group="Appearance")
showSigBg = input.bool(true, "Highlight Signal Bar",       group="Appearance")
zoneLo    = input.int(30, "Lower Zone Limit", minval=1,  maxval=49, group="Appearance")
zoneHi    = input.int(70, "Upper Zone Limit", minval=51, maxval=99, group="Appearance")
 
htfStr = period == "1H" ? "60" : period == "2H" ? "120" : period == "4H" ? "240" : period
 
int LBL_OFF = 3   // how many bars to the right of the last bar the labels are shifted
 
// ── LINE COLORS (plots and end labels are fed from a single source) ──
COL_T       = color.rgb(0, 229, 255)
COL_B       = color.rgb(255, 171, 64)
COL_DIV     = color.new(#b388ff, 20)
COL_DIV_UP  = color.new(color.teal, 40)
COL_DIV_DN  = color.new(color.maroon, 40)
COL_UP      = color.new(color.teal, 50)
COL_DN      = color.new(color.maroon, 50)
 
// ── CORE: position within the range ──
// up  = distance of the close from the window bottom (%)
// dn  = distance of the previous open from the window top (%)
// pos = up/(up+dn)×100 → 0% bottom · 50% middle · 100% top
// The qualifier of len is SIMPLE: in v6, if a type is given without a qualifier
// it defaults to series; the window length is a constant coming from an input,
// so it must not be a series.
f_range(float closeSrc, float prevOpen, simple int len) =>
    hi = ta.highest(closeSrc, len)
    lo = ta.lowest(prevOpen, len)
    up = lo > 0 ? (closeSrc - lo) / lo * 100 : na
    dn = hi > 0 ? (hi - prevOpen) / hi * 100 : na
    tot = na(up) or na(dn) ? na : up + dn
    pos = not na(tot) and tot > 0 ? up / tot * 100 : na
    [pos, up, dn]
 
// Converts a bar count to a readable duration (142 bars on a 5m chart → "11h 50m")
f_ago(int bars) =>
    float mins = bars * timeframe.in_seconds() / 60.0
    int d = int(mins / 1440)
    int h = int((mins - d * 1440) / 60)
    int m = int(mins - d * 1440 - h * 60)
    string res = str.tostring(m) + "m"
    if d > 0
        res := str.tostring(d) + "d " + str.tostring(h) + "h"
    else if h > 0
        res := str.tostring(h) + "h " + str.tostring(m) + "m"
    res
 
// ONE label per series: creates it if missing, otherwise only moves/updates it.
// Since label.new is not called on every bar, labels never accumulate (max_labels limit is not stressed either).
f_tag(label lb, float y, string txt, color col, bool on) =>
    label r = lb
    if not on or na(y)
        if not na(r)
            label.delete(r)
            r := na
    else if na(r)
        r := label.new(x = bar_index + LBL_OFF, y = y, text = txt,
             xloc = xloc.bar_index, yloc = yloc.price,
             color = color.new(color.black, 100), style = label.style_none,
             textcolor = col, size = size.tiny)
    else
        label.set_xy(r, bar_index + LBL_OFF, y)
        label.set_text(r, txt)
        label.set_textcolor(r, col)
    r
 
// Chart TF — symbol (our own bars; the signal is final at close anyway)
[posT, upT, dnT] = f_range(close, open[1], rangeLen)
 
// Chart TF — BTC (the live bar's close moves; produces no signal, panel only)
btcC  = request.security(btcSym, "", close,   lookahead=barmerge.lookahead_off)
btcPO = request.security(btcSym, "", open[1], lookahead=barmerge.lookahead_off)
[posB, upB, dnB] = f_range(btcC, btcPO, rangeLen)
 
// HTF — LAST CLOSED bar
tickHtfC  = request.security(syminfo.tickerid, htfStr, close[1],  lookahead=barmerge.lookahead_off)
tickHtfPO = request.security(syminfo.tickerid, htfStr, open[2],   lookahead=barmerge.lookahead_off)
btcHtfC   = request.security(btcSym,           htfStr, close[1],  lookahead=barmerge.lookahead_off)
btcHtfPO  = request.security(btcSym,           htfStr, open[2],   lookahead=barmerge.lookahead_off)
[posTh, upTh, dnTh] = f_range(tickHtfC, tickHtfPO, rangeLen)
[posBh, upBh, dnBh] = f_range(btcHtfC, btcHtfPO, rangeLen)
 
// Differences
diffTicker    = posT  - (100 - posT)          // symbol: position − mirror  (= 2·pos−100)
diffBtc       = posB  - (100 - posB)
diffTickerHtf = na(posTh) ? na : 2 * posTh - 100
diffBtcHtf    = na(posBh) ? na : 2 * posBh - 100
divergence    = na(posT) or na(posB) ? na : posT - posB   // symbol − BTC position difference
 
// ── SIGNAL: midpoint cross (closed bar only) ──
// In v6, and/or short-circuit: the stateful ta.crossover/ta.crossunder sit on the
// LEFT side, so they are evaluated on every bar — no bar is ever skipped.
barOk = not confirmB or barstate.isconfirmed
longSig  = ta.crossover(posT, 50)  and barOk
shortSig = ta.crossunder(posT, 50) and barOk
 
// ── LAST SIGNAL STATE (persistent) ──
// longSig/shortSig are true only on the cross bar; since the panel is drawn on the
// last bar, reading them directly would always show "no signal". Direction and
// bar index are stored instead.
var int lastSigDir = 0        // 1 = LONG · -1 = SHORT · 0 = none yet
var int lastSigBar = na
if longSig
    lastSigDir := 1
    lastSigBar := bar_index
if shortSig
    lastSigDir := -1
    lastSigBar := bar_index
 
// ═══════════════════════ DRAWING (appearance only) ═══════════════════════
 
// ── Horizontal lines + zone shading ──
h0   = hline(0,      "Bottom",      color=color.new(color.green, 70), linestyle=hline.style_dotted)
hLo  = hline(zoneLo, "Lower Zone",  color=color.new(color.gray, 100))
h50  = hline(50,     "Midpoint",    color=color.new(color.gray, 40),  linestyle=hline.style_dashed)
hHi  = hline(zoneHi, "Upper Zone",  color=color.new(color.gray, 100))
h100 = hline(100,    "Top",         color=color.new(color.red, 70),   linestyle=hline.style_dotted)
fill(h0,  hLo, color = showZones ? color.new(color.green, 90) : na, title="Lower Zone Fill")
fill(hHi, h100, color = showZones ? color.new(color.red, 90)  : na, title="Upper Zone Fill")
 
// ── Symbol line: color gradient by position (bottom green → top red) ──
posCol = color.from_gradient(posT, 0, 100, color.new(color.green, 0), color.new(color.red, 0))
plot(posT, "Symbol Position %", color=posCol, linewidth=2)
 
// ── BTC: thin stepped line ──
plot(posB, "BTC Position %", color=COL_B, linewidth=1, style=plot.style_stepline)
 
// ── Divergence: columns, colored by sign ──
plot(divergence, "Divergence (Symbol−BTC)", color = divergence >= 0 ? COL_DIV_UP : COL_DIV_DN, style=plot.style_columns)
 
// ── Raw distance lines (optional) ──
plot(showDist ? upT : na, "Symbol Distance From Bottom %", color=COL_UP)
plot(showDist ? dnT : na, "Symbol Distance From Top %",    color=COL_DN)
 
// ── Signal markers: labels on top of the line ──
plotshape(longSig  ? posT : na, title="LONG",  style=shape.labelup,   location=location.absolute, color=color.lime, textcolor=color.black, text="L", size=size.tiny)
plotshape(shortSig ? posT : na, title="SHORT", style=shape.labeldown, location=location.absolute, color=color.red,  textcolor=color.white, text="S", size=size.tiny)
 
// ── Highlight signal bar ──
bgcolor(showSigBg and longSig  ? color.new(color.lime, 85) : na, title="LONG Bar Highlight")
bgcolor(showSigBg and shortSig ? color.new(color.red,  85) : na, title="SHORT Bar Highlight")
 
// ── LINE-END NAME LABELS ──
var label tagT  = na
var label tagB  = na
var label tagA  = na
var label tagUp = na
var label tagDn = na
if barstate.islast
    tagT  := f_tag(tagT,  posT,       syminfo.ticker,    COL_T,   showTags)
    tagB  := f_tag(tagB,  posB,       "BTC",             COL_B,   showTags)
    tagA  := f_tag(tagA,  divergence, "Divergence",      COL_DIV, showTags)
    tagUp := f_tag(tagUp, upT,        "From bottom",     COL_UP,  showTags and showDist)
    tagDn := f_tag(tagDn, dnT,        "From top",        COL_DN,  showTags and showDist)
 
// ── PANEL (clean, semi-transparent, bottom right) ──
if showPanel and barstate.islast
    var table t = table.new(position.bottom_right, 3, 8, border_width=0, frame_width=0)
    bg  = color.new(color.black, 30)
    bgH = color.new(color.rgb(30, 30, 30), 20)
    table.cell(t, 0, 0, "POSITION",      text_color=color.white,  bgcolor=bgH, text_size=size.tiny)
    table.cell(t, 1, 0, "BTC",           text_color=color.orange, bgcolor=bgH, text_size=size.tiny)
    table.cell(t, 2, 0, syminfo.ticker,  text_color=color.aqua,   bgcolor=bgH, text_size=size.tiny)
    table.cell(t, 0, 1, "Range position %", text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 1, 1, str.tostring(posB, "#.#"), text_color=posB>50?color.lime:color.red, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 2, 1, str.tostring(posT, "#.#"), text_color=posT>50?color.lime:color.red, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 0, 2, "HTF position % (" + period + ")", text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 1, 2, str.tostring(posBh, "#.#"), text_color=color.new(color.orange,20), bgcolor=bg, text_size=size.tiny)
    table.cell(t, 2, 2, str.tostring(posTh, "#.#"), text_color=color.new(color.aqua,20), bgcolor=bg, text_size=size.tiny)
    table.cell(t, 0, 3, "Dist. from bottom %", text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 1, 3, str.tostring(upB, "#.#"), text_color=color.lime, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 2, 3, str.tostring(upT, "#.#"), text_color=color.lime, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 0, 4, "Dist. from top %", text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 1, 4, str.tostring(dnB, "#.#"), text_color=color.red, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 2, 4, str.tostring(dnT, "#.#"), text_color=color.red, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 0, 5, "Diff (2·pos−100)", text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 1, 5, str.tostring(diffBtc, "#.#"), text_color=diffBtc>0?color.lime:color.red, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 2, 5, str.tostring(diffTicker, "#.#"), text_color=diffTicker>0?color.lime:color.red, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 0, 6, "Divergence", text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 1, 6, str.tostring(divergence, "#.#"), text_color=divergence>0?color.lime:color.red, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 2, 6, "Coin & BTC Divergence", text_color=color.new(color.white, 25), bgcolor=bg, text_size=size.tiny)
 
    // Last signal: direction + how many bars ago (read from persistent state)
    int    sigAge = na(lastSigBar) ? na : bar_index - lastSigBar
    string sigTxt = lastSigDir == 1 ? "▲ LONG" : lastSigDir == -1 ? "▼ SHORT" : "— none"
    string ageTxt = na(sigAge) ? "—" : str.tostring(sigAge) + " bars ago (" + f_ago(sigAge) + ")"
    color  sigCol = lastSigDir == 1 ? color.lime : lastSigDir == -1 ? color.red : color.gray
    table.cell(t, 0, 7, "Last signal", text_color=color.white, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 1, 7, sigTxt, text_color=sigCol, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 2, 7, ageTxt, text_color=color.new(color.white, 25), bgcolor=bg, text_size=size.tiny)
 
alertcondition(longSig,  "Range Midpoint Cross ↑", "{{ticker}} crossed ABOVE the midpoint of its 1000-bar range")
alertcondition(shortSig, "Range Midpoint Cross ↓", "{{ticker}} crossed BELOW the midpoint of its 1000-bar range")

← 返回列表