本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// CA Range Break Evidence Map v2
// Changelog: v1 - initial release.
// v2 - narrower ranges forming inside an active range now replace it ("Superseded");
// default max width 6 ATR; active range edges plotted; stronger box styling;
// compact table (default) with text size and position inputs.
//
// Chart analysis indicator, symbol-agnostic. Detects consolidation ranges from the chart's own data and
// grades every close outside them by accumulated, volatility-scaled evidence instead of a single poke.
// - Range: rolling high/low over a lookback whose edges stayed unchanged for N bars, width inside an
// ATR band, and a low efficiency ratio (net move / total path) = choppy, two-sided trade.
// A narrower qualifying range inside an active one replaces it (optional).
// - Evidence: two-sided CUSUM on close-to-close changes standardised by an EWMA volatility estimate
// (drift allowance k, decision threshold h). Sums reset when a range forms or resolves.
// - States: sweep (wick beyond edge, close inside), pending break (close beyond edge, evidence < h),
// confirmed break (close beyond edge with evidence >= h), failed break (close back inside
// during the confirmation window), weak break (window ends without evidence), expired.
// All state changes happen on confirmed bars only. When a range is detected its box is drawn back to the
// start of the qualifying window; afterwards only its right edge and final style change.
// Volume pressure is a candle-body approximation (no intrabar data): volume * (close - open) / (high - low).
indicator("CA Range Break Evidence Map v2", shorttitle="CA RBE v2", overlay=true, max_labels_count=300, max_lines_count=50, max_boxes_count=100)
// ───────────── Inputs: range detection ─────────────
string gR = "Range detection"
int rngLen = input.int(30, "Range lookback (bars)", minval=10, maxval=500, group=gR, tooltip="30 bars = 5 days on 4H.")
int flatBars = input.int(6, "Edges unchanged for (bars)", minval=1, maxval=200, group=gR, tooltip="Both the rolling high and low must have stayed the same for at least this many bars.")
float erMax = input.float(0.35, "Max efficiency ratio", minval=0.05, maxval=1.0, step=0.05, group=gR, tooltip="|net move| / sum of |bar changes| over the lookback. Low values = choppy, range-like trade.")
float minWAtr = input.float(2.0, "Min range width (ATR)", minval=0.5, maxval=50.0, step=0.5, group=gR)
float maxWAtr = input.float(6.0, "Max range width (ATR)", minval=1.0, maxval=100.0, step=0.5, group=gR)
bool useRefine = input.bool(true, "Replace with narrower inner range", group=gR, tooltip="If a new qualifying range forms while one is active and is clearly narrower, it replaces the active one.")
float refineRatio = input.float(0.7, "Inner range max width (x active width)", minval=0.2, maxval=0.95, step=0.05, group=gR)
int maxAge = input.int(150, "Range expiry (bars)", minval=10, maxval=2000, group=gR)
int atrLen = input.int(14, "ATR length", minval=1, group=gR)
// ───────────── Inputs: break evidence ─────────────
string gB = "Break evidence (CUSUM)"
float src = input.source(close, "Source", group=gB)
int volLen = input.int(50, "Volatility length (EWMA)", minval=5, maxval=500, group=gB)
float kDrift = input.float(0.5, "Drift allowance k (sigma)", minval=0.0, maxval=3.0, step=0.1, group=gB, tooltip="Bar moves smaller than k sigma drain the evidence instead of building it.")
float hThr = input.float(2.5, "Decision threshold h (sigma)", minval=0.5, maxval=20.0, step=0.25, group=gB, tooltip="Accumulated evidence needed to call a break confirmed. Higher = stricter.")
float bufAtr = input.float(0.10, "Min close beyond edge (ATR)", minval=0.0, maxval=3.0, step=0.05, group=gB)
int confWin = input.int(6, "Confirmation window (bars)", minval=1, maxval=100, group=gB, tooltip="Bars a pending break has to build evidence before it is graded weak.")
int vpLen = input.int(14, "Volume pressure length", minval=1, maxval=200, group=gB)
bool useVp = input.bool(false, "Require volume pressure agreement (optional filter)", group=gB, tooltip="If on, a confirmed break up also needs positive volume pressure, and a break down negative.")
// ───────────── Inputs: visuals ─────────────
string gV = "Visuals"
bool showEdges = input.bool(true, "Show active range edges", group=gV)
bool showBoxes = input.bool(true, "Show range boxes", group=gV)
int maxBoxes = input.int(20, "Max range boxes", minval=1, maxval=90, group=gV)
bool showMarks = input.bool(true, "Show sweep / pending markers", group=gV)
bool showLabels = input.bool(true, "Show outcome labels", group=gV)
int maxLabels = input.int(120, "Max outcome labels", minval=1, maxval=280, group=gV)
bool showBg = input.bool(true, "Tint background while a break is pending", group=gV)
bool showTrig = input.bool(true, "Show 1-bar drift break levels", group=gV)
float nearAtr = input.float(6.0, "Hide trigger levels farther than (ATR)", minval=1.0, maxval=50.0, step=0.5, group=gV)
bool showTable = input.bool(true, "Show table", group=gV)
bool fullTable = input.bool(false, "Full table (more rows)", group=gV)
string tableSize = input.string("Tiny", "Table text size", options=["Tiny", "Small", "Normal"], group=gV)
string tablePos = input.string("Bottom right", "Table position", options=["Top right", "Bottom right", "Top left", "Bottom left"], group=gV)
// ───────────── Calculations (every bar) ─────────────
float atr = ta.atr(atrLen)
float hh = ta.highest(high, rngLen)
float ll = ta.lowest(low, rngLen)
bool hhChg = na(hh[1]) or hh != hh[1]
bool llChg = na(ll[1]) or ll != ll[1]
int hhAge = ta.barssince(hhChg)
int llAge = ta.barssince(llChg)
float pathSum = math.sum(math.abs(close - close[1]), rngLen)
float er = na(pathSum) or pathSum <= 0 or na(close[rngLen]) ? na : math.abs(close - close[rngLen]) / pathSum
// EWMA volatility of bar changes (seeded with a simple average)
float d = src - src[1]
float d2 = na(d) ? na : d * d
float smaD2 = ta.sma(d2, volLen)
float alpha = 2.0 / (volLen + 1)
var float ev = na
if na(ev)
ev := smaD2
else if not na(d2)
ev := alpha * d2 + (1.0 - alpha) * ev
float sigPrev = na(ev[1]) or ev[1] <= 0 ? na : math.sqrt(ev[1])
float z = na(sigPrev) or na(d) ? 0.0 : d / sigPrev
// Two-sided CUSUM
var float sUp = 0.0
var float sDn = 0.0
if not na(sigPrev)
sUp := math.max(0.0, sUp + z - kDrift)
sDn := math.max(0.0, sDn - z - kDrift)
// Volume pressure (candle-body approximation)
float barRng = high - low
float vol = nz(volume)
float barP = barRng > 0 ? vol * (close - open) / barRng : 0.0
float vSum = math.sum(vol, vpLen)
float pSum = math.sum(barP, vpLen)
float vp = na(vSum) or vSum <= 0 ? na : 100.0 * pSum / vSum
bool vpOkUp = not useVp or (not na(vp) and vp > 0)
bool vpOkDn = not useVp or (not na(vp) and vp < 0)
// ───────────── Helpers ─────────────
var array<label> evLabels = array.new<label>()
addLabel(int x, float y, string txt, color col, bool below, string tip) =>
if showLabels
label lb = label.new(x, y, txt, style=below ? label.style_label_up : label.style_label_down, color=color.new(col, 10), textcolor=color.white, size=size.small, tooltip=tip)
evLabels.push(lb)
if evLabels.size() > maxLabels
evLabels.shift().delete()
px(float x) => na(x) ? "-" : str.tostring(math.round_to_mintick(x), format.mintick)
num(float x) => na(x) ? "-" : str.tostring(x, "#.##")
breakOnChange(float x) => x != x[1] ? na : x
// ───────────── State ─────────────
// st: 0 = no range, 1 = inside range, 2 = pending break up, 3 = pending break down
var int st = 0
var float rTop = na
var float rBot = na
var int rCreated = na
var int pendBar = na
var int lastEnd = na
var int sweepsUp = 0
var int sweepsDn = 0
var int nConf = 0
var int nFail = 0
var int nWeak = 0
var int nExp = 0
var int nSup = 0
var string lastOutcome = "-"
var box curBox = na
var array<box> boxes = array.new<box>()
bool evNew = false
bool evSweepUp = false
bool evSweepDn = false
bool evPendUp = false
bool evPendDn = false
bool evConfUp = false
bool evConfDn = false
bool evFail = false
bool evWeak = false
bool endNow = false
string endTxt = ""
color endCol = color.gray
bool ready = barstate.isconfirmed and not na(atr) and atr > 0
float bufP = na(atr) ? na : bufAtr * atr
if ready
// 1) Manage the active range
if st == 1
if close > rTop + bufP
if sUp >= hThr and vpOkUp
evConfUp := true
nConf += 1
endNow := true
endTxt := "Confirmed break up"
endCol := color.teal
addLabel(bar_index, low, "BREAK UP", color.teal, true, "Close above the range with up-evidence " + num(sUp) + " >= h " + num(hThr) + " sigma.")
else
st := 2
pendBar := bar_index
evPendUp := true
else if close < rBot - bufP
if sDn >= hThr and vpOkDn
evConfDn := true
nConf += 1
endNow := true
endTxt := "Confirmed break down"
endCol := color.red
addLabel(bar_index, high, "BREAK DN", color.red, false, "Close below the range with down-evidence " + num(sDn) + " >= h " + num(hThr) + " sigma.")
else
st := 3
pendBar := bar_index
evPendDn := true
else
if high > rTop and close <= rTop
evSweepUp := true
sweepsUp += 1
if low < rBot and close >= rBot
evSweepDn := true
sweepsDn += 1
if bar_index - rCreated >= maxAge
nExp += 1
endNow := true
endTxt := "Expired"
endCol := color.gray
else if st == 2
if close < rTop
evFail := true
nFail += 1
sUp := 0.0
st := 1
addLabel(bar_index, high, "FAIL", color.red, false, "Failed break up: closed back inside the range within " + str.tostring(confWin) + " bars.")
else if close > rTop + bufP and sUp >= hThr and vpOkUp
evConfUp := true
nConf += 1
endNow := true
endTxt := "Confirmed break up"
endCol := color.teal
addLabel(bar_index, low, "BREAK UP", color.teal, true, "Pending break up confirmed: up-evidence " + num(sUp) + " >= h " + num(hThr) + " sigma.")
else if bar_index - pendBar >= confWin
evWeak := true
nWeak += 1
endNow := true
endTxt := "Weak break up"
endCol := color.gray
addLabel(bar_index, low, "WEAK", color.gray, true, "Price stayed above the range but evidence never reached h within " + str.tostring(confWin) + " bars.")
else if st == 3
if close > rBot
evFail := true
nFail += 1
sDn := 0.0
st := 1
addLabel(bar_index, low, "FAIL", color.teal, true, "Failed break down: closed back inside the range within " + str.tostring(confWin) + " bars.")
else if close < rBot - bufP and sDn >= hThr and vpOkDn
evConfDn := true
nConf += 1
endNow := true
endTxt := "Confirmed break down"
endCol := color.red
addLabel(bar_index, high, "BREAK DN", color.red, false, "Pending break down confirmed: down-evidence " + num(sDn) + " >= h " + num(hThr) + " sigma.")
else if bar_index - pendBar >= confWin
evWeak := true
nWeak += 1
endNow := true
endTxt := "Weak break down"
endCol := color.gray
addLabel(bar_index, high, "WEAK", color.gray, false, "Price stayed below the range but evidence never reached h within " + str.tostring(confWin) + " bars.")
// 2) Detect a new range (or a narrower inner range that replaces the active one)
bool gapOk = na(lastEnd) or bar_index - lastEnd >= flatBars
bool canNew = st == 0 and not endNow and gapOk
bool canRefine = useRefine and st == 1 and not endNow and not na(rTop) and not na(rBot)
if (canNew or canRefine) and not na(hh) and not na(ll) and not na(er)
float w = hh - ll
bool hhFlat = not na(hhAge) and hhAge >= flatBars
bool llFlat = not na(llAge) and llAge >= flatBars
bool qual = er <= erMax and w >= minWAtr * atr and w <= maxWAtr * atr and hhFlat and llFlat
bool narrow = canNew or w <= refineRatio * (rTop - rBot)
if qual and narrow
if canRefine
nSup += 1
endNow := true
endTxt := "Superseded"
endCol := color.gray
// close the previous box before opening the new one
if endNow and not na(curBox)
curBox.set_right(bar_index)
curBox.set_border_color(color.new(endCol, 30))
curBox.set_bgcolor(color.new(endCol, 94))
curBox.set_border_style(line.style_dashed)
curBox.set_border_width(1)
curBox.set_text(endTxt)
curBox := na
if endNow
lastOutcome := endTxt
endNow := false
st := 1
rTop := hh
rBot := ll
rCreated := bar_index
sweepsUp := 0
sweepsDn := 0
sUp := 0.0
sDn := 0.0
evNew := true
if showBoxes
curBox := box.new(bar_index - rngLen + 1, rTop, bar_index, rBot, border_color=color.new(color.orange, 0), border_width=2, bgcolor=color.new(color.orange, 85), text="Range " + num(w / atr) + " ATR", text_size=size.small, text_color=color.new(color.orange, 0), text_halign=text.align_left, text_valign=text.align_top)
boxes.push(curBox)
if boxes.size() > maxBoxes
boxes.shift().delete()
// 3) Resolve the range
if endNow
st := 0
lastEnd := bar_index
lastOutcome := endTxt
sUp := 0.0
sDn := 0.0
if not na(curBox)
bool expired = endTxt == "Expired"
curBox.set_right(bar_index)
curBox.set_border_color(color.new(endCol, expired ? 30 : 0))
curBox.set_bgcolor(color.new(endCol, expired ? 94 : 88))
curBox.set_border_style(expired ? line.style_dashed : line.style_solid)
curBox.set_border_width(expired ? 1 : 2)
curBox.set_text(endTxt)
curBox.set_text_color(color.new(endCol, 0))
curBox := na
// Keep the active box extended to the current bar
if st != 0 and not na(curBox)
curBox.set_right(bar_index)
// ───────────── Active range edges ─────────────
float topPl = breakOnChange(st != 0 ? rTop : na)
float botPl = breakOnChange(st != 0 ? rBot : na)
plot(showEdges ? topPl : na, "Range top", color=color.new(color.orange, 0), linewidth=2, style=plot.style_linebr, display=display.pane)
plot(showEdges ? botPl : na, "Range bottom", color=color.new(color.orange, 0), linewidth=2, style=plot.style_linebr, display=display.pane)
// ───────────── 1-bar drift break levels (close needed on the current bar) ─────────────
float trigUp = st == 0 or na(sigPrev) or na(bufP) ? na : math.max(rTop + bufP, close[1] + (hThr - sUp[1] + kDrift) * sigPrev)
float trigDn = st == 0 or na(sigPrev) or na(bufP) ? na : math.min(rBot - bufP, close[1] - (hThr - sDn[1] + kDrift) * sigPrev)
var line lnUp = na
var line lnDn = na
var label lbUp = na
var label lbDn = na
if barstate.islast
line.delete(lnUp)
line.delete(lnDn)
label.delete(lbUp)
label.delete(lbDn)
if showTrig and not na(atr)
if not na(trigUp) and math.abs(trigUp - close) <= nearAtr * atr
lnUp := line.new(bar_index, trigUp, bar_index + 8, trigUp, color=color.new(color.teal, 0), style=line.style_dotted, width=2)
lbUp := label.new(bar_index + 8, trigUp, "1-bar drift break up " + px(trigUp), style=label.style_label_left, color=color.new(color.teal, 70), textcolor=color.white, size=size.small)
if not na(trigDn) and math.abs(close - trigDn) <= nearAtr * atr
lnDn := line.new(bar_index, trigDn, bar_index + 8, trigDn, color=color.new(color.red, 0), style=line.style_dotted, width=2)
lbDn := label.new(bar_index + 8, trigDn, "1-bar drift break down " + px(trigDn), style=label.style_label_left, color=color.new(color.red, 70), textcolor=color.white, size=size.small)
// ───────────── Markers and background ─────────────
plotshape(showMarks and evSweepUp, "Sweep above range", shape.triangledown, location.abovebar, color=color.new(color.orange, 0), size=size.small, display=display.pane)
plotshape(showMarks and evSweepDn, "Sweep below range", shape.triangleup, location.belowbar, color=color.new(color.orange, 0), size=size.small, display=display.pane)
plotshape(showMarks and evPendUp, "Pending break up", shape.diamond, location.belowbar, color=color.new(color.teal, 0), size=size.small, display=display.pane)
plotshape(showMarks and evPendDn, "Pending break down", shape.diamond, location.abovebar, color=color.new(color.red, 0), size=size.small, display=display.pane)
bgcolor(showBg and (st == 2 or st == 3) ? color.new(color.orange, 90) : na, title="Pending break tint")
// ───────────── Table ─────────────
string tPos = tablePos == "Top right" ? position.top_right : tablePos == "Bottom right" ? position.bottom_right : tablePos == "Top left" ? position.top_left : position.bottom_left
string tSize = tableSize == "Tiny" ? size.tiny : tableSize == "Small" ? size.small : size.normal
var table tbl = table.new(tPos, 2, 12, bgcolor=color.new(color.black, 40), border_width=1, border_color=color.new(color.gray, 70))
cell(int c, int r, string t, color tc) =>
table.cell(tbl, c, r, t, text_color=tc, text_size=tSize, text_halign=c == 0 ? text.align_left : text.align_right)
if barstate.islast and showTable
string stTxt = st == 0 ? "No active range" : st == 1 ? "Inside range" : st == 2 ? "Pending up " + str.tostring(bar_index - pendBar) + "/" + str.tostring(confWin) : "Pending down " + str.tostring(bar_index - pendBar) + "/" + str.tostring(confWin)
color stCol = st == 2 ? color.teal : st == 3 ? color.red : st == 1 ? color.orange : color.gray
bool act = st != 0 and not na(rTop) and not na(rBot)
float wR = act ? rTop - rBot : na
float pos = act and wR > 0 ? 100.0 * (close - rBot) / wR : na
cell(0, 0, "Range state", color.white)
cell(1, 0, stTxt, stCol)
cell(0, 1, "Top / bottom", color.white)
cell(1, 1, act ? px(rTop) + " / " + px(rBot) : "-", color.orange)
cell(0, 2, "Position / width", color.white)
cell(1, 2, act and not na(atr) and atr > 0 ? (na(pos) ? "-" : str.tostring(pos, "#") + "%") + " / " + num(wR / atr) + " ATR" : "-", color.white)
cell(0, 3, "Evidence up / down (h " + num(hThr) + ")", color.white)
cell(1, 3, num(sUp) + " / " + num(sDn), sUp >= hThr ? color.teal : sDn >= hThr ? color.red : color.white)
cell(0, 4, "1-bar drift break up / down", color.white)
cell(1, 4, px(trigUp) + " / " + px(trigDn), color.white)
cell(0, 5, "Volume pressure (" + str.tostring(vpLen) + ")", color.white)
cell(1, 5, na(vp) ? "-" : (vp > 0 ? "+" : "") + str.tostring(vp, "#.#") + "%", na(vp) ? color.gray : vp > 0 ? color.teal : color.red)
cell(0, 6, "Last resolved", color.white)
cell(1, 6, lastOutcome, color.gray)
if fullTable
cell(0, 7, "Age (bars)", color.white)
cell(1, 7, act ? str.tostring(bar_index - rCreated) : "-", color.white)
cell(0, 8, "Sweeps above / below", color.white)
cell(1, 8, act ? str.tostring(sweepsUp) + " / " + str.tostring(sweepsDn) : "-", color.orange)
cell(0, 9, "Conf / fail / weak", color.white)
cell(1, 9, str.tostring(nConf) + " / " + str.tostring(nFail) + " / " + str.tostring(nWeak), color.gray)
cell(0, 10, "Expired / superseded", color.white)
cell(1, 10, str.tostring(nExp) + " / " + str.tostring(nSup), color.gray)
cell(0, 11, "Closed bars only; evidence in sigma (k " + num(kDrift) + "). Loaded history only.", color.gray)
table.merge_cells(tbl, 0, 11, 1, 11)
// ───────────── Alerts (confirmed bars only) ─────────────
alertcondition(evNew, "Range formed", "{{ticker}} {{interval}}: new consolidation range detected")
alertcondition(evSweepUp, "Sweep above range", "{{ticker}} {{interval}}: wick above range top, close back inside")
alertcondition(evSweepDn, "Sweep below range", "{{ticker}} {{interval}}: wick below range bottom, close back inside")
alertcondition(evPendUp, "Pending break up", "{{ticker}} {{interval}}: close above range, evidence below threshold")
alertcondition(evPendDn, "Pending break down", "{{ticker}} {{interval}}: close below range, evidence below threshold")
alertcondition(evConfUp, "Confirmed break up", "{{ticker}} {{interval}}: drift-confirmed break above range")
alertcondition(evConfDn, "Confirmed break down", "{{ticker}} {{interval}}: drift-confirmed break below range")
alertcondition(evFail, "Failed break", "{{ticker}} {{interval}}: break failed, close back inside range")