← К каталогу
Исходный код · ID 4830

BTC Cost Basis Quantile Bands

indicator btc cost basis quantile bands for tradingview.pine
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

BTC Cost Basis Quantile Bands (BTC-CQB) — индикатор TradingView на Pine Script v6, предназначенный для анализа биткоинских пар. Он строит скользящие процентильные полосы (Q10–Q90) вокруг рассчитанной стоимостной базы, отражающей статистическое распределение отклонения цены от среднего значения накопления. Индикатор заблокирован исключительно на BTC-пары и требует таймфрейм не ниже 4 часов, иначе выдаёт ошибку расчёта.

Индикатор поддерживает три типа стоимостной базы (SMA, EMA, VWMA), обнаружение сжатия полос (squeeze), выявление дивергенций на основе пивотов, раскраску свечей по зонам оценки и отображение информационной таблицы-дашборда на графике. Дискретные сигналы (пробитие полос, зондирование зон, дивергенции) могут сопровождаться оповещениями TradingView.

Это инструмент визуального анализа и отображения, а не торговый советник: он не моделирует сделки и не выполняет автоматических ордеров. Все данные рассчитываются на основе ценового ряда и объёма, без привлечения внешних источников.

Настройки программы

НастройкаОписание
minTF Минимально допустимый таймфрейм в минутах. Ниже этого значения выборка слишком шумна, и скрипт отказывается от расчёта, выдавая ошибку. По умолчанию 240 минут (4 часа).
src Ценовой ряд, на котором построен весь движок стоимостной базы и квантилей. По умолчанию — Close (стандартный академический выбор). Переключение на hl2, hlc3 или пользовательский ряд смещает все полосы.
cbType Тип скользящей средней, используемой как статистический «центр тяжести» (прокси стоимостной базы), вокруг которого строятся все процентильные полосы: SMA — равные веса, EMA — экспоненциальное взвешивание, VWMA — взвешивание по объёму.
cbLen Количество баров для расчёта основной стоимостной базы. На дневном графике приблизительно соответствует этому количеству календарных дней (155 ≈ 5 месяцев). На других допустимых таймфреймах это соответствующее количество баров.
enableFast Включает отображение дополнительной быстрой линии стоимостной базы с более коротким периодом. Сравнение быстрой и основной линий даёт представление о краткосрочной и долгосрочной стоимости позиции.
fastLen Количество баров для расчёта быстрой линии стоимостной базы. Подчиняется тому же правилу масштабирования баров/календарных дней, что и основной период.
qLen Размер скользящего выбора (в барах) для расчёта статистического распределения отклонения цены от стоимостной базы, из которого выводятся процентильные полосы Q10–Q90. Большее окно даёт более устойчивое, но более медленное распределение.
smoothLen Применяет лёгкое сглаживание EMA к итоговым процентильным полосам для уменьшения ступенчатости. Значение 1 означает отсутствие сглаживания (чистой математический вывод). Увеличение значения снижает отзывчивость в пользу плавности.
autoScaleDays При включении основные и быстрые параметры стоимостной базы, а также окно квантилей автоматически масштабируются в календарные дни в зависимости от таймфрейма графика. По умолчанию отключено для сохранения поведения, привязанного к количеству баров.
sqzLookback Количество баров в скользящем оконном периоде для обнаружения сжатия полос. Текущая ширина полос сравнивается с минимальной шириной за этот период; при приближении к минимуму фиксируется сжатие.
sqzThresholdPct Насколько близко (в процентах) текущая ширина полос должна быть к минимальной ширине за период обнаружения, чтобы классифицироваться как сжатие. По умолчанию 5%. Уменьшение значения выявляет только наиболее экстремальные сжатия.
showSqzBG Рисует мягкую жёлтую заливку за барами, в которых в данный момент активно сжатие полос, облегчая визуальное обнаружение периодов сжатой волатильности.
useVolFloor Предотвращает чрезмерное сжатие экстремальных полос Q10/Q90 в периоды очень низкой волатильности путём установления минимальной полу-ширины в ценовых единицах на основе ATR.
atrFloorLen Длина периода усреднённого истинного диапазона (ATR), используемого для расчёта минимальной ширины экстремальных полос. Классическая длина ATR — 14. Влияет только на ограничение сжатия полос при низкой волатильности.
atrFloorMult Множитель ATR, определяющий минимальное расстояние полос Q90/Q10 от Q50 в ценовых единицах. Увеличение расширяет экстремальные полосы в периоды спокойного рынка; уменьшение — позволяет процентильной статистике доминировать. Не действует при отключённом ограничении волатильности.
showDiv Включает детектор дивергенций на основе пивотов, сравнивающий ценовые экстремумы с показателем позиции цены в полосе (0–100). Обнаруживает бычьи и медвежьи расхождения классического типа.
pivLeft Количество баров слева от кандидата на пивот, в которых должен быть более низкий минимум или более высокий максимум для подтверждения пивота. Большее значение требует более значимого разворота.
pivRight Количество баров справа от кандидата на пивот, необходимых для его подтверждения. Также определяет задержку подтверждения дивергенции, что делает её нерепейнтинговой.
waitForClose Определяет, должны ли дискретные сигналы (пробития, касания зон, начало сжатия, маркеры дивергенций) появляться только после полного закрытия бара, или могут срабатывать внутри бара. По умолчанию включено для нерепейтингового поведения.
showQ90 Показывает или скрывает 90-ю процентильную полосу — уровень, выше которого цена торговалась лишь 10% времени. На дашборде обозначается как «EUPHORIA».
showQ75 Показывает или скрывает 75-ю процентильную полосу — уровень, выше которого цена торговалась лишь 25% времени. Используется как уровень перегрева и триггер маркера пробития.
showQ50 Показывает или скрывает медианную (50-ю процентильную) полосу, которая совпадает с выбранным типом стоимостной базы (SMA/EMA/VWMA) — центральную линию, вокруг которой рассчитываются все остальные полосы.
showQ25 Показывает или скрывает 25-ю процентильную полосу — уровень, ниже которого цена торговалась лишь 25% времени. Используется как уровень пробития вниз.
showQ10 Показывает или скрывает 10-ю процентильную полосу — уровень, ниже которого цена торговалась лишь 10% времени за период наблюдения. На дашборде обозначается как «CAPITULATION».
showFastCB Отображает линию быстрой стоимостной базы (белая линия), определённую в настройках движка стоимостной базы, для визуального сравнения краткосрочной и долгосрочной средней цены накопления.
showShadeExt Заливает область между Q75–Q90 (зона премиума/перегрева) и между Q10–Q25 (зона дисконта) лёгким цветовым градиентом для визуального выделения этих регионов.
showShadeVal Заливает область между Q25 и Q75 — статистическую «справедливую зону», где цена исторически находилась 50% времени — мягким подсветочным цветом.
showCandles Перекрашивает тело, фитиль и границу каждой свечи в зависимости от того, в какой процентильной зоне находится закрытие (выше Q90, между Q50–Q90, между Q10–Q50 или ниже Q10), превращая график в карту оценки.
showBG Добавляет мягкое полноширинное фоновое затемнение, когда цена находится в зонах эйфории, перегрева, дисконта или капитуляции, усиливая визуальное восприятие тепловой карты.
showShapes Отображает треугольные маркеры для трёх основных дискретных событий: пересечение вверх Q75, касание зоны эйфории Q90 и пересечение вниз Q25. Подчиняются настройке ожидания закрытия бара.
showBreakoutLabels Отображает текстовые метки (например, «+Q75 BREAK», «EUPHORIA») при событиях пробития и зондирования, дополнительно или вместо маленьких маркеров. Подчиняется настройке ожидания закрытия бара.
showDivLabels Отображает текстовые метки «BULL DIV» / «BEAR DIV» в точках подтверждения пивотов, дополнительно или вместо маленьких круговых маркеров.
showTable Включает или отключает графиковую таблицу-дашборд, отображающую текущий процентильный балл, классификацию режима, цену, значения стоимостной базы, статус полосы/сжатия, состояние дивергенции и расстояние до целевого уровня.
tablePosOpt Выбирает угол графика, к которому привязана таблица-дашборд: верхний правый, верхний левый, нижний правый или нижний левый.
tableSizeOpt Управляет размером шрифта текста в таблице-дашборде, независимо от масштаба графика: крошечный, маленький, нормальный или большой.

Поиск по коду файла

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 addi

Показано первые 50% кода (символов: 24469)