Range Compression Detector

Consultya · study · 133 行 · 点赞 29 · TradingView 原页

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

Pine Script

//@version=6
indicator("Range Compression Detector", overlay=true, max_boxes_count=200, max_labels_count=100)
 
// ── INPUTS ────────────────────────────────────────────────
i_fast    = input.int(20, "Fast EMA", group="Moving averages")
i_slow    = input.int(50, "Slow EMA", group="Moving averages")
 
i_compTh  = input.float(0.10, "Compression threshold %", step=0.01, group="Classification", tooltip="Separation below this percentage is treated as a range. Tune it per instrument.")
i_trendTh = input.float(0.25, "Trend threshold %", step=0.01, group="Classification", tooltip="Separation above this percentage is treated as a trend. The gap between the two thresholds is the transition zone.")
i_minBars = input.int(8, "Min bars to draw a range", minval=1, group="Classification", tooltip="A range must last at least this many bars before its box is drawn.")
i_confirm = input.int(3, "Confirmation bars", minval=1, group="Classification", tooltip="How many consecutive bars a state must hold before it is accepted.")
 
i_shade   = input.bool(true, "Shade range periods", group="Display")
i_showBox = input.bool(true, "Draw range boundaries", group="Display")
i_showPnl = input.bool(true, "Show status panel", group="Display")
i_showLbl = input.bool(true, "Label state changes", group="Display")
i_txtSize = input.string("Large", "Panel text size", options=["Small", "Normal", "Large", "Huge"], group="Display", tooltip="Enlarge the status panel for high-resolution screens or screenshots.")
 
c_range   = input.color(color.new(#F0C040, 88), "Range shading", group="Colours")
c_trendUp = input.color(color.new(#6DC230, 90), "Uptrend shading", group="Colours")
c_trendDn = input.color(color.new(#FF6464, 90), "Downtrend shading", group="Colours")
 
// ── CORE MEASUREMENT ──────────────────────────────────────
emaF = ta.ema(close, i_fast)
emaS = ta.ema(close, i_slow)
sep  = math.abs(emaF - emaS) / close * 100.0
 
plot(emaF, "Fast EMA", color=color.new(color.yellow, 30), linewidth=1)
plot(emaS, "Slow EMA", color=color.new(#1E90FF, 30), linewidth=1)
 
// ── STATE CLASSIFICATION ──────────────────────────────────
rawState = sep <= i_compTh ? 0 : sep >= i_trendTh ? 1 : 2
 
var int state     = 2
var int holdCount = 0
var int pendState = 2
 
if rawState == pendState
    holdCount += 1
else
    pendState := rawState
    holdCount := 1
 
stateChanged = false
if holdCount >= i_confirm and state != pendState
    state := pendState
    stateChanged := true
 
isRange = state == 0
isTrend = state == 1
isTrans = state == 2
trendUp = isTrend and emaF > emaS
trendDn = isTrend and emaF < emaS
 
// ── BACKGROUND SHADING ────────────────────────────────────
bgCol = not i_shade ? na : isRange ? c_range : trendUp ? c_trendUp : trendDn ? c_trendDn : na
bgcolor(bgCol, title="State shading")
 
// ── RANGE BOUNDARIES ──────────────────────────────────────
var float rngHi    = na
var float rngLo    = na
var int   rngStart = na
var box   rngBox   = na
var int   rngBars  = 0
 
if barstate.isconfirmed
    if isRange
        if na(rngStart)
            rngStart := bar_index
            rngHi := high
            rngLo := low
            rngBars := 1
        else
            rngHi := math.max(rngHi, high)
            rngLo := math.min(rngLo, low)
            rngBars += 1
            if i_showBox and na(rngBox) and rngBars >= i_minBars
                rngBox := box.new(rngStart, rngHi, bar_index, rngLo, border_color=color.new(#F0C040, 40), border_width=1, bgcolor=color.new(#F0C040, 94))
            if i_showBox and not na(rngBox)
                box.set_right(rngBox, bar_index)
                box.set_top(rngBox, rngHi)
                box.set_bottom(rngBox, rngLo)
    else
        rngStart := na
        rngBox := na
        rngBars := 0
 
rngHeight = (not na(rngHi) and not na(rngLo)) ? rngHi - rngLo : na
rngPct    = not na(rngHeight) ? rngHeight / close * 100.0 : na
 
// ── STATE CHANGE LABELS ───────────────────────────────────
if i_showLbl and stateChanged and barstate.isconfirmed and not isTrans
    txt  = isRange ? "RANGE" : trendUp ? "TREND UP" : "TREND DOWN"
    col  = isRange ? #F0C040 : trendUp ? #6DC230 : #FF6464
    sty  = trendUp ? label.style_label_up : label.style_label_down
    yPos = trendUp ? low : high
    label.new(bar_index, yPos, txt, color=color.new(col, 20), textcolor=color.black, style=sty, size=size.small)
 
// ── STATUS PANEL ──────────────────────────────────────────
var table pnl = table.new(position.top_right, 2, 6, bgcolor=#0D1117, border_width=1, border_color=#2A2D4A, frame_width=2, frame_color=#2A2D4A)
 
szBig = i_txtSize == "Small" ? size.normal : i_txtSize == "Normal" ? size.large : i_txtSize == "Large" ? size.huge : size.huge
szMid = i_txtSize == "Small" ? size.small : i_txtSize == "Normal" ? size.normal : i_txtSize == "Large" ? size.large : size.huge
szSml = i_txtSize == "Small" ? size.tiny : i_txtSize == "Normal" ? size.small : i_txtSize == "Large" ? size.normal : size.large
 
if i_showPnl and barstate.islast
    stTxt = isRange ? "RANGE" : trendUp ? "TREND UP" : trendDn ? "TREND DOWN" : "TRANSITION"
    stCol = isRange ? #F0C040 : trendUp ? #6DC230 : trendDn ? #FF6464 : #8899AA
    hdrBg = #1A1E3A
    rowBg = #0D1117
    thTxt = str.tostring(i_compTh, "#.##") + "% / " + str.tostring(i_trendTh, "#.##") + "%"
    qual  = isRange and rngBars >= i_minBars
    bandTxt = qual and not na(rngHeight) ? str.tostring(rngLo, format.mintick) + " - " + str.tostring(rngHi, format.mintick) : "-"
    sizeTxt = qual and not na(rngPct) ? str.tostring(rngHeight, format.mintick) + "  (" + str.tostring(rngPct, "#.##") + "%)  " + str.tostring(rngBars) + " bars" : "-"
 
    table.cell(pnl, 0, 0, "COMPRESSION", text_color=#8AB4FF, text_size=szMid, bgcolor=hdrBg, text_halign=text.align_left)
    table.cell(pnl, 1, 0, "", bgcolor=hdrBg)
    table.cell(pnl, 0, 1, stTxt, text_color=stCol, text_size=szBig, bgcolor=rowBg, text_halign=text.align_center)
    table.cell(pnl, 1, 1, "", bgcolor=rowBg)
    table.cell(pnl, 0, 2, "Separation", text_color=#BBBBBB, text_size=szMid, bgcolor=rowBg, text_halign=text.align_left)
    table.cell(pnl, 1, 2, str.tostring(sep, "#.###") + "%", text_color=color.white, text_size=szMid, bgcolor=rowBg, text_halign=text.align_right)
    table.cell(pnl, 0, 3, "Range / Trend", text_color=#BBBBBB, text_size=szSml, bgcolor=rowBg, text_halign=text.align_left)
    table.cell(pnl, 1, 3, thTxt, text_color=#9AAABB, text_size=szSml, bgcolor=rowBg, text_halign=text.align_right)
    table.cell(pnl, 0, 4, "Band", text_color=#BBBBBB, text_size=szSml, bgcolor=rowBg, text_halign=text.align_left)
    table.cell(pnl, 1, 4, bandTxt, text_color=#F0C040, text_size=szSml, bgcolor=rowBg, text_halign=text.align_right)
    table.cell(pnl, 0, 5, "Height", text_color=#BBBBBB, text_size=szSml, bgcolor=rowBg, text_halign=text.align_left)
    table.cell(pnl, 1, 5, sizeTxt, text_color=#8AB4FF, text_size=szSml, bgcolor=rowBg, text_halign=text.align_right)
 
// ── ALERTS ────────────────────────────────────────────────
alertcondition(stateChanged and isRange, "Range detected", "Moving average separation has collapsed - market is ranging.")
alertcondition(stateChanged and isTrend, "Trend detected", "Moving average separation has expanded - market is trending.")
 
plot(sep, "Separation %", color=color.new(color.purple, 100), display=display.data_window)

← 返回列表