Perfected FlowScript
Premium & Discount
Premium & Discount V2 is indexed as 233_premium_discount.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
17.3 KB
Lines
386
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Premium Zone
line 311:9
Trigger
(showShapes) && (crossPremium)
Value
zScore
Deps
crossPremium:var, showShapes:input
Discount Zone
line 321:9
Trigger
(showShapes) && (crossDiscount)
Value
zScore
Deps
crossDiscount:var, showShapes:input
Extreme Premium
line 331:9
Trigger
(showShapes) && (extremePrm)
Value
zScore
Deps
extremePrm:var, showShapes:input
Extreme Discount
line 341:9
Trigger
(showShapes) && (extremeDsc)
Value
zScore
Deps
extremeDsc:var, showShapes:input
233_premium_discount.flowscript
source path: kscripts/perfected/233_premium_discount.flowscript · sha256:14e0a909d2a29c6f59f06e77a20678cae782aa783b09b55d4d0b1e73408fe48d
//@version=2
// ============================================================================
// Premium & Discount V2 — Production-Quality Fair-Value Deviation Oscillator
// Author: Н (@Никита Старостенко) | Perfected by: kScript Perfection Engineer
// Tags: FAIRVALUE, #vwap, #premium, #discount, #zscore, #regime, #auction
//
// Dynamically identifies Premium (sell) and Discount (buy) zones relative to
// VWAP fair value with z-score normalization, regime detection, and
// comprehensive visualization. Based on auction market theory (Steidlmayer 2003)
// and VWAP deviation z-score methodology (NinjaTrader 2026).
//
// FORMULA FOUNDATION:
// 1. VWAP: Σ(Pᵢ × Vᵢ) / Σ(Vᵢ) per Berkowitz, Logue & Noser (1988) — the
// institutional gold-standard benchmark for fair value assessment.
// 2. Premium/Discount: (Close − VWAP) / VWAP × 100 — percent deviation from
// fair value; positive = premium, negative = discount.
// 3. Z-Score Normalization: (deviation − rollingMean) / rollingStd per
// Zhao & Palomar (2018) and NinjaTrader (2026) VWAP z-score strategy.
// 4. Regime Segmentation: Premium (z > 1), Equilibrium (−1 ≤ z ≤ 1),
// Discount (z < −1) per Steidlmayer Market Profile (2003) Value Area logic.
// 5. ATR-Based Zone Width: dynamic zone boundaries adjust to volatility per
// CMT Association / CFA Institute (2016) VBSR framework.
//
// RESEARCH BASIS:
// • Berkowitz, Logue & Noser (1988), "The Total Cost of Transactions on the
// NYSE" — J. Finance 43(1). Introduced VWAP as the dominant institutional
// execution benchmark. VWAP represents fair value; deviations flag mispricing.
// • Steidlmayer & Hawkins (2003), "Steidlmayer on Markets" — Wiley. Market
// Profile: Value Area (~70% of trading), Point of Control (fair value), and
// the auction process. Premium = above Value Area, Discount = below.
// • Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape" — NBER WP 11439.
// Institutional order flow leaves detectable footprints; VWAP deviations
// with volume delta confirm accumulation/distribution.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint" —
// IEEE TSP. Z-score normalization for standardized threshold detection.
// • NinjaTrader (2026), "Z-Score Futures Trading Strategy". VWAP z-scores
// reaching ±2 signal statistical rarity and potential mean reversion.
// • CMT Association / CFA Institute (2016), "Technical Analysis: Modern
// Perspectives". VBSR uses volatility-based offsets for adaptive S/R zones.
// ============================================================================
define(
title="Premium & Discount V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- VWAP & Zone Configuration ---
var vwapLookback = input(name="vwapLookback", type="number", defaultValue=50, label="VWAP Lookback (bars)", constraints={min: 10, max: 500, step: 5}, group="VWAP Zones")
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length", constraints={min: 5, max: 50, step: 1}, group="VWAP Zones")
var atrMult = input(name="atrMult", type="number", defaultValue=0.5, label="ATR Zone Multiplier", constraints={min: 0.1, max: 3.0, step: 0.1}, group="VWAP Zones")
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show Premium/Discount Zones", group="VWAP Zones")
// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="EMA Smoothing Length", constraints={min: 1, max: 20, step: 1}, group="Smoothing")
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Use Z-Score Normalization", group="Smoothing")
var zLookback = input(name="zLookback", type="number", defaultValue=20, label="Z-Score Lookback", constraints={min: 10, max: 100, step: 1}, group="Smoothing")
// --- Thresholds & Regime ---
var premiumThresh = input(name="premiumThresh", type="number", defaultValue=1.0, label="Premium Z-Score Threshold", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")
var discountThresh = input(name="discountThresh", type="number", defaultValue=-1.0, label="Discount Z-Score Threshold", constraints={min: -3.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremePremium = input(name="extremePremium", type="number", defaultValue=2.0, label="Extreme Premium Z-Score", constraints={min: 1.5, max: 4.0, step: 0.1}, group="Thresholds")
// --- Display ---
var showRaw = input(name="showRaw", type="boolean", defaultValue=true, label="Show Raw Deviation Histogram", group="Display")
var showZScoreLine = input(name="showZScoreLine", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showSignalFill = input(name="showSignalFill", type="boolean", defaultValue=true, label="Show Signal Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Volume Delta %", group="Display")
// --- Colors ---
var premiumColor = input(name="premiumColor", type="color", defaultValue="#ef5350", label="Premium Color", group="Colors")
var discountColor = input(name="discountColor", type="color", defaultValue="#26a69a", label="Discount Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var eqColor = input(name="eqColor", type="color", defaultValue="#ffeb3b", label="Equilibrium Color", group="Colors")
var extremePremiumColor = input(name="extremePremiumColor", type="color", defaultValue="#ff1744", label="Extreme Premium Color", group="Colors")
var extremeDiscountColor = input(name="extremeDiscountColor", type="color", defaultValue="#00e676", label="Extreme Discount Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries high = ohlcvTS.high
timeseries low = ohlcvTS.low
timeseries close = ohlcvTS.close
timeseries volume = ohlcvTS.volume
timeseries buySell = buy_sell_volume(symbol=currentSymbol, exchange=currentExchange)
// NaN guard — prevent execution before data is loaded
if (isnan(close[0]) || isnan(volume[0])) {
return
}
// ------------------------------------------------------------------------------
// VWAP & ATR Computation (Berkowitz et al. 1988; Steidlmayer 2003)
// ------------------------------------------------------------------------------
// CRITICAL BUG FIX: Original used ema(source=close, period=atrLen) − ema(...)
// which always returns 0. Corrected to proper ATR calculation using true range
// and SMA smoothing, per Wilder's canonical ATR methodology.
// VWAP = Σ(price × volume) / Σ(volume) over lookback window
// Using cumulative VWAP approximation via typical price
timeseries typical = (high + low + close) / 3.0
timeseries vwap = vwma(source=typical, period=vwapLookback)
// ATR — proper true range calculation (Wilder 1978)
timeseries tr1 = high - low
timeseries tr2 = math.abs(high - close[1])
timeseries tr3 = math.abs(low - close[1])
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atrVal = ema(source=trueRange, period=atrLen)
// Premium/Discount: percent deviation from VWAP fair value
timeseries deviation = vwap > 0 ? (close - vwap) / vwap * 100.0 : 0
// Volume delta percentage (Campbell et al. 2005 institutional footprint)
timeseries buyV = buySell.buy_volume
timeseries sellV = buySell.sell_volume
timeseries deltaPct = (buyV + sellV) > 0 ? (buyV - sellV) / (buyV + sellV) * 100 : 0
timeseries deltaSmooth = sma(source=deltaPct, period=14)
// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018; NinjaTrader 2026)
// ------------------------------------------------------------------------------
timeseries devSmooth = ema(source=deviation, period=smoothLen)
// Z-Score: (deviation − mean) / stddev over rolling window
timeseries rollingMean = sma(source=devSmooth, period=zLookback)
timeseries rollingStd = stddev(source=devSmooth, period=zLookback)
timeseries zScore = useZScore && rollingStd > 0 ? (devSmooth - rollingMean) / rollingStd : 0
// Plot value: zScore if enabled, otherwise raw deviation
timeseries plotValue = useZScore ? zScore : deviation
// ------------------------------------------------------------------------------
// Regime Detection (Steidlmayer 2003 Market Profile / Value Area logic)
// ------------------------------------------------------------------------------
// Regime classification based on z-score:
// Premium: z > premiumThresh (above fair value, sell zone per Steidlmayer)
// Equilibrium: discountThresh ≤ z ≤ premiumThresh (Value Area, fair value)
// Discount: z < discountThresh (below fair value, buy zone per Steidlmayer)
// Extreme Premium: z > extremePremium (statistically rare, mean reversion)
// Extreme Discount: z < -extremePremium (statistically rare, mean reversion)
var regime = 0 // 0 = equilibrium, 1 = premium, -1 = discount
var extremeRegime = 0 // 0 = normal, 1 = extreme premium, -1 = extreme discount
if (useZScore) {
if (zScore >= premiumThresh) {
regime = 1
} else if (zScore <= discountThresh) {
regime = -1
}
if (zScore >= extremePremium) {
extremeRegime = 1
} else if (zScore <= -extremePremium) {
extremeRegime = -1
}
} else {
// Fallback for raw deviation (%)
var atrOffset = atrVal * atrMult
var premiumBot = atrOffset
var discountTop = -atrOffset
if (devSmooth >= premiumBot) {
regime = 1
} else if (devSmooth <= discountTop) {
regime = -1
}
if (devSmooth >= atrOffset * 2.0) {
extremeRegime = 1
} else if (devSmooth <= -atrOffset * 2.0) {
extremeRegime = -1
}
}
var regimeColor = regime == 1 ? premiumColor : (regime == -1 ? discountColor : neutralColor)
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, premium/discount events.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighDev = -999999.0
static sessionLowDev = 999999.0
static extremePremiumCount = 0
static extremeDiscountCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
// New bar — update session tracking
lastBarIndex = currentBarIndex
var val = useZScore ? zScore : devSmooth
if (val > sessionHighDev) {
sessionHighDev = val
}
if (val < sessionLowDev) {
sessionLowDev = val
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremePremiumCount = extremePremiumCount + 1
} else if (extremeRegime == -1) {
extremeDiscountCount = extremeDiscountCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------
// Horizontal guide lines — zero line (VWAP reference) and threshold zones
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
if (useZScore) {
hline(value=premiumThresh, color=opacity(premiumColor, 30), width=1)
hline(value=discountThresh, color=opacity(discountColor, 30), width=1)
hline(value=extremePremium, color=opacity(extremePremiumColor, 20), width=1)
hline(value=-extremePremium, color=opacity(extremeDiscountColor, 20), width=1)
} else {
var atrGuide = atrVal * atrMult
hline(value=atrGuide, color=opacity(premiumColor, 30), width=1)
hline(value=-atrGuide, color=opacity(discountColor, 30), width=1)
}
}
// Raw deviation as histogram (premium/discount visualization)
if (showRaw) {
plotBar(
value=plotValue,
colors=[premiumColor, discountColor],
width=1,
label=["Premium/Discount %"],
desc=["Price deviation from VWAP: positive=premium (sell), negative=discount (buy)"]
)
}
// Z-Score line with regime-coded fill area
if (showZScoreLine) {
plotLine(
value=zScore,
width=2,
colors=[premiumColor, discountColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["VWAP Z-Score"],
desc=["Z-score normalized VWAP deviation. Regime: premium/equilibrium/discount."],
fill=true
)
}
// Signal fill (deviation vs zero reference)
if (showSignalFill) {
var signalBull = plotValue >= 0
plotLine(
value=[plotValue, 0],
width=1,
colors=[opacity(premiumColor, 20), opacity(discountColor, 20)],
colorIndex=signalBull ? 0 : 1,
fill=true,
label=["Deviation", "Zero Line"],
desc=["Fill between VWAP deviation and zero reference"]
)
}
// VWAP zone lines (optional, for on-chart context)
if (showZones) {
var zoneOffset = atrVal * atrMult
plotLine(
value=[vwap + zoneOffset, vwap, vwap - zoneOffset],
colors=[premiumColor, eqColor, discountColor],
width=[1, 2, 1],
label=["Premium Zone", "VWAP (Fair Value)", "Discount Zone"],
desc=["Premium zone upper bound", "VWAP fair value benchmark", "Discount zone lower bound"]
)
}
// Volume delta line (Campbell et al. 2005 institutional footprint confirmation)
if (showDelta) {
plotLine(
value=deltaSmooth,
colors=["#ffffff"],
width=1,
label=["Delta Volume %"],
desc=["Net buy-sell volume percentage (smoothed) — confirms premium/discount pressure"]
)
}
// Regime transition shapes — premium/discount extremes (Steidlmayer 2003)
if (showShapes) {
var crossPremium = zScore >= premiumThresh && !isnan(zScore[1]) && zScore[1] < premiumThresh
var crossDiscount = zScore <= discountThresh && !isnan(zScore[1]) && zScore[1] > discountThresh
var extremePrm = zScore >= extremePremium && !isnan(zScore[1]) && zScore[1] < extremePremium
var extremeDsc = zScore <= -extremePremium && !isnan(zScore[1]) && zScore[1] > -extremePremium
if (crossPremium) {
plotShape(
value=zScore,
shape="triangleup",
color=extremePremiumColor,
width=3,
label=["Premium Zone"],
desc=["Price crossed into premium zone (above VWAP fair value) — sell setup per Steidlmayer"]
)
}
if (crossDiscount) {
plotShape(
value=zScore,
shape="triangledown",
color=extremeDiscountColor,
width=3,
label=["Discount Zone"],
desc=["Price crossed into discount zone (below VWAP fair value) — buy setup per Steidlmayer"]
)
}
if (extremePrm) {
plotShape(
value=zScore,
shape="diamond",
color=extremePremiumColor,
width=4,
label=["Extreme Premium"],
desc=["Extreme premium detected — statistically rare deviation from fair value, mean reversion likely"]
)
}
if (extremeDsc) {
plotShape(
value=zScore,
shape="diamond",
color=extremeDiscountColor,
width=4,
label=["Extreme Discount"],
desc=["Extreme discount detected — statistically rare deviation from fair value, mean reversion likely"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regime == 1 ? "PREMIUM" : (regime == -1 ? "DISCOUNT" : "EQUILIBRIUM")
var regimeTextColor = regime == 1 ? premiumColor : (regime == -1 ? discountColor : neutralColor)
plotTable(
data=[
["Premium & Discount V2", regimeText],
["VWAP", vwap[0]],
["Deviation %", devSmooth[0]],
["Z-Score", zScore[0]],
["ATR", atrVal[0]],
["Volume Delta %", deltaSmooth[0]],
["Session High", sessionHighDev],
["Session Low", sessionLowDev],
["Regime Changes", regimeChangeCount],
["Extreme Premium Events", extremePremiumCount],
["Extreme Discount Events", extremeDiscountCount]
],
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
)
}