Perfected FlowScript
Bitcoin Sentiment Index - Tradingriot
Bitcoin Sentiment Index [Tradingriot] — Perfected is indexed as 021_bitcoin_sentiment_index_tradingriot.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.
This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.
Dialect
flowscript-v2
Compatibility
flowscript-v2-needs-transpile
Position
offchart
Axis
true
Size
18.9 KB
Lines
561
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Fear
line 466:9
Trigger
(showShapes) && (enterExtremeFear)
Value
composite
Deps
enterExtremeFear:var, showShapes:input
Exit Fear
line 476:9
Trigger
(showShapes) && (exitExtremeFear)
Value
composite
Deps
exitExtremeFear:var, showShapes:input
Extreme Greed
line 486:9
Trigger
(showShapes) && (enterExtremeGreed)
Value
composite
Deps
enterExtremeGreed:var, showShapes:input
Exit Greed
line 496:9
Trigger
(showShapes) && (exitExtremeGreed)
Value
composite
Deps
exitExtremeGreed:var, showShapes:input
Fear Entry
line 506:9
Trigger
(showShapes) && (enterFear)
Value
composite
Deps
enterFear:var, showShapes:input
Greed Entry
line 516:9
Trigger
(showShapes) && (enterGreed)
Value
composite
Deps
enterGreed:var, showShapes:input
021_bitcoin_sentiment_index_tradingriot.flowscript
source path: kscripts/perfected/021_bitcoin_sentiment_index_tradingriot.flowscript · sha256:1a78be58cce7c86c42dcd7c685ea9fff5d78107bc3dd98f8d3f77c3b076e5a08
//@version=2
// ============================================================================
// Bitcoin Sentiment Index [Tradingriot] — Perfected Edition
// Author: abetrade (@abetrade) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, #skew, #risk, #reversal, #term, #structure, #sentiment, #zscore
//
// Production-grade composite sentiment index combining five positioning metrics:
// risk reversal skew (approximated from return asymmetry), funding rates,
// open interest delta, implied volatility (approximated from ATR), and price
// momentum. Each component is z-score normalized over a rolling window and
// combined into a weighted composite with regime detection, color coding,
// extreme markers, and full toggles for individual components.
//
// Research papers underpinning this design:
// 1. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
// Stock Returns": seminal paper on composite sentiment construction from
// multiple proxies via PCA. Underpins the weighted multi-component
// architecture.
// 2. Carr & Wu (2009), "Variance Risk Premia": VRP measurement captures
// the term-structure component. IV extremes flag crowded positioning.
// 3. Carr & Wu (2007), "Stochastic Skew in Currency Options": risk reversal
// = IV(25Δ Call) - IV(25Δ Put). Stochastic skew models validate dynamic
// skew interpretation for sentiment extremes.
// 4. He & Manela (2022), "Fundamentals of Perpetual Futures": funding rate
// deviation as a sentiment indicator; momentum-funding relationship.
// 5. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
// Basis and Open Interest": OI levels predict future volatility;
// unexpected OI changes carry more information than levels.
// 6. Rakovská (2021), "Composite Survey Sentiment as a Predictor": composite
// indices outperform single indicators; macro-orthogonalization.
// 7. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
// z-score normalization framework; entry thresholds at ±1σ, ±2σ.
// ============================================================================
define(
title="Bitcoin Sentiment Index [Tradingriot] — Perfected",
position="offchart",
axis=true
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- Z-Score Settings ---
var lookback = input(
name="lookback",
type="number",
defaultValue=30,
label="Z-Score Window",
constraints={min: 10, max: 200, step: 1},
group="Z-Score Settings"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="Composite Smoothing",
constraints={min: 1, max: 20, step: 1},
group="Z-Score Settings"
)
// --- Component Weights ---
var skewWeight = input(
name="skewWeight",
type="number",
defaultValue=0.20,
label="Skew Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Component Weights"
)
var fundingWeight = input(
name="fundingWeight",
type="number",
defaultValue=0.25,
label="Funding Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Component Weights"
)
var oiWeight = input(
name="oiWeight",
type="number",
defaultValue=0.20,
label="OI Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Component Weights"
)
var ivWeight = input(
name="ivWeight",
type="number",
defaultValue=0.20,
label="IV Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Component Weights"
)
var retWeight = input(
name="retWeight",
type="number",
defaultValue=0.15,
label="Return Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Component Weights"
)
// --- Regime Thresholds ---
var extremeFearThresh = input(
name="extremeFearThresh",
type="number",
defaultValue=-2.5,
label="Extreme Fear Threshold",
constraints={min: -4.0, max: -1.0, step: 0.1},
group="Regime Thresholds"
)
var fearThresh = input(
name="fearThresh",
type="number",
defaultValue=-1.5,
label="Fear Threshold",
constraints={min: -3.0, max: -0.5, step: 0.1},
group="Regime Thresholds"
)
var greedThresh = input(
name="greedThresh",
type="number",
defaultValue=1.5,
label="Greed Threshold",
constraints={min: 0.5, max: 3.0, step: 0.1},
group="Regime Thresholds"
)
var extremeGreedThresh = input(
name="extremeGreedThresh",
type="number",
defaultValue=2.5,
label="Extreme Greed Threshold",
constraints={min: 1.0, max: 4.0, step: 0.1},
group="Regime Thresholds"
)
// --- Display ---
var showSkew = input(
name="showSkew",
type="boolean",
defaultValue=true,
label="Show Skew Component",
group="Display"
)
var showFunding = input(
name="showFunding",
type="boolean",
defaultValue=true,
label="Show Funding Component",
group="Display"
)
var showOI = input(
name="showOI",
type="boolean",
defaultValue=true,
label="Show OI Component",
group="Display"
)
var showIV = input(
name="showIV",
type="boolean",
defaultValue=true,
label="Show IV Component",
group="Display"
)
var showReturn = input(
name="showReturn",
type="boolean",
defaultValue=true,
label="Show Return Component",
group="Display"
)
var showComposite = input(
name="showComposite",
type="boolean",
defaultValue=true,
label="Show Composite Index",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Extreme Markers",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Regime Fill",
group="Display"
)
// --- Colors ---
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bullish/Extreme Fear Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bearish/Extreme Greed Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
var fearColor = input(
name="fearColor",
type="color",
defaultValue="#42a5f5",
label="Fear Color",
group="Colors"
)
var greedColor = input(
name="greedColor",
type="color",
defaultValue="#ffa726",
label="Greed Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries vol = bars.volume
timeseries funding = source("funding_rate", currentSymbol, currentExchange)
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0])) {
return
}
// ----------------------------------------------------------------------------
// Static State Tracking (session-level persistence)
// ----------------------------------------------------------------------------
static lastRegime = 0 // 0=neutral, 1=extremeFear, 2=fear, 3=greed, 4=extremeGreed
static regimeChangeCount = 0
static extremeEventCount = 0
static barCount = 0
// -----------------------------------------------------------------------------
// 3. COMPONENT 1 — SKEW (approximated from return asymmetry)
// -----------------------------------------------------------------------------
// Since 25-delta risk reversal skew is not directly accessible in this DSL,
// we approximate it from the rolling skewness of returns (asymmetric tail risk).
// Positive skew = left tail heavier (fear); negative skew = right tail heavier (greed).
timeseries ret = (px - px[1]) / math.max(0.0001, px[1])
// Rolling third moment (skewness numerator)
timeseries retMean = sma(ret, lookback)
timeseries retStd = stdev(ret, lookback)
timeseries retDev = ret - retMean
timeseries retCubed = retDev * retDev * retDev
timeseries retCubedMean = sma(retCubed, lookback)
// Skewness approximation: E[(x-μ)³] / σ³; guard against div by zero
timeseries skewProxy = retStd > 0 ? retCubedMean / (retStd * retStd * retStd) : 0
// Z-score of skew proxy
timeseries skewMean = sma(skewProxy, lookback)
timeseries skewStd = stdev(skewProxy, lookback)
timeseries skewZ = skewStd > 0 ? (skewProxy - skewMean) / skewStd : 0
// -----------------------------------------------------------------------------
// 4. COMPONENT 2 — FUNDING RATE
// -----------------------------------------------------------------------------
timeseries fundingSeries = isnum(funding.value) ? funding.value : 0
timeseries fundingMean = sma(fundingSeries, lookback)
timeseries fundingStd = stdev(fundingSeries, lookback)
timeseries fundingZ = fundingStd > 0 ? (fundingSeries - fundingMean) / fundingStd : 0
// -----------------------------------------------------------------------------
// 5. COMPONENT 3 — OPEN INTEREST DELTA
// -----------------------------------------------------------------------------
timeseries oiChange = oi.close - oi.close[1]
timeseries oiMean = sma(oiChange, lookback)
timeseries oiStd = stdev(oiChange, lookback)
timeseries oiZ = oiStd > 0 ? (oiChange - oiMean) / oiStd : 0
// -----------------------------------------------------------------------------
// 6. COMPONENT 4 — IMPLIED VOLATILITY (approximated from ATR)
// -----------------------------------------------------------------------------
// IV proxy = annualized ATR volatility: (ATR / price) × sqrt(252) × 100
timeseries prevClose = isnan(px[1]) ? px : px[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, 14)
timeseries ivProxy = px > 0 ? (atr / px) * math.sqrt(252) * 100 : 0
timeseries ivMean = sma(ivProxy, lookback)
timeseries ivStd = stdev(ivProxy, lookback)
timeseries ivZ = ivStd > 0 ? (ivProxy - ivMean) / ivStd : 0
// -----------------------------------------------------------------------------
// 7. COMPONENT 5 — PRICE MOMENTUM / RETURN
// -----------------------------------------------------------------------------
// Returns already computed above
timeseries retMean2 = sma(ret, lookback)
timeseries retStd2 = stdev(ret, lookback)
timeseries retZ = retStd2 > 0 ? (ret - retMean2) / retStd2 : 0
// -----------------------------------------------------------------------------
// 8. WEIGHTED COMPOSITE SENTIMENT INDEX
// -----------------------------------------------------------------------------
// Normalize weights so they sum to 1.0
timeseries totalWeight = skewWeight + fundingWeight + oiWeight + ivWeight + retWeight
timeseries wSkew = totalWeight > 0 ? skewWeight / totalWeight : 0.2
timeseries wFunding = totalWeight > 0 ? fundingWeight / totalWeight : 0.2
timeseries wOI = totalWeight > 0 ? oiWeight / totalWeight : 0.2
timeseries wIV = totalWeight > 0 ? ivWeight / totalWeight : 0.2
timeseries wRet = totalWeight > 0 ? retWeight / totalWeight : 0.2
// Raw composite (unsmoothed)
timeseries rawComposite = wSkew * skewZ + wFunding * fundingZ + wOI * oiZ + wIV * ivZ + wRet * retZ
// Smoothed composite
timeseries composite = ema(source=rawComposite, period=smoothLen)
// -----------------------------------------------------------------------------
// 9. REGIME DETECTION
// -----------------------------------------------------------------------------
// Five-tier regime classification: extreme fear, fear, neutral, greed, extreme greed
var regimeExtremeFear = composite < extremeFearThresh
var regimeFear = composite < fearThresh && composite >= extremeFearThresh
var regimeNeutral = composite >= fearThresh && composite <= greedThresh
var regimeGreed = composite > greedThresh && composite <= extremeGreedThresh
var regimeExtremeGreed = composite > extremeGreedThresh
// Regime color for composite line
var regimeColor = regimeExtremeFear ? bullColor : (regimeFear ? fearColor : (regimeGreed ? greedColor : (regimeExtremeGreed ? bearColor : neutralColor)))
// -----------------------------------------------------------------------------
// 10. EXTREME EVENT FLAGS
// -----------------------------------------------------------------------------
// Extreme events for shape markers: entering/leaving extreme zones
var enterExtremeFear = composite < extremeFearThresh && composite[1] >= extremeFearThresh
var exitExtremeFear = composite >= extremeFearThresh && composite[1] < extremeFearThresh
var enterExtremeGreed = composite > extremeGreedThresh && composite[1] <= extremeGreedThresh
var exitExtremeGreed = composite <= extremeGreedThresh && composite[1] > extremeGreedThresh
var enterFear = composite < fearThresh && composite[1] >= fearThresh
var exitFear = composite >= fearThresh && composite[1] < fearThresh
var enterGreed = composite > greedThresh && composite[1] <= greedThresh
var exitGreed = composite <= greedThresh && composite[1] > greedThresh
// Update static state tracking
var currentRegime = regimeExtremeFear ? 1 : (regimeFear ? 2 : (regimeGreed ? 3 : (regimeExtremeGreed ? 4 : 0)))
if (barCount > 0 && currentRegime != lastRegime) {
regimeChangeCount = regimeChangeCount + 1
lastRegime = currentRegime
}
if (barCount == 0) {
lastRegime = currentRegime
}
if (enterExtremeFear || enterExtremeGreed) {
extremeEventCount = extremeEventCount + 1
}
barCount = barCount + 1
// -----------------------------------------------------------------------------
// 11. PLOTTING
// -----------------------------------------------------------------------------
// --- Reference Lines ---
hline(value=0, color="#ffffff40", width=1)
hline(value=extremeGreedThresh, color=transparency(bearColor, 70), width=1)
hline(value=greedThresh, color=transparency(greedColor, 70), width=1)
hline(value=fearThresh, color=transparency(fearColor, 70), width=1)
hline(value=extremeFearThresh, color=transparency(bullColor, 70), width=1)
// --- Composite Line (regime-colored) ---
if (showComposite) {
plotLine(
value=composite,
width=2,
colors=[regimeColor],
label=["Composite Sentiment"],
desc=["Weighted composite sentiment index (smoothed)"]
)
}
// --- Regime Fill (composite vs zero) ---
if (showFill) {
var fillBull = composite >= 0
plotLine(
value=[composite, 0],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["Composite", "Zero"],
desc=["Fill between composite sentiment and zero line", "Regime-colored fill"]
)
}
// --- Individual Component Lines ---
if (showSkew) {
plotLine(
value=skewZ,
width=1,
colors=[transparency("#ab47bc", 50)],
label=["Skew Z"],
desc=["Return skewness z-score (asymmetric tail risk proxy)"]
)
}
if (showFunding) {
plotLine(
value=fundingZ,
width=1,
colors=[transparency("#42a5f5", 50)],
label=["Funding Z"],
desc=["Funding rate z-score (perpetual futures sentiment)"]
)
}
if (showOI) {
plotLine(
value=oiZ,
width=1,
colors=[transparency("#66bb6a", 50)],
label=["OI Z"],
desc=["Open interest delta z-score (positioning changes)"]
)
}
if (showIV) {
plotLine(
value=ivZ,
width=1,
colors=[transparency("#ffa726", 50)],
label=["IV Z"],
desc=["Implied volatility z-score (ATR-based annualized vol proxy)"]
)
}
if (showReturn) {
plotLine(
value=retZ,
width=1,
colors=[transparency("#ec407a", 50)],
label=["Return Z"],
desc=["Bar return z-score (price momentum)"]
)
}
// --- Extreme Event Shape Markers ---
if (showShapes) {
if (enterExtremeFear) {
plotShape(
value=composite,
shape="triangleup",
colorIndex=bullColor,
width=3,
label=["Extreme Fear"],
desc=["Entered extreme fear zone: potential bullish reversal (contrarian)"]
)
}
if (exitExtremeFear) {
plotShape(
value=composite,
shape="arrowup",
colorIndex=fearColor,
width=2,
label=["Exit Fear"],
desc=["Exited extreme fear zone: sentiment improving"]
)
}
if (enterExtremeGreed) {
plotShape(
value=composite,
shape="triangledown",
colorIndex=bearColor,
width=3,
label=["Extreme Greed"],
desc=["Entered extreme greed zone: potential bearish reversal (contrarian)"]
)
}
if (exitExtremeGreed) {
plotShape(
value=composite,
shape="arrowdown",
colorIndex=greedColor,
width=2,
label=["Exit Greed"],
desc=["Exited extreme greed zone: sentiment cooling"]
)
}
if (enterFear) {
plotShape(
value=composite,
shape="circle",
colorIndex=fearColor,
width=2,
label=["Fear Entry"],
desc=["Entered fear zone"]
)
}
if (enterGreed) {
plotShape(
value=composite,
shape="circle",
colorIndex=greedColor,
width=2,
label=["Greed Entry"],
desc=["Entered greed zone"]
)
}
}
// -----------------------------------------------------------------------------
// 12. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeExtremeFear ? "EXTREME FEAR" : (regimeFear ? "FEAR" : (regimeGreed ? "GREED" : (regimeExtremeGreed ? "EXTREME GREED" : "NEUTRAL")))
var regimeTextColor = regimeExtremeFear ? bullColor : (regimeFear ? fearColor : (regimeGreed ? greedColor : (regimeExtremeGreed ? bearColor : neutralColor)))
plotTable(
data=[
["Sentiment Index — Perfected", regimeText],
["Composite", composite[0]],
["Skew Z", skewZ[0]],
["Funding Z", fundingZ[0]],
["OI Z", oiZ[0]],
["IV Z", ivZ[0]],
["Return Z", retZ[0]],
["Raw Composite", rawComposite[0]],
["Regime Changes", regimeChangeCount],
["Extreme Events", extremeEventCount],
["Bars Processed", barCount]
],
position="top_right",
headerRow=true,
headerColumn=true,
textColor="#e2e8f0",
headerTextColor="#ffffff",
backgroundColor=transparency("#0f172a", 40),
headerBackgroundColor=transparency("#1e293b", 40),
borderColor=transparency("#334155", 40),
borderWidth=1,
fontSize=10,
cellPadding=4
)
}