本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("BTC Cost Basis Quantile Bands", shorttitle="BTC-CQB", overlay=true, max_bars_back=5000, max_labels_count=500)
GRP_LOCK = "0 - Market Lock"
GRP_CB = "1 - Cost Basis Engine"
GRP_SQZ = "2 - Volatility & Bandwidth Squeeze"
GRP_DIV = "3 - Quantile Momentum Divergence"
GRP_CONF = "4 - Signal Confirmation & Alerts"
GRP_VIS = "5 - Visuals & Display"
GRP_TBL = "6 - Dashboard Table"
minTF = input.string("240", "Minimum Allowed Timeframe (Minutes)", group=GRP_LOCK,
tooltip="BTC-CQB is a position/swing tool built on a rolling statistical distribution of price deviation from its cost basis. Below this timeframe the sample is too noisy and the market-microstructure noise dominates the signal, so the script will refuse to calculate and will throw an error instead of printing misleading numbers. Default is 240 minutes (4 hours). Raise it (e.g. to 1D) if you want to restrict the script to Daily or higher only.")
isBTC = syminfo.basecurrency == "BTC" or str.contains(syminfo.root, "BTC") or str.contains(syminfo.ticker, "BTC")
isTFok = timeframe.in_seconds(timeframe.period) >= timeframe.in_seconds(minTF)
if not isBTC
runtime.error("BTC-CQB is locked to Bitcoin pairs only (BTC vs. any quote currency, e.g. USD, USDT, USDC - any exchange). Current symbol is not supported.")
if not isTFok
runtime.error("BTC-CQB requires a timeframe of 4 hours or higher.")
src = input.source(close, "Source Price", group=GRP_CB,
tooltip="The price series the entire cost-basis / quantile engine is built on. Close is the academically standard choice because it represents the price market participants actually settled at when the bar finished forming. Switching to hl2, hlc3 or a custom series will shift every band slightly and is intended for advanced experimentation only.")
cbType = input.string("VWMA", "Cost Basis Type", options=["SMA", "EMA", "VWMA"], group=GRP_CB,
tooltip="Selects the moving-average engine used as the statistical 'center of gravity' (the proxy cost basis) that all quantile bands are measured around.\n\n• SMA - equal weight to every bar in the window, slowest to react, most stable.\n• EMA - exponentially weights recent bars, reacts faster to new trend shifts.\n• VWMA (default) - weights each bar by its traded volume, so bars with heavier participation (higher conviction) pull the cost basis more than quiet, low-volume bars. This is the closest proxy to a true aggregate on-chain cost basis that can be built from price/volume data alone.")
cbLen = input.int(155, "Main Cost-Basis Lookback (Bars)", minval=5, maxval=1000, group=GRP_CB,
tooltip="Number of bars used to build the main cost-basis average. On a Daily chart this is approximately equal to that many calendar days (155 ≈ 5 months); on any other allowed timeframe (the script enforces 4H minimum) it is 155 BARS of that timeframe, which is a shorter real-world duration (e.g. 155 bars on a 4H chart ≈ 25.8 days). Enable 'Auto-Scale Lookbacks to Calendar Days' below if you want this value to always represent real calendar days regardless of the chart timeframe you are on.")
enableFast = input.bool(true, "Enable Fast Cost-Basis Overlay", group=GRP_CB,
tooltip="Plots a secondary, shorter-window cost-basis line (white) alongside the main one. Comparing the fast line to the main line is a simple proxy for short-term versus long-term holder cost basis and a fast/slow moving-average cross engine: fast above main = short-term participants are, on average, paying a premium to the longer-term base (short-term bullish momentum); fast below main = the opposite.")
fastLen = input.int(30, "Fast Cost-Basis Lookback (Bars)", minval=5, maxval=90, group=GRP_CB,
tooltip="Number of bars used for the fast cost-basis line. Same bars-vs-calendar-days caveat as the main lookback above applies here; see the 'Auto-Scale Lookbacks to Calendar Days' tooltip for details.")
qLen = input.int(365, "Quantile Window (Bars)", minval=30, maxval=1500, group=GRP_CB,
tooltip="Size of the rolling sample (in bars) used to compute the statistical distribution of price deviation from its cost basis, from which the Q10/Q25/Q50/Q75/Q90 percentile bands are derived every bar. A larger window produces a more statistically robust, slower-moving distribution (closer to 'full cycle' behaviour); a smaller window adapts faster to recent volatility regimes but is noisier. The dashboard's 'History' row tells you how much of this window is currently filled and whether the bands are statistically reliable yet.")
smoothLen = input.int(1, "Band Smoothing (1 = Pure Raw Math)", minval=1, maxval=21, group=GRP_CB,
tooltip="Applies a light EMA smoothing pass to the final percentile bands to reduce bar-to-bar jaggedness. The default value of 1 is mathematically a pass-through (no smoothing at all - the bands are the pure, unaltered percentile output). Increase gradually (e.g. 3-5) only if you want visually smoother bands for discretionary chart reading; higher values trade a small amount of responsiveness for smoothness.")
autoScaleDays = input.bool(false, "Auto-Scale Lookbacks to Calendar Days", group=GRP_CB,
tooltip="OFF by default to preserve the original bar-counting behaviour exactly. When turned ON, the Main/Fast Cost-Basis and Quantile Window lookbacks above are automatically multiplied by the number of bars-per-day implied by your current chart timeframe (e.g. x6 on a 4H chart, x1 on a Daily chart), so a value of '365' always means '365 real calendar days' of history no matter which allowed timeframe you are viewing. Internally capped to protect script performance on very low timeframes.")
sqzLookback = input.int(100, "Squeeze Lookback Window (Bars)", minval=20, maxval=500, group=GRP_SQZ,
tooltip="Number of bars used as the rolling reference window to detect a bandwidth squeeze. The script compares today's band bandwidth (Q90-Q10, normalized by Q50) against the lowest bandwidth reading inside this window; when price's statistical dispersion compresses close to its local minimum, a squeeze is flagged. Conceptually this is the same idea as a Bollinger Band-Width squeeze, applied to the cost-basis quantile bands instead of a standard-deviation envelope.")
sqzThresholdPct = input.float(5.0, "Squeeze Sensitivity Threshold (%)", minval=0.1, maxval=50.0, step=0.1, group=GRP_SQZ,
tooltip="How close (in %) the current bandwidth must be to the rolling minimum bandwidth to be classified as a squeeze. Default 5.0 means bandwidth must be within 5% of its lowest value over the Squeeze Lookback Window. Lower this value to only flag the tightest, most extreme compressions; raise it to flag squeezes earlier/more frequently.")
showSqzBG = input.bool(false, "Highlight Squeeze Bars (Background)", group=GRP_SQZ,
tooltip="Paints a soft yellow background behind bars where a bandwidth squeeze is currently active, making periods of compressed volatility (historically often followed by expansion / a directional breakout) easy to spot visually.")
useVolFloor = input.bool(true, "Enable ATR Volatility Floor", group=GRP_SQZ,
tooltip="Prevents the Q10/Q90 extreme bands from collapsing to an unrealistically tight width during very low-volatility regimes by enforcing a minimum half-width, in price terms, derived from ATR. This keeps the euphoria/capitulation bands statistically meaningful even if the recent percentile sample happens to be abnormally compressed.")
atrFloorLen = input.int(14, "ATR Length for Floor", minval=1, maxval=200, group=GRP_SQZ,
tooltip="Lookback length of the Average True Range calculation used purely to build the volatility floor described above. This is a classic Wilder ATR length; 14 is the standard default used across most ATR-based tools.")
atrFloorMult = input.float(1.0, "ATR Floor Multiplier", minval=0.1, step=0.1, group=GRP_SQZ,
tooltip="Multiplies the ATR Floor value to set how far, at minimum, Q90/Q10 must sit from Q50. Increase this to force wider extreme bands during calm markets; decrease it to let the pure percentile statistics dominate with less ATR interference. Has no effect if 'Enable ATR Volatility Floor' is off.")
showDiv = input.bool(true, "Detect Quantile Momentum Divergences", group=GRP_DIV,
tooltip="Enables a pivot-based divergence detector that compares swing price extremes against the indicator's own 0-100 band-position score (where price sits between Q10 and Q90). A bullish divergence prints when a new swing low in price is NOT confirmed by a new swing low in the band-position score (i.e. price fell further but is relatively less stretched inside the distribution than at the prior swing low), and a bearish divergence is the mirror case at swing highs. This is the classic price/oscillator divergence concept applied to a distribution-based oscillator instead of RSI or MACD.")
pivLeft = input.int(5, "Pivot Left Lookback (Bars)", minval=1, maxval=20, group=GRP_DIV,
tooltip="Number of bars to the left of a candidate swing point that must have a lower low / higher high for that point to qualify as a pivot. Larger values require a more significant, larger-radius swing before it is considered a pivot.")
pivRight = input.int(3, "Pivot Right Lookback (Bars)", minval=1, maxval=10, group=GRP_DIV,
tooltip="Number of bars to the right of a candidate swing point required to confirm it as a pivot. This is also the structural confirmation delay: a pivot (and therefore a divergence built on it) can only be confirmed this many bars after it actually occurred, which is what makes the divergence engine inherently non-repainting - once printed, a pivot-based divergence does not move or disappear.")
waitForClose = input.bool(true, "Wait for Bar Close Before Signals (Recommended)", group=GRP_CONF,
tooltip="Controls whether discrete, actionable signals - breakout/breakdown crosses, euphoria/capitulation taps, squeeze-start events, and divergence markers/labels/alerts - are allowed to fire on the current, still-forming bar, or must wait until the bar is fully confirmed (barstate.isconfirmed).\n\nON (default, recommended for non-repainting behaviour): a signal can only appear after its triggering bar has closed, exactly as the data will remain forever - no mid-bar flip-flopping and no signal that silently disappears before the candle closes.\n\nOFF: signals can appear intrabar as soon as the condition is true, which is faster but means a signal may appear and then vanish again before the bar closes if price reverses. The continuous heat-map coloring of candles/background and the live dashboard numbers always remain real-time regardless of this setting, since they describe the current state of the market rather than a discrete trade trigger.")
showQ90 = input.bool(true, "Q90 Euphoria", inline="b1", group=GRP_VIS,
tooltip="Shows/hides the 90th-percentile band: historically, the level above which price has only traded 10% of the time over the lookback window. Readings above this band are flagged on the dashboard as 'EUPHORIA'.")
showQ75 = input.bool(true, "Q75 Overheated", inline="b1", group=GRP_VIS,
tooltip="Shows/hides the 75th-percentile band: price has traded above this level only 25% of the time over the lookback window. Used as the 'overheated' trigger level for the breakout marker and the dashboard's distance-to-target readout.")
showQ50 = input.bool(true, "Q50 Cost Basis", inline="b1", group=GRP_VIS,
tooltip="Shows/hides the median (50th percentile) band, which also represents the selected Cost-Basis Type (SMA/EMA/VWMA) - the statistical center line that all other quantile bands are measured around.")
showQ25 = input.bool(true, "Q25 Discount", inline="b2", group=GRP_VIS,
tooltip="Shows/hides the 25th-percentile band: price has traded below this level only 25% of the time over the lookback window. Used as the breakdown trigger level.")
showQ10 = input.bool(true, "Q10 Capitulation", inline="b2", group=GRP_VIS,
tooltip="Shows/hides the 10th-percentile band: historically, the level below which price has only traded 10% of the time over the lookback window. Readings below this band are flagged on the dashboard as 'CAPITULATION'.")
showFastCB = input.bool(true, "Show Fast Cost-Basis Line", group=GRP_VIS,
tooltip="Plots the shorter-window (white) cost-basis line defined in the Cost Basis Engine group, used to visually compare short-term versus longer-term average acquisition price.")
showShadeExt = input.bool(true, "Shade Premium / Discount Zones", group=GRP_VIS,
tooltip="Fills the area between Q75-Q90 (premium/overheated zone) and between Q10-Q25 (discount zone) with a light color gradient so these regions are immediately visible without needing to read exact band values.")
showShadeVal = input.bool(true, "Shade Value Zone (Q25-Q75)", group=GRP_VIS,
tooltip="Fills the area between Q25 and Q75 - the statistical 'fair value' zone where price has historically spent 50% of its time - with a soft highlight color.")
showCandles = input.bool(true, "Color Heat Candles (Body & Wicks)", group=GRP_VIS,
tooltip="Recolors every candle's body, wick and border according to which quantile zone the close is currently inside (above Q90, between Q50-Q90, between Q10-Q50, or below Q10), turning the chart into an at-a-glance 'valuation heat map'. This recoloring is a continuous descriptive state and is therefore always real-time regardless of the 'Wait for Bar Close' setting.")
showBG = input.bool(false, "Heat Background Highlights", group=GRP_VIS,
tooltip="Adds a soft full-width background tint when price is inside the euphoria, overheated, discount or capitulation zones, reinforcing the heat-map reading behind the bars/candles themselves.")
showShapes = input.bool(true, "Breakout Markers", group=GRP_VIS,
tooltip="Plots small triangle/marker shapes for the three core discrete events: crossing above Q75, tapping into the Q90 euphoria zone, and crossing below Q25. These markers obey the 'Wait for Bar Close' confirmation setting.")
showBreakoutLabels = input.bool(false, "Breakout Labels", group=GRP_VIS,
tooltip="Adds explicit text labels ('+Q75 BREAK', 'EUPHORIA') at breakout and euphoria-tap events, in addition to (or instead of) the small marker shapes. Also obeys the 'Wait for Bar Close' confirmation setting.")
showDivLabels = input.bool(false, "Divergence Labels", group=GRP_VIS,
tooltip="Adds explicit 'BULL DIV' / 'BEAR DIV' text labels at confirmed pivot locations, in addition to (or instead of) the small circle markers plotted by the divergence engine.")
showTable = input.bool(true, "Show Dashboard Table", group=GRP_TBL,
tooltip="Toggles the on-chart data panel that summarizes the current quantile score, regime classification, price, cost-basis values, bandwidth/squeeze status, divergence state and distance to the next statistical target level.")
tablePosOpt = input.string("Top Right", "Table Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=GRP_TBL,
tooltip="Selects which corner of the chart the dashboard table is anchored to.")
tableSizeOpt = input.string("Small", "Table Text Size", options=["Tiny", "Small", "Normal", "Large"], group=GRP_TBL,
tooltip="Controls the font size of the dashboard table's text, independent of chart zoom level.")
f_tablePos(string s) =>
switch s
"Top Right" => position.top_right
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
=> position.top_right
f_tableSize(string s) =>
switch s
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
=> size.small
barsPerDay = timeframe.in_seconds(timeframe.period) > 0 ? math.max(1.0, 86400.0 / timeframe.in_seconds(timeframe.period)) : 1.0
effCbLenF = autoScaleDays ? cbLen * barsPerDay : cbLen
effFastLenF = autoScaleDays ? fastLen * barsPerDay : fastLen
effQLenF = autoScaleDays ? qLen * barsPerDay : qLen
effCbLen = int(math.min(effCbLenF, 4500))
effFastLen = int(math.min(effFastLenF, 4500))
effQLen = int(math.min(effQLenF, 4500))
smaMain = ta.sma(src, effCbLen)
emaMain = ta.ema(src, effCbLen)
vwmaMain = ta.vwma(src, effCbLen)
smaFast = ta.sma(src, effFastLen)
emaFast = ta.ema(src, effFastLen)
vwmaFast = ta.vwma(src, effFastLen)
f_selectCB(float _sma, float _ema, float _vwma, string _type) =>
switch _type
"SMA" => _sma
"EMA" => _ema
"VWMA" => _vwma
=> _sma
cb = f_selectCB(smaMain, emaMain, vwmaMain, cbType)
cbFast = f_selectCB(smaFast, emaFast, vwmaFast, cbType)
dev = cb > 0 ? math.log(src / cb) : na
var float[] devWindow = array.new_float(0)
if not na(dev)
array.push(devWindow, dev)
if array.size(devWindow) > effQLen
array.shift(devWindow)
f_percentile(float[] sortedArr, float p) =>
int n = array.size(sortedArr)
float result = na
if n > 0
float rank = (p / 100.0) * (n - 1)
int lo = int(math.floor(rank))
int hi = int(math.ceil(rank))
float loVal = array.get(sortedArr, lo)
float hiVal = array.get(sortedArr, hi)
float frac = rank - lo
result := loVal + (hiVal - loVal) * frac
result
sortedDev = array.copy(devWindow)
array.sort(sortedDev, order.ascending)
histCount = array.size(devWindow)
histReady = histCount >= effQLen
q90dev = f_percentile(sortedDev, 90)
q75dev = f_percentile(sortedDev, 75)
q50dev = f_percentile(sortedDev, 50)
q25dev = f_percentile(sortedDev, 25)
q10dev = f_percentile(sortedDev, 10)
q90raw = not na(q90dev) ? cb * math.exp(q90dev) : na
q75raw = not na(q75dev) ? cb * math.exp(q75dev) : na
q50raw = not na(q50dev) ? cb * math.exp(q50dev) : na
q25raw = not na(q25dev) ? cb * math.exp(q25dev) : na
q10raw = not na(q10dev) ? cb * math.exp(q10dev) : na
atrFloor = ta.atr(atrFloorLen)
minHalfWidth = useVolFloor ? atrFloorMult * atrFloor : 0.0
q90floored = not na(q90raw) and not na(q50raw) ? math.max(q90raw, q50raw + minHalfWidth) : q90raw
q10floored = not na(q10raw) and not na(q50raw) ? math.min(q10raw, q50raw - minHalfWidth) : q10raw
q90s = ta.ema(q90floored, smoothLen)
q75s = ta.ema(q75raw, smoothLen)
q50s = ta.ema(q50raw, smoothLen)
q25s = ta.ema(q25raw, smoothLen)
q10s = ta.ema(q10floored, smoothLen)
f_bandScore(float px, float b10, float b25, float b50, float b75, float b90) =>
float res = 50.0
if px <= b10
res := 10.0 - (b10 - px) / math.max(1.0, b25 - b10) * 18.0
else if px <= b25
res := 10.0 + (px - b10) / math.max(1.0, b25 - b10) * 15.0
else if px <= b50
res := 25.0 + (px - b25) / math.max(1.0, b50 - b25) * 25.0
else if px <= b75
res := 50.0 + (px - b50) / math.max(1.0, b75 - b50) * 25.0
else if px <= b90
res := 75.0 + (px - b75) / math.max(1.0, b90 - b75) * 15.0
else
res := 90.0 + (px - b90) / math.max(1.0, b90 - b75) * 14.0
math.max(0.0, math.min(99.5, res))
qNow = f_bandScore(close, q10s, q25s, q50s, q75s, q90s)
qBW = q50s > 0 ? ((q90s - q10s) / q50s) * 100.0 : 0.0
qBW_min = ta.lowest(qBW, sqzLookback)
sqzFactor = 1.0 + (sqzThresholdPct / 100.0)
isSqueeze = qBW <= qBW_min * sqzFactor
sqzStart = isSqueeze and not isSqueeze[1]
ph = ta.pivothigh(high, pivLeft, pivRight)
pl = ta.pivotlow(low, pivLeft, pivRight)
var float lastPH_price = na
var float lastPH_q = na
var float lastPL_price = na
var float lastPL_q = na
bool bullDiv = false
bool bearDiv = false
if not na(pl) and showDiv
currentPL_price = low[pivRight]
currentPL_q = qNow[pivRight]
if not na(lastPL_price) and currentPL_price < lastPL_price and currentPL_q > lastPL_q
bullDiv := true
lastPL_price := currentPL_price
lastPL_q := currentPL_q
if not na(ph) and showDiv
currentPH_price = high[pivRight]
currentPH_q = qNow[pivRight]
if not na(lastPH_price) and currentPH_price > lastPH_price and currentPH_q < lastPH_q
bearDiv := true
lastPH_price := currentPH_price
lastPH_q := currentPH_q
breakUp = ta.crossover(close, q75s)
breakDn = ta.crossunder(close, q25s)
isEuphoria = close > q90s
isCapit = close < q10s
isHot = qNow >= 75.0
isCold = qNow <= 25.0
distQ75 = (q75s - close) / close * 100.0
fastAboveMain = cbFast > cb
confirmed = not waitForClose or barstate.isconfirmed
sigBreakUp = breakUp and confirmed
sigBreakDn = breakDn and confirmed
sigEuphoriaTap = isEuphoria and not isEuphoria[1] and confirmed
sigCapitTap = isCapit and not isCapit[1] and confirmed
sigSqzStart = sqzStart and confirmed
sigBullDiv = bullDiv and confirmed
sigBearDiv = bearDiv and confirmed
p90 = plot(showQ90 ? q90s : na, "Q90 Euphoria", color=#ff0000, linewidth=1)
p75 = plot(showQ75 ? q75s : na, "Q75 Overheated", color=#ca2727, linewidth=1)
p50 = plot(showQ50 ? q50s : na, "Q50 Cost Basis", color=#000000, linewidth=2)
p25 = plot(showQ25 ? q25s : na, "Q25 Discount", color=#2cb519, linewidth=1)
p10 = plot(showQ10 ? q10s : na, "Q10 Capitulation", color=#1fff00, linewidth=1)
fill(p90, p75, q90s, q75s, showShadeExt ? color.new(#ff0000, 85) : na, showShadeExt ? color.new(#ca2727, 85) : na, title="Premium Zone (Q75-Q90)")
fill(p25, p10, q25s, q10s, showShadeExt ? color.new(#2cb519, 85) : na, showShadeExt ? color.new(#1fff00, 85) : na, title="Discount Zone (Q10-Q25)")
fill(p25, p75, color=showShadeVal ? color.new(#ffca28, 88) : na, title="Value Zone (Q25-Q75)")
heatColor = close >= q90s ? color.new(#ff0000, 0) : close >= q50s ? color.new(#ca2727, 0) : close >= q10s ? color.new(#2cb519, 0) : color.new(#1fff00, 0)
plotcandle(showCandles ? open : na, showCandles ? high : na, showCandles ? low : na, showCandles ? close : na, title="Heat Candles", color=heatColor, wickcolor=heatColor, bordercolor=heatColor)
barcolor(showCandles ? heatColor : na, title="Bar Color")
pFastCB = plot(enableFast and showFastCB ? cbFast : na, "Fast Cost Basis", color=#ffffff, linewidth=1, style=plot.style_line)
bgCol = showBG and isEuphoria ? color.new(#ff0000, 88) : showBG and isHot ? color.new(#ca2727, 92) : showBG and isCapit ? color.new(#1fff00, 92) : showBG and isCold ? color.new(#2cb519, 92) : showSqzBG and isSqueeze ? color.new(#ffeb3b, 88) : na
bgcolor(bgCol, title="Background Highlights")
plotshape(showShapes and sigBreakUp, title="+Q75 Break", style=shape.triangleup, location=location.belowbar, color=color.new(#ca2727, 0), size=size.tiny)
plotshape(showShapes and sigEuphoriaTap, title="Euphoria Tap", style=shape.triangledown, location=location.abovebar, color=color.new(#000000, 0), size=size.tiny)
plotshape(showShapes and sigBreakDn, title="Q25 Breakdown", style=shape.triangledown, location=location.abovebar, color=color.new(#2cb519, 0), size=size.tiny)
plotshape(sigBullDiv, title="Bullish Quantile Divergence", style=shape.circle, location=location.belowbar, color=color.new(#1fff00, 0), size=size.tiny, offset=-pivRight)
plotshape(sigBearDiv, title="Bearish Quantile Divergence", style=shape.circle, location=location.abovebar, color=color.new(#ca2727, 0), size=size.tiny, offset=-pivRight)
if showBreakoutLabels and sigBreakUp
label.new(bar_index, low, "+Q75\nBREAK", xloc=xloc.bar_index, yloc=yloc.belowbar, style=label.style_label_up, color=color.new(#ff0000, 0), textcolor=color.white, size=size.tiny)
if showBreakoutLabels and sigEuphoriaTap
label.new(bar_index, high, "EUPHORIA", xloc=xloc.bar_index, yloc=yloc.abovebar, style=label.style_label_down, color=color.new(#ff0000, 0), textcolor=color.white, size=size.tiny)
if showDivLabels and sigBullDiv
label.new(bar_index - pivRight, low[pivRight], "BULL DIV", xloc=xloc.bar_index, yloc=yloc.belowbar, style=label.style_label_up, color=color.new(#1fff00, 0), textcolor=color.black, size=size.tiny)
if showDivLabels and sigBearDiv
label.new(bar_index - pivRight, high[pivRight], "BEAR DIV", xloc=xloc.bar_index, yloc=yloc.abovebar, style=label.style_label_down, color=color.new(#ca2727, 0), textcolor=color.white, size=size.tiny)
alertcondition(sigBreakUp, title="Price Crossed Above Q75", message="BTC-CQB: price crossed above the Q75 overheated band.")
alertcondition(sigBreakDn, title="Price Crossed Below Q25", message="BTC-CQB: price crossed below the Q25 discount band.")
alertcondition(sigEuphoriaTap, title="Euphoria Zone Tapped", message="BTC-CQB: price tapped into the Q90 euphoria zone.")
alertcondition(sigCapitTap, title="Capitulation Zone Tapped", message="BTC-CQB: price tapped into the Q10 capitulation zone.")
alertcondition(sigSqzStart, title="Bandwidth Squeeze Started", message="BTC-CQB: quantile bandwidth compressed to a new local minimum (squeeze).")
alertcondition(sigBullDiv, title="Bullish Quantile Divergence", message="BTC-CQB: bullish divergence between price and the band-position score.")
alertcondition(sigBearDiv, title="Bearish Quantile Divergence", message="BTC-CQB: bearish divergence between price and the band-position score.")
var table dash = table.new(f_tablePos(tablePosOpt), 2, 12, bgcolor=color.new(#000000, 0), frame_width=1, frame_color=color.new(#ffffff, 80), border_width=1, border_color=color.new(#ffffff, 88))
regimeTxt = qNow >= 90 ? "EUPHORIA" : qNow >= 75 ? "+Q75 OVERHEATED" : qNow >= 55 ? "BULLISH" : qNow >= 40 ? "NEUTRAL" : qNow >= 25 ? "WEAK" : "CAPITULATION"
regimeBg = qNow >= 90 ? color.new(#ff0000, 20) : qNow >= 75 ? color.new(#ca2727, 20) : qNow <= 10 ? color.new(#1fff00, 20) : qNow <= 25 ? color.new(#2cb519, 20) : color.new(#616161, 20)
var string lastDivTxt = "NONE YET"
var color lastDivCol = color.gray
var int lastDivBar = na
if sigBullDiv
lastDivTxt := "BULLISH"
lastDivCol := color.new(#1fff00, 0)
lastDivBar := bar_index
if sigBearDiv
lastDivTxt := "BEARISH"
lastDivCol := color.new(#ca2727, 0)
lastDivBar := bar_index
divDisplay = not na(lastDivBar) ? lastDivTxt + " (" + str.tostring(bar_index - lastDivBar) + " bars ago)" : lastDivTxt
tSize = f_tableSize(tableSizeOpt)
if barstate.islast and showTable
table.cell(dash, 0, 0, "COST-BASIS QUANTILE", text_color=color.new(#ffffff, 20), text_size=tSize)
table.cell(dash, 1, 0, str.tostring(qNow, "#.#"), text_color=color.white, bgcolor=regimeBg, text_size=tSize)
table.cell(dash, 0, 1, "Regime", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 1, regimeTxt, text_color=color.white, bgcolor=regimeBg, text_size=tSize)
table.cell(dash, 0, 2, "Price", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 2, str.tostring(close, format.mintick), text_color=color.white, text_size=tSize)
table.cell(dash, 0, 3, "Cost Basis (" + cbType + ")", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 3, str.tostring(q50s, format.mintick), text_color=color.white, text_size=tSize)
table.cell(dash, 0, 4, "Fast Cost Basis", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 4, str.tostring(cbFast, format.mintick), text_color=fastAboveMain ? color.white : color.new(#ca2727, 0), text_size=tSize)
table.cell(dash, 0, 5, "Bandwidth (Q90-Q10)", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 5, str.tostring(qBW, "#.#") + "%" + (isSqueeze ? " [SQUEEZE]" : ""), text_color=isSqueeze ? color.yellow : color.white, text_size=tSize)
table.cell(dash, 0, 6, "Divergence", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 6, divDisplay, text_color=lastDivCol, text_size=tSize)
table.cell(dash, 0, 7, "Q75 Trigger", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 7, str.tostring(q75s, format.mintick), text_color=color.new(#ca2727, 0), text_size=tSize)
table.cell(dash, 0, 8, "To +Q75", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 8, (distQ75 > 0 ? "+" : "") + str.tostring(distQ75, "#.#") + "%", text_color=color.white, text_size=tSize)
table.cell(dash, 0, 9, "Q90 Euphoria", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 9, str.tostring(q90s, format.mintick), text_color=color.new(#ff0000, 0), text_size=tSize)
table.cell(dash, 0, 10, "History", text_color=color.new(#ffffff, 40), text_size=tSize)
table.cell(dash, 1, 10, str.tostring(histCount) + " / " + str.tostring(effQLen) + (histReady ? " READY" : " WARMING UP"), text_color=histReady ? color.white : color.yellow, text_size=tSize)
table.cell(dash, 0, 11, "POTENTIAL CYCLE TARGET", text_color=color.new(#ffffff, 20), text_size=tSize)
table.cell(dash, 1, 11, str.tostring(q75s, format.mintick) + " - " + str.tostring(q90s, format.mintick), text_color=color.black, bgcolor=color.new(#2dfd03, 0), text_size=tSize)