Perfected FlowScript
Session Prism • [Leviathan]
Session Prism V2 — Multi-Session Flow is indexed as 259_session_prism_leviathan.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
15.0 KB
Lines
425
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Session Start
line 358:5
Trigger
(showShapes && isSessionStart)
Value
0
Deps
isSessionStart:timeseries, showShapes:input
Unlabeled shape
line 374:5
Trigger
(showShapes && regimeDiverge)
Value
cvdSmooth
Deps
regimeDiverge:var, showShapes:input
259_session_prism_leviathan.flowscript
source path: kscripts/perfected/259_session_prism_leviathan.flowscript · sha256:ff2faf1d0f98ec62fd5a77f14db62a740a80da88db76cd16d37cf1cb4af2f1af
//@version=2
// ============================================================================
// Session Prism V2 — Multi-Session Normalized Flow Analysis
// Author: Leviathan (@Leviathan) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, OFFCHART, #session, #tokyo, #london, #newyork, #prism
//
// Normalizes price, open interest (OI), and cumulative volume delta (CVD) to
// a common volatility scale, resets to zero at each session start, and
// visualizes convergences / divergences across three major trading sessions.
// Detects Tokyo, London, and New York sessions via UTC hour classification,
// computes session-specific metrics, and color-codes regime by dominant flow.
// Static state tracks session persistence, cumulative session flow, and
// cross-session divergence for context-aware alerting.
//
// Academic foundation (exact papers & formulas):
// 1. Harris (1986), "A Transaction Data Study of Weekly and Intradaily
// Patterns in Stock Returns", Journal of Financial Economics, 16(1), 99–117.
// Found significant weekday differences in intraday returns during the
// first 45 minutes after market open. Negative Monday close-to-close returns
// accrue between Friday close and Monday open. U-shaped intraday volume.
// DOI: https://doi.org/10.1016/0304-405X(86)90068-8
//
// 2. Ito & Hashimoto (2006), "Intraday Seasonality in Activities of the Foreign
// Exchange Markets", NBER Working Paper 12413.
// U-shaped pattern of quote revision frequency and trading volume for Tokyo
// and London participants; overlapping hours (London/NY) show large effects
// on price changes and volumes. FOREX activity highest in ordinary opening
// hours with no end-of-day spike.
// URL: https://www.nber.org/system/files/working_papers/w12413/w12413.pdf
//
// 3. Heston, Korajczyk & Sadka (2010), "Intra-day Patterns in the Cross-Section
// of Stock Returns", Journal of Finance, 65(4), 1369–1407.
// Return effect is pronounced in first and last half-hours of trading.
// Day 1 daily decile spread earns >11 bps in opening half-hour and >8 bps
// near the close. A smaller effect remains during the middle of the day.
// DOI: https://doi.org/10.1111/j.1540-6261.2010.01573.x
//
// 4. Steidlmayer & Hawkins (2002), "Steidlmayer on Markets: Trading with Market
// Profile" (2nd ed.), Wiley Trading. The Initial Balance (price range in the
// first hour) is used as a reference point for the rest of the session.
// Value Area (~70% of trading), Point of Control (POC), and day structure
// types form the auction market framework.
//
// 5. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// Journal of Financial Econometrics, 12(1), 47–88.
// [Formula] Δp_t = λ·OFI_t + ε_t. Order flow imbalance (OFI) linearly
// predicts short-term price changes. Session overlap periods see elevated
// OFI due to dual-market participation.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
//
// 6. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", Journal of Financial Economics, 65(1), 111–130.
// Market-wide returns are strongly affected by contemporaneous and lagged
// order imbalances. Excess buy or sell orders reduce liquidity.
// DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
// ============================================================================
define(
title="Session Prism V2 — Multi-Session Flow",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Data Sources --
var exchange = input(
name="exchange",
type="select",
defaultValue="BINANCE_FUTURES",
label="Exchange",
options=["BINANCE_FUTURES", "BYBIT", "OKEX_SWAP", "DERIBIT", "HYPERLIQUID_FUTURES"],
group="Data Sources"
)
var symbol = input(
name="symbol",
type="string",
defaultValue="BTCUSDT",
label="Symbol",
group="Data Sources"
)
// -- Computation --
var sessionLen = input(
name="sessionLen",
type="number",
defaultValue=96,
label="Session Length (bars)",
constraints={min: 24, max: 288, step: 12},
group="Computation"
)
var zWindow = input(
name="zWindow",
type="number",
defaultValue=50,
label="Z-Score Normalization Window",
constraints={min: 20, max: 200, step: 5},
group="Computation"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="EMA Smooth Length",
constraints={min: 1, max: 20, step: 1},
group="Computation"
)
// -- Display --
var showPrice = input(
name="showPrice",
type="boolean",
defaultValue=true,
label="Show Normalized Price Flow",
group="Display"
)
var showOI = input(
name="showOI",
type="boolean",
defaultValue=true,
label="Show Normalized OI Flow",
group="Display"
)
var showCVD = input(
name="showCVD",
type="boolean",
defaultValue=true,
label="Show Normalized CVD Flow",
group="Display"
)
var showRibbon = input(
name="showRibbon",
type="boolean",
defaultValue=true,
label="Show Session Ribbon Fill",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Session Transition Shapes",
group="Display"
)
var showSessionBg = input(
name="showSessionBg",
type="boolean",
defaultValue=false,
label="Show Session Background Labels",
group="Display"
)
// -- Colors --
var priceColor = input(
name="priceColor",
type="color",
defaultValue="#ffffff",
label="Price Flow Color",
group="Colors"
)
var oiColor = input(
name="oiColor",
type="color",
defaultValue="#2962ff",
label="OI Flow Color",
group="Colors"
)
var cvdColor = input(
name="cvdColor",
type="color",
defaultValue="#ffeb3b",
label="CVD Flow Color",
group="Colors"
)
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#00c853",
label="Bullish Divergence Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#d50000",
label="Bearish Divergence Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvTS.close
timeseries oi = open_interest(symbol=symbol, exchange=exchange)
timeseries buySell = buy_sell_volume(symbol=symbol, exchange=exchange)
// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(ohlcvTS.close[0]) || isnan(oi.close) || isnan(buySell.buy_volume)) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Per-bar % changes (guarded against zero) --
// Price % change: (close - close[1]) / close[1] × 100
timeseries pricePct = close[1] > 0 ? ((close - close[1]) / close[1]) * 100 : 0
// OI % change: (oi - oi[1]) / oi[1] × 100
timeseries oiPct = oi.close[1] > 0 ? ((oi.close - oi.close[1]) / oi.close[1]) * 100 : 0
// CVD delta: buy_volume - sell_volume; normalized by total volume
timeseries cvdDelta = buySell.buy_volume - buySell.sell_volume
timeseries totalVol = buySell.buy_volume + buySell.sell_volume
timeseries cvdPct = totalVol > 0 ? (cvdDelta / totalVol) * 100 : 0
// -- 3.2 Z-score normalisation (all denominators guarded against zero) --
// Per Harris (1986), intraday returns exhibit U-shaped patterns; z-score
// standardisation removes scale differences so price, OI, and CVD can be
// compared on a common axis.
timeseries priceMean = sma(source=pricePct, period=zWindow)
timeseries priceStd = stdev(source=pricePct, period=zWindow)
timeseries priceZ = (priceStd > 0) ? (pricePct - priceMean) / priceStd : 0
timeseries oiMean = sma(source=oiPct, period=zWindow)
timeseries oiStd = stdev(source=oiPct, period=zWindow)
timeseries oiZ = (oiStd > 0) ? (oiPct - oiMean) / oiStd : 0
timeseries cvdMean = sma(source=cvdPct, period=zWindow)
timeseries cvdStd = stdev(source=cvdPct, period=zWindow)
timeseries cvdZ = (cvdStd > 0) ? (cvdPct - cvdMean) / cvdStd : 0
// -- 3.3 EMA smoothing for visual clarity --
timeseries priceSmooth = ema(source=priceZ, period=smoothLen)
timeseries oiSmooth = ema(source=oiZ, period=smoothLen)
timeseries cvdSmooth = ema(source=cvdZ, period=smoothLen)
// -- 3.4 Session detection (Tokyo, London, NY) via UTC hour --
// Per Ito & Hashimoto (2006): Tokyo ~00-08 UTC, London ~08-16 UTC, NY ~13-21 UTC
// These are approximate crypto-market conventions; ICT killzones add nuance.
timeseries t = ohlcvTS.time
timeseries hourOfDay = (t / 3600000) % 24
var isTokyo = hourOfDay >= 0 && hourOfDay < 8
var isLondon = hourOfDay >= 8 && hourOfDay < 16
var isNY = hourOfDay >= 13 && hourOfDay < 21
var isOverlap = isLondon && isNY // London/NY overlap (13-16 UTC)
// Session label for display
var sessionLabel = isOverlap ? "OVERLAP" : (isTokyo ? "TOKYO" : (isLondon ? "LONDON" : (isNY ? "NEW YORK" : "OTHER")))
// -- 3.5 Session-based rolling metrics (cumulative within session window) --
// We use a bar-counter modulo sessionLen to reset cumulative sums.
timeseries barCounter = bar_index % sessionLen
timeseries isSessionStart = barCounter == 0
// Rolling session sums (reset every sessionLen bars via bar_counter reset)
timeseries priceSession = sma(source=priceZ, period=sessionLen)
timeseries oiSession = sma(source=oiZ, period=sessionLen)
timeseries cvdSession = sma(source=cvdZ, period=sessionLen)
// -- 3.6 Regime detection (convergence / divergence) --
// Convergence: all three flows aligned (all positive or all negative)
// Divergence: price and CVD disagree (price up, CVD down = bearish divergence)
var allBull = priceSmooth > 0 && oiSmooth > 0 && cvdSmooth > 0
var allBear = priceSmooth < 0 && oiSmooth < 0 && cvdSmooth < 0
var priceCvdDiverge = (priceSmooth > 0 && cvdSmooth < 0) || (priceSmooth < 0 && cvdSmooth > 0)
var regimeBull = allBull
var regimeBear = allBear
var regimeDiverge = priceCvdDiverge && !allBull && !allBear
var regimeNeutral = !regimeBull && !regimeBear && !regimeDiverge
// -- 3.7 Session state tracking via static variables --
// Tracks which session is active, session transitions, and cumulative flow.
static lastSessionLabel = ""
static sessionTransitions = 0
static cumTokyoFlow = 0.0
static cumLondonFlow = 0.0
static cumNYFlow = 0.0
if (sessionLabel != lastSessionLabel) {
sessionTransitions = sessionTransitions + 1
lastSessionLabel = sessionLabel
}
if (!isnan(priceZ)) {
if (isTokyo) {
cumTokyoFlow = cumTokyoFlow + priceZ
} else if (isLondon) {
cumLondonFlow = cumLondonFlow + priceZ
} else if (isNY) {
cumNYFlow = cumNYFlow + priceZ
}
}
// -- 3.8 Zero-line helper for fill areas --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill
// ---------------------------------------------------------------------------
// 4.1 Normalized Price Flow (plotLine)
if (showPrice) {
plotLine(
value=priceSmooth,
width=2,
colors=[priceColor],
label=["Price Flow"],
desc=["Z-score normalized price change (%), smoothed"]
)
}
// 4.2 Normalized OI Flow (plotLine)
if (showOI) {
plotLine(
value=oiSmooth,
width=2,
colors=[oiColor],
label=["OI Flow"],
desc=["Z-score normalized OI change (%), smoothed"]
)
}
// 4.3 Normalized CVD Flow (plotLine)
if (showCVD) {
plotLine(
value=cvdSmooth,
width=2,
colors=[cvdColor],
label=["CVD Flow"],
desc=["Z-score normalized CVD (%), smoothed"]
)
}
// 4.4 Session ribbon fill (plotLine + fill) between Price and CVD
// colorIndex: 0 = bullish convergence, 1 = bearish convergence, 2 = divergence
timeseries ribbonColorIdx = regimeBull ? 0 : (regimeBear ? 1 : 2)
if (showRibbon) {
plotLine(
value=[priceSmooth, cvdSmooth],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30), transparency("#9e9e9e", 30)],
colorIndex=ribbonColorIdx,
fill=true,
label=["Price Flow", "CVD Flow"],
desc=["Ribbon fill between price and CVD z-scores; colour = regime"]
)
}
// 4.5 Session transition shapes (plotShape) — mark session start bars
if (showShapes && isSessionStart) {
plotShape(
value=0,
shape="diamond",
colorIndex="#ffffff",
width=2,
label=["Session Start"],
desc=["New session window started (bar " + barCounter + ")"]
)
}
// 4.6 Divergence shapes (plotShape) — when price and CVD disagree
if (showShapes && regimeDiverge) {
var divShape = priceSmooth > 0 ? "triangledown" : "triangleup"
var divColor = priceSmooth > 0 ? bearColor : bullColor
var divLabel = priceSmooth > 0 ? "Bearish Div" : "Bullish Div"
var divDesc = priceSmooth > 0 ? "Price rising but CVD falling — bearish divergence" : "Price falling but CVD rising — bullish divergence"
plotShape(
value=cvdSmooth,
shape=divShape,
colorIndex=divColor,
width=2,
label=[divLabel],
desc=[divDesc]
)
}
// 4.7 Reference zero line
hline(value=0, color="#ffffff30", width=1)
// 4.8 Optional session background labels (text labels on chart)
if (showSessionBg && isSessionStart) {
// Platform-dependent; if label() is supported, uncomment below:
// label(text=sessionLabel, y=0, color=transparency("#ffffff", 80), size="small")
}
// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULL CONV" : (regimeBear ? "BEAR CONV" : (regimeDiverge ? "DIVERGENCE" : "NEUTRAL"))
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : (regimeDiverge ? "#ff9800" : "#9e9e9e"))
plotTable(
data=[
["Session Prism V2", regimeText],
["Session", sessionLabel],
["Price Z", priceSmooth[0]],
["OI Z", oiSmooth[0]],
["CVD Z", cvdSmooth[0]],
["Cum Tokyo", cumTokyoFlow],
["Cum London", cumLondonFlow],
["Cum NY", cumNYFlow],
["Transitions", sessionTransitions]
],
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
)
}