Quarterly/Monthly/Weekly Performance | Astral Vision Quarterly/Monthly/Weekly Performance | Astral Vision 🌠💠
Price performance measured over fixed trailing windows (7, 30, and 90 bars) captures the momentum of Bitcoin's move at three structurally distinct timescales simultaneously.
Weekly performance reflects short-term trend pressure; monthly performance captures the medium-term cycle direction; quarterly performance reveals whether the broader macro trend is accumulating or distributing. Reading all three in a single panel eliminates the need to switch timeframes to understand where momentum stands across the full temporal structure.
This indicator plots trailing price performance as gradient-filled columns for each active window, with configurable overbought and oversold thresholds that identify statistically extreme moves. All three windows can be active simultaneously or independently, and each drives its own overlay on the price chart through candle coloring or background highlighting.
Calculation ⚙️
`Performance = (close − close ) / close × 100`
Where N is 7, 30, or 90 bars for weekly, monthly, and quarterly windows respectively. The result is a simple trailing percentage return expressed relative to the close N bars ago, with no smoothing applied — preserving the raw momentum read at each timescale.
Plots 📊
Performance columns for each active window (weekly, monthly, quarterly) with gradient fill, opaque at the column tip, fading toward zero
Zero baseline
Overbought and oversold threshold lines for each active window
Background highlight on the price chart when any active window's performance breaches a threshold (Background Color mode)
Candle coloring on the price chart by the sign of the active window's performance (Plot Candle mode)
Inputs 🎛️
`Overlay Mode`: Background Color, Plot Candle, or None for price chart output
`Show Weekly / Monthly / Quarterly`: independent toggles for each performance window
`Weekly OB / OS Threshold`: extreme levels for the 7-bar window (defaults +20 / −15)
`Monthly OB / OS Threshold`: extreme levels for the 30-bar window (defaults +35 / −20)
`Quarterly OB / OS Threshold`: extreme levels for the 90-bar window (defaults +50 / −30)
Colors 🎨
5 Astral Vision presets + custom override. Default: Hermes. Positive color applies when performance is above zero; negative color applies when performance is below zero. Both the column fills and the price chart overlays follow the same coloring logic.
Purpose 🎯
Standard momentum indicators process price through mathematical transformations (RSI, MACD, stochastic) that make their absolute values abstract and cycle-dependent. A trader looking for a direct answer to "how much has Bitcoin moved in the last month?" gets no clean output from any of those tools.
This indicator answers that question directly with no transformation, keeping the output in percentage terms that are immediately interpretable.
The three-window structure lets traders read weekly, monthly, and quarterly momentum in a single panel, identifying divergences between timescales, such as a strong monthly trend with an overextended weekly reading, that single-window indicators cannot surface.
The threshold system identifies when a given trailing return has reached historically extreme levels for that window, providing a contextual signal layer on top of the raw performance read.
Disclaimer ⭕️
It is not financial advice, not an investment recommendation, and not affiliated with any financial institution, research firm, or organization of any kind. All content is provided for educational and informational purposes only. Always conduct your own research before making any financial decision. Indicator

Rolling Sharpe Ratio Oscillator | Astral Vision Rolling Sharpe Ratio Oscillator | Astral Vision 🌠💠
The Sharpe Ratio measures risk-adjusted return: how much excess return is being generated per unit of volatility. Applied as a rolling oscillator to Bitcoin's daily log returns, it answers a question that neither price nor momentum indicators address: is the current appreciation being earned efficiently relative to the risk being taken, or is it a volatile, noisy move that consumes large drawdowns to produce modest gains?
High rolling Sharpe values indicate sustained, low-volatility uptrends where return per unit of risk is structurally elevated, historically coinciding with the most efficient phases of Bitcoin's bull runs. Negative Sharpe values indicate periods where volatility exceeds returns, marking drawdowns and bear phases.
This indicator plots the annualized rolling Sharpe as a smoothed oscillator with configurable thresholds, and back-projects those thresholds onto the price chart as dynamic levels representing the price that would produce each Sharpe extreme given current return and volatility conditions.
Calculation ⚙️
`Log Return = log(close / close )`
`Rolling Sharpe = (SMA(Log Return, length) / StdDev(Log Return, length)) × √365`
The ratio is annualized by multiplying by the square root of 365, expressing it in standard annual terms. An EMA of configurable length is then applied to smooth the raw Sharpe before threshold evaluation and coloring.
The price bands invert the Sharpe thresholds back to price space:
`Band Price = close × exp(threshold × StdDev / √365 × length)`
This produces a dynamic price level representing what price would need to be, given current volatility, to produce the specified Sharpe value.
Plots 📊
Smoothed Sharpe oscillator line in the indicator panel, colored by regime or continuous gradient
Overbought and oversold threshold lines
Fill between oscillator and overbought threshold when breached (distribution zone)
Fill between oscillator and oversold threshold when breached (accumulation zone)
Dynamic overbought and oversold price bands on the price chart, EMA-smoothed
Candle coloring on the price chart by regime or gradient
Background highlight on the price chart when either threshold is active
Inputs 🎛️
`Lookback Period (days)`: rolling window for mean and standard deviation of log returns (default 365)
`Smoothing EMA Length`: EMA applied to the raw Sharpe before all output (default 30)
`Oversold Threshold`: Sharpe level marking risk-adjusted accumulation extremes (default −1.5)
`Overbought Threshold`: Sharpe level marking risk-adjusted distribution extremes (default 2.8)
`Use Gradient Color`: toggles between continuous gradient coloring across the −2 to +2 range and discrete regime-based coloring
Colors 🎨
5 Astral Vision presets + custom override. Default: Futura. In gradient mode, color transitions continuously from negative to positive across the Sharpe range. In discrete mode, positive color activates above the overbought threshold, negative below the oversold threshold, and neutral between them.
Purpose 🎯
Standard momentum indicators like RSI and MACD measure price direction and speed, but are blind to whether that directional move is being achieved efficiently. A 30% Bitcoin rally with 80% annualized volatility carries very different risk-adjusted implications than the same rally with 40% volatility, yet both look identical on a price or momentum chart.
The rolling Sharpe makes that distinction explicit. The price band back-projection eliminates the need to mentally translate Sharpe values into price context: the bands show directly on the chart what price level corresponds to each statistical extreme given current volatility, updating dynamically as the volatility regime evolves.
The gradient coloring option provides a continuous read of risk-adjusted efficiency across the entire oscillator range, not just at binary threshold crossings.
Disclaimer ⭕️
It is not financial advice, not an investment recommendation, and not affiliated with any financial institution, research firm, or organization of any kind. All content is provided for educational and informational purposes only. Always conduct your own research before making any financial decision. Indicator

Bootstrap Confidence Break [forexobroker]Bootstrap Confidence Break flags bars whose return falls outside a 90 percent confidence interval on the rolling mean return. The CI uses the standard-error formulation that is asymptotically equivalent to the percentile bootstrap when N >= 30, but is fully deterministic — no random number generation, no repainting. Signals fire on EMA cross when the move is statistically significant.
🔶 ALGORITHM
1. r = close - close (single-bar return).
2. mu = sma(r, N); sd = stdev(r, N); se = sd / sqrt(N).
3. CI high = mu + 1.645 * se; CI low = mu - 1.645 * se (90 percent two-sided).
4. Outside-up regime when r > CI_high; outside-down when r < CI_low.
🔶 SIGNAL LOGIC
- Buy: outside-up AND close crosses EMA up AND not already long AND cooldown elapsed AND barstate.isconfirmed.
- Sell: outside-down AND close crosses EMA down.
- Position-lock state machine.
🔶 INPUTS
- Return Window (default 40)
- Pullback EMA Length (default 8)
- Cooldown Bars (default 4)
- Visual: dashboard, glow, EMA toggle, buy / sell colors
🔶 ALERTS
BCB Buy, BCB Sell, BCB Any Signal, BCB Outside Up, BCB Outside Down, BCB EMA Up, BCB EMA Down, BCB 2-Sigma, BCB Webhook JSON.
🔶 LIMITATIONS
- Standard-error CI assumes approximately normal returns; heavy-tailed distributions widen the true tail risk and make this more conservative than a true percentile bootstrap.
- 90 percent interval is a reasonable default; adjust the multiplier (1.645) for stricter or looser cutoffs by editing the script.
- Signal cadence depends entirely on volatility regime; quiet markets produce few outside-CI bars.
- Combining CI break with EMA cross dampens whipsaws but slightly delays entry vs raw CI break.
Indicator

Bayesian Trend Posterior [forexobroker]Bayesian Trend Posterior treats each bar as a Bernoulli observation (up vs not-up) and runs a Beta-Bernoulli sequential update over a sliding window. The posterior probability P(next bar up) = (alpha + u) / (alpha + beta + N), where u is the count of up-bars in the window. Schmitt hysteresis on the posterior locks bull or bear regimes, preventing chatter near 0.5.
🔶 ALGORITHM
1. Count up-bars u in the last N closes (close > close ).
2. Posterior mean = (alpha + u) / (alpha + beta + N) using Beta(alpha, beta) prior.
3. Hysteresis: regime locks to +1 when posterior >= upper threshold, locks to -1 when posterior <= lower threshold, holds otherwise.
4. Within a locked regime, an EMA cross provides the entry trigger so the indicator can fire multiple times during sustained trends.
🔶 SIGNAL LOGIC
- Buy: bull regime locked AND close crosses pullback EMA up AND not already long AND cooldown elapsed AND barstate.isconfirmed.
- Sell: bear regime locked AND close crosses pullback EMA down.
- Position-lock state machine.
🔶 INPUTS
- Posterior Window N (default 30)
- Prior alpha (default 2.0)
- Prior beta (default 2.0)
- Upper Hysteresis (default 0.55)
- Lower Hysteresis (default 0.45)
- Pullback EMA Length (default 8)
- Cooldown Bars (default 4)
- Visual: dashboard, glow, EMA toggle, buy / sell colors
🔶 ALERTS
BTP Buy, BTP Sell, BTP Any Signal, BTP Bull Lock, BTP Bear Lock, BTP High Posterior, BTP Low Posterior, BTP Cross 0.5, BTP Webhook JSON.
🔶 LIMITATIONS
- Bernoulli simplification ignores bar size; a tiny up-bar contributes the same as a strong one. Pair with an ATR-aware filter for size-weighted posteriors.
- Window N is the dominant tuning knob: smaller N reacts faster but flips more; larger N is steadier.
- Prior alpha = beta = 2 is uninformative; users with strong directional bias can adjust.
- Hysteresis prevents chatter but slightly delays regime detection vs threshold-only logic.
Indicator

Local Linear Slope Network [forexobroker]Local Linear Slope Network runs four `ta.linreg` regressions at windows 10/20/40/80, computes each line's slope sign per bar, and only fires signals when at least N slopes agree AND the previous bar did NOT yet have agreement. A clean fractal trend-confirmation entry — most trend indicators use one length; this one votes across four.
🔶 ALGORITHM
For each window n in {10, 20, 40, 80}:
1. linreg_n = ta.linreg(close, n, 0)
2. slope_n = linreg_n − linreg_n
3. slope-sign vote: count how many slopes are > 0 (upCount) and how many are < 0 (dnCount)
4. Agreement edge: at least N slopes agree AND previous bar agreement was below the same threshold
The "agreement edge" requirement gates the signal to a single bar at the regime change, not a stream of confirmations.
🔶 SIGNAL LOGIC
- Buy: upCount ≥ N AND previous bar upCount < N AND cooldown AND barstate.isconfirmed
- Sell: dnCount ≥ N AND previous bar dnCount < N AND cooldown AND barstate.isconfirmed
🔶 INPUTS
- Window 1/2/3/4 (defaults 10/20/40/80 — dyadic spacing)
- Min Slopes Agreeing (default 3 of 4)
- Signal Cooldown (default 8)
- Visual toggles for slowest line, dashboard, glow, colors
🔶 ALERTS
LLN Buy / Sell, Any Signal, Full Bull (4/4), Full Bear (4/4), Fast Pair Up/Dn, Webhook JSON.
🔶 LIMITATIONS
- ta.linreg internally is OLS regression — robust but assumes linear local trend. Works well on liquid trending instruments.
- Slope is computed as endpoint difference (linreg − linreg ) — sensitive to outlier bars.
- Slowest window (80 default) sets warmup.
- The dyadic spacing (10/20/40/80) is opinionated; tighter/wider spacings change signal frequency drastically.
Indicator

Indicator

Auto Crypto Market CapAuto Crypto Market Cap is a simple utility indicator that automatically displays the current market capitalization of the cryptocurrency shown on your chart.
The script detects the base asset from the current symbol, for example:
AAVEUSDT → AAVE
SOLUSDT → SOL
ETHUSDT → ETH
It then requests the matching PulseWire CRYPTOCAP symbol, such as CRYPTOCAP:AAVE or CRYPTOCAP:SOL, and displays the result in a clean table on the chart.
Features:
• Automatically detects the crypto ticker from the current chart
• Displays market cap in a readable format: K, M, B, or T
• Optional manual ticker override for special symbols
• Useful for quickly checking whether a coin is small-cap, mid-cap, or large-cap
• Works directly on price charts without needing to open a separate CRYPTOCAP chart
Examples:
AAVEUSDT → shows AAVE market cap
BTCUSDT → shows BTC market cap
ETHUSDT → shows ETH market cap
LINKUSDT → shows LINK market cap
For symbols like 1000PEPEUSDT, WETHUSDT, or WBTCUSDT, you can use the manual override input to set the correct ticker, for example PEPE, ETH, or BTC.
Important:
This indicator depends on PulseWire’s CRYPTOCAP data. If PulseWire does not provide a CRYPTOCAP symbol for a specific asset, the market cap may show as unavailable. Indicator

Bitcoin/USDT Dominance Ratio | Astral Vision Bitcoin/USDT Dominance Ratio | Astral Vision 🌠💠
USDT dominance measures the share of total crypto market capitalization held in Tether.
When USDT dominance is high, capital is parked in stablecoins: risk appetite is low and dry powder is accumulating.
When USDT dominance is low, capital has rotated into risk assets: stablecoin supply relative to the market has been deployed.
Dividing Bitcoin's price by USDT dominance produces a ratio that amplifies both conditions: it rises when BTC appreciates while stablecoin dominance contracts (maximum risk-on), and falls when BTC depreciates while stablecoin dominance expands (maximum risk-off).
The ratio acts as a liquidity-adjusted price: a measure of how much Bitcoin is worth relative to the available pool of sidelined capital.
Calculation ⚙️
`Ratio = BTC Price / USDT Dominance (%)`
Both the ratio candles and the price chart candles are colored identically by the same threshold logic, so the regime read is simultaneously visible in the indicator panel and on the price chart without switching focus.
Plots 📊
Ratio candles in the indicator panel, colored by active regime
Oversold threshold line (positive color) and overbought threshold line (negative color)
Price chart candle coloring by the same regime logic
Background highlight on the price chart when either threshold is breached
Inputs 🎛️
`Oversold Threshold`: ratio level below which the signal enters accumulation territory (default 2100)
`Overbought Threshold`: ratio level above which the signal enters distribution territory (default 27000)
Colors 🎨
5 Astral Vision presets + custom override. Default: Infinito. Positive color activates below the oversold threshold; negative color activates above the overbought threshold.
Purpose 🎯
Tracking BTC price and USDT dominance as separate charts requires constant context-switching and leaves the relationship between the two implicit. Most dominance indicators plot stablecoin share in isolation with no connection to price magnitude, while raw BTC price charts carry no information about the liquidity environment surrounding each move.
This indicator fuses the two into a single ratio that makes the liquidity context inseparable from price. A BTC rally with contracting USDT dominance reads as a structurally stronger move than the same price gain with stable or rising stablecoin dominance and this indicator makes that difference directly visible through threshold crossings, candle color, and background regime highlighting on the price chart.
Disclaimer ⭕️
It is not financial advice, not an investment recommendation, and not affiliated with any financial institution, research firm, or organization of any kind. All content is provided for educational and informational purposes only. Always conduct your own research before making any financial decision. Indicator

Anchored Volume Weighted Average Price | Astral Vision Anchored Volume Weighted Average Price | Astral Vision 🌠💠
The Volume Weighted Average Price anchored to a fixed date represents the average price at which every Bitcoin has changed hands since that moment, weighted by volume.
Unlike a moving average which weights bars equally by time an anchored VWAP weights each bar by its trading activity, making it a true reflection of the average cost basis for all market participants who entered after the anchor point.
When price trades above an anchored VWAP, the aggregate of participants since that anchor is in profit. When price trades below it, they are in loss.
This makes anchored VWAPs among the most reliable dynamic support and resistance levels available, as they represent the price at which the largest volume of participants is either defending a gain or protecting against a loss.
This indicator plots up to 16 simultaneous anchored VWAPs: one per calendar year from 2013 through 2025, plus three fully custom anchors at any user-defined date, all on the price chart with individual color control and labeled at the current bar.
Calculation ⚙️
`VWAP = Cumulative(HLC3 × Volume) / Cumulative(Volume)`
Accumulation begins on the first bar of the anchor year (or the exact timestamp for custom anchors) and runs continuously to the present bar. Each VWAP is computed independently, carrying its own cumulative price-volume and volume sums from its respective start date.
Plots 📊
Up to 13 year-anchored VWAP lines (2013–2025), each with a dual-layer glow (linewidths 6/2, transparency 80/0)
3 custom timestamp-anchored VWAP lines with the same glow rendering
Labeled endpoints at the current bar for every active VWAP, showing year or custom identifier
Inputs 🎛️
`2013` through `2025` :individual toggles to enable each year-anchored VWAP, each with its own color picker
`Custom 1 / 2 / 3`: toggles for three free-anchor VWAPs, each with a date/time input and color picker
Colors 🎨
Each VWAP line has its own independent color, pre-assigned along a spectral progression from violet (2013) through the visible spectrum to yellow (2025), giving each cycle year a visually distinct identity at a glance. Custom anchors default to blue, yellow, and green with full override available.
Purpose 🎯
Standard VWAP tools on PulseWire anchor to the current session or a single user-defined point, offering no way to compare multiple historical anchors simultaneously. Traders who want to assess confluence across different cycle entry points must place and manage anchors manually, one at a time.
This indicator solves that entirely: all major Bitcoin calendar years are available as one-click toggles, letting you layer any combination of historical cost bases onto the chart instantly. The custom anchors extend this to any structurally significant date (cycle lows, halving events, ETF approvals) without any manual drawing tool interaction. Confluence zones where multiple VWAPs converge are immediately visible and have historically acted as the strongest support and resistance levels in Bitcoin's price structure.
Disclaimer ⭕️
It is not financial advice, not an investment recommendation, and not affiliated with any financial institution, research firm, or organization of any kind. All content is provided for educational and informational purposes only. Always conduct your own research before making any financial decision. Indicator

NQ HMA Midday StrategyThe Story Behind This Strategy
This strategy didn't come from a quick backtest or a weekend project. It's the result of months of systematic research across multiple strategy families (DVD, Zscore, HMA) on both NQ and ES futures.
My Research Process:
I started with six strategy families and ran extensive backtests spanning from 2019 through April 2025, followed by recent validation from 2025 through April 2026. My goal wasn't to maximize historical PnL - it was to identify robust strategies with better drawdown behavior, stronger profit factors, and more stable portfolio-level risk/reward.
After evaluating hundreds of parameter combinations and multiple objective functions, I narrowed down to two core NQ candidates. This HMA Midday strategy emerged as one of them because it showed:
Strong recent performance (2025-2026: $16,865 profit, 1.53 profit factor)
Reasonable drawdown characteristics ($8,940 max drawdown)
Clean portfolio behavior when combined with other strategies
Better risk-adjusted returns than the baseline HMA version
What This Strategy Actually Does:
It's a momentum-based system using Hull Moving Averages, EMAs, and Rate of Change to identify trade setups during specific time windows (11:00-15:45 ET trading, 10:30-13:00 ET entries). I added the one-trade-per-day limit after observing that multiple daily entries often degraded risk-adjusted returns.
The Honest Truth:
This is still a research strategy, not a live-trading system
I have a Python version with walk-forward optimization that I use to tune parameters when market regimes change
Parameters should be re-optimized periodically - they're not set-and-forget
The strategy works best as part of a portfolio, not in isolation
Past performance (2019-2026) doesn't guarantee future results
Why I'm Publishing It:
To share the methodology and code structure with the community. The approach - combining trend indicators with momentum filters, time windows, and ATR-based risk management - is worth studying even if you don't trade this exact configuration.
Developer: QuantByBoji
Status: Research candidate, not live-trading recommendation Strategy

Indicator

Indicator

QuantAbundancia - AI Bubble MapMethodology
━━━━━━━━━━━
This indicator overlays QuantAbundancia's bubble framework on any PulseWire chart. We classify ~80 AI-adjacent stocks into 12 thematic blocs and measure each bloc's 252-day residualized correlation — that is, the correlation of each constituent's returns AFTER stripping out AMEX:SPY beta. What's left is the idiosyncratic component: how much of the price action is real thematic flow vs market beta in costume.
What it shows
━━━━━━━━━━━━━
For the chart's symbol, the indicator displays:
• Which bubble it belongs to (Quantum, Memory, Compute, etc.)
• That bubble's 252-day residualized correlation + verdict
• Editorial Fib key level (if we've marked one)
Verdict legend
━━━━━━━━━━━━━━
🟢 strongest / tightest / validated → real bloc, idiosyncratic flow
🟡 validating / moderate / speculative → emerging, monitor
🔴 FAILED → market beta in costume, NOT a real bloc
Bubbles covered
━━━━━━━━━━━━━━━
Quantum (0.76 strongest) · Semi Equipment (0.82 tightest) · Memory / HBM (0.71 validated) · Cooling / DC Infra (0.70 validated) · Compute / GPUs (0.65 moderate) · Networking / Optical (0.60 validating) · Space / Sat Comms (0.60 validating) · Datacenter Power (0.55 validating) · Nuclear / SMR (0.70 speculative) · AI Software (0.10 FAILED) · Hyperscalers (0.05 FAILED) · Robotics (0.20 FAILED)
Editorial Fib key levels
━━━━━━━━━━━━━━━━━━━━━━━━
48 tickers have user-curated Fib levels marked (NVDA $71, MU $341, ASML $1205, ASTS $63, RKLB $69, OKLO $69, etc.) — drawn as horizontal dashed lines.
Data source
━━━━━━━━━━━
Data is embedded as constants in this script. The live truth lives at quantabundancia.com — methodology article: quantabundancia.com/articles/residualized-correlation. Daily refreshed digest at quantabundancia.com/today.
This is observational data only — not buy/sell signals. We map flows; you bring the conviction. Indicator

Indicator

PickMyTradeLibLibrary "PickMyTradeLib"
PickMyTradeLib — Market Microstructure & Quantitative Finance Library for Pine Script.
Provides analytically rigorous, academically grounded functions covering five domains:
(1) Synthetic bid-ask spread estimation (Roll 1984, Corwin-Schultz 2012),
(2) Market illiquidity & price impact (Amihud 2002, Kyle 1985),
(3) OHLC-efficient volatility estimators (Garman-Klass 1980, Parkinson 1980, Rogers-Satchell 1991),
(4) Fractal & complexity measures (Higuchi 1988, Hurst R/S, Katz 1988),
(5) Realized distributional moments (skewness, excess kurtosis, realized variance).
All functions are pure Pine — no request.security calls, no external dependencies.
Compatible with any instrument and timeframe. Import with:
import PickMyTrade/PickMyTradeLib/1 as pmtq
rollSpread(src, len, zLen)
Roll's (1984) synthetic bid-ask spread estimator.
Exploits the negative serial covariance of price changes that
arises from the bid-ask bounce. Requires no order-book data.
Formula: spread = 2 * sqrt(max(0, -Cov(Δp_t, Δp_{t-1})))
Reference: Roll, R. (1984). "A Simple Implicit Measure of the
Effective Bid-Ask Spread in an Efficient Market." JoF 39(4).
Parameters:
src (float) : Price series (typically close)
len (simple int) : Lookback window for covariance estimation (minimum 10)
zLen (simple int) : Window for z-score normalisation (default = len * 3)
Returns: SpreadResult with value, zscore, and anomaly flag
corwinSchultz(h, l, zLen)
Corwin & Schultz (2012) high-low spread estimator.
Derives the effective spread from the ratio of two-day to
one-day high-low ranges. More robust than Roll on noisy series.
Reference: Corwin, S. & Schultz, P. (2012). "A Simple Way to
Estimate Bid-Ask Spreads from Daily High and Low Prices."
JoF 67(2), 719-760.
Parameters:
h (float) : High series
l (float) : Low series
zLen (simple int) : Window for z-score normalisation
Returns: SpreadResult
amihud(src, vol, len, zLen)
Amihud (2002) illiquidity ratio.
Measures how much price moves per unit of trading volume —
higher values mean illiquid markets where small trades move price.
Formula: ILLIQ_t = |r_t| / Volume_t, smoothed over len bars.
Reference: Amihud, Y. (2002). "Illiquidity and stock returns."
Journal of Financial Markets 5(1), 31-56.
Parameters:
src (float) : Price series for return calculation
vol (float) : Volume series
len (simple int) : Rolling average window
zLen (simple int) : Z-score window
Returns: SpreadResult (value = illiquidity ratio, z-scored)
kyleLambda(src, vol, len)
Kyle's Lambda — price impact coefficient (Kyle 1985).
Estimates how aggressively price responds to signed order flow.
Approximates signed volume as: buy volume when close >= open,
sell volume otherwise. Lambda = OLS slope of Δprice on signed vol.
Reference: Kyle, A.S. (1985). "Continuous Auctions and Insider
Trading." Econometrica 53(6), 1315-1335.
Parameters:
src (float) : Price series
vol (float) : Volume series
len (simple int) : Regression window (minimum 15)
Returns: SpreadResult (value = lambda slope)
garmanKlass(o, h, l, c, len)
Garman-Klass (1980) volatility estimator.
Uses OHLC data to estimate variance more efficiently than
close-to-close (theoretical efficiency ratio ≈ 7.4×).
Formula: σ² = 0.5*(ln H/L)² − (2ln2−1)*(ln C/O)²
Reference: Garman, M. & Klass, M. (1980). "On the Estimation
of Security Price Volatilities from Historical Data."
Journal of Business 53(1), 67-78.
Parameters:
o (float) : Open series
h (float) : High series
l (float) : Low series
c (float) : Close series
len (simple int) : Averaging window
Returns: VolResult with daily, annual, and rank fields
parkinson(h, l, len)
Parkinson (1980) volatility estimator.
Uses only High and Low — ignores close. More efficient than
close-to-close (theoretical efficiency ≈ 5.2×) but assumes
no overnight gaps or drift. Good intraday baseline.
Reference: Parkinson, M. (1980). "The Extreme Value Method
for Estimating the Variance of the Rate of Return."
Journal of Business 53(1), 61-65.
Parameters:
h (float) : High series
l (float) : Low series
len (simple int) : Averaging window
Returns: VolResult
rogersSatchell(o, h, l, c, len)
Rogers-Satchell (1991) volatility estimator.
Accounts for non-zero drift — unbiased even when price trends.
The only classical OHLC estimator that handles drift correctly.
Formula: σ² = ln(H/C)*ln(H/O) + ln(L/C)*ln(L/O)
Reference: Rogers, L. & Satchell, S. (1991). "Estimating
Variance From High, Low and Closing Prices."
Annals of Applied Probability 1(4), 504-512.
Parameters:
o (float) : Open series
h (float) : High series
l (float) : Low series
c (float) : Close series
len (simple int) : Averaging window
Returns: VolResult
higuchifd(src, len, kMax)
Higuchi (1988) Fractal Dimension.
Estimates the fractal complexity of a time series directly from
the data. D = 1 → perfectly smooth trend. D = 2 → pure noise.
D < 1.4: trending. 1.4-1.6: random walk. D > 1.6: mean-reverting.
This implementation uses the average of k=2..kMax curve lengths
and OLS regression of log(L_k) on log(k) to get the slope (= -FD).
Reference: Higuchi, T. (1988). "Approach to an irregular time
series on the basis of the fractal theory." Physica D 31(2).
Parameters:
src (float) : Input price series
len (simple int) : Number of bars to sample (minimum 20, recommended 30-50)
kMax (simple int) : Maximum lag (2-8; higher = more stable but slower)
Returns: FractalResult with fd, regime string, and normalised
hurstRS(src, len)
Hurst Exponent via Rescaled Range (R/S) analysis.
H > 0.55 → persistent trend-following (long memory).
H ≈ 0.50 → random walk (no memory).
H < 0.45 → mean-reverting (anti-persistent).
Note: FD and Hurst are complementary: FD = 2 - H (theoretically).
Parameters:
src (float) : Input price series
len (simple int) : Lookback length (minimum 30, recommended 60-100)
Returns: float Hurst exponent in
moments(src, len)
Rolling distributional moments of a return series.
Computes mean, standard deviation, skewness, and excess kurtosis
over a rolling window using Welford's online algorithm for
numerical stability.
Parameters:
src (float) : Input series (typically log returns: math.log(close/close ))
len (simple int) : Rolling window length
Returns: MomentResult with mean, stdev, skew, kurt
normalise(src, len)
Normalise any float series to over a rolling window.
Parameters:
src (float) : Input series
len (simple int) : Lookback for min/max
Returns: float in
ewZscore(src, len)
Exponentially weighted z-score — reacts faster than simple z-score.
Parameters:
src (float) : Input series
len (simple int) : EMA length for mean and variance estimation
Returns: float z-score
zscoreColor(z)
Colour helper — maps a z-score to a green-grey-red gradient.
z < -2: bright green (anomaly low) z > 2: bright red (anomaly high)
Parameters:
z (float) : Z-score value
Returns: color
SpreadResult
Holds a complete spread estimate result with its z-score
Fields:
value (series float) : Raw spread estimate (in price units or as ratio)
zscore (series float) : Rolling z-score of the estimate vs lookback window
isAnomaly (series bool) : True when zscore > threshold (default 2.0)
VolResult
Holds a volatility estimate with annualisation
Fields:
daily (series float) : Daily volatility estimate (fraction of price)
annual (series float) : Annualised estimate (daily * sqrt(252))
rank (series float) : 0-100 percentile rank vs lookback window
FractalResult
Fractal / complexity measurement result
Fields:
fd (series float) : Fractal Dimension value (1.0 = smooth trend, 2.0 = noise)
regime (series string) : "Trending" when fd < 1.4, "Random" 1.4–1.6, "Choppy" > 1.6
normalised (series float) : fd linearly mapped to 0.0 (trend) – 1.0 (noise)
MomentResult
Rolling moment statistics
Fields:
mean (series float) : Rolling mean
stdev (series float) : Rolling standard deviation
skew (series float) : Rolling skewness (negative = left tail)
kurt (series float) : Rolling excess kurtosis (positive = fat tails / leptokurtic) Library

Indicator

BNS Jump Statistic & RV DecompositionBNS Jump Statistic & RV Decomposition
A jump-detection oscillator that splits realized variance into a continuous (diffusive) component and a jump component, using the bipower variation framework of Barndorff-Nielsen and Shephard. It answers a specific question: how much of recent volatility is everyday noise, and how much is sudden, discontinuous moves?
How it works
Over a rolling window of length N, three quantities are computed from log returns:
Realized Variance (RV) — the sum of squared returns. Captures everything: continuous variance plus any jumps.
Bipower Variation (BV) — the (π/2)-scaled sum of |r_t|·|r_{t−1}|. Asymptotically robust to jumps, so it captures only the continuous part.
Jump component (J) — max(RV − BV, 0), the variance left over after subtracting the continuous estimate.
The Relative Jump (RJ) ratio is J / RV — the share of variance attributable to jumps. Bounded between 0 and 1: zero means all-continuous, one means all-jump.
The BNS z-statistic (ratio form, with the Huang–Tauchen adjustment) tests whether the jump component is statistically significant. It uses tripower quarticity for a robust standard error:
z = √N · RJ / √( θ · max(1, TQ/BV²) ), with θ = π²/4 + π − 5
Under the null of no jumps, z is asymptotically standard normal. Critical values at 1.96, 2.58, and 3.09 correspond to 95%, 99%, and 99.9% confidence.
How to read it
Columns show the RJ ratio. Cool cyan when variance is mostly continuous; amber and rose as the jump share rises.
Smoothed line is a 3-bar EMA of RJ, layered with a soft glow. The line color tracks the regime — useful for spotting persistent jump activity versus one-off spikes.
Reference levels at 20%, 50%, and 80% mark the continuous threshold, the regime boundary, and the extreme zone.
Markers above the pane fire on bars where the BNS test is significant: a circle at 95%, a triangle at 99%, a diamond at 99.9%.
Background tint reflects the regime state (CONTINUOUS, MIXED, or JUMP), with hysteresis so it doesn't flicker on borderline bars.
Status table in the top-right shows the latest RV, BV, jump component, RJ, z-statistic, and current significance level.
Inputs
Window Length — bars used to compute RV and BV. 22 ≈ one trading month on daily. Default 22.
Source — input series. Default close.
Significance thresholds — z-values for 95%, 99%, and 99.9% confidence. Defaults 1.96, 2.58, 3.09.
Regime thresholds — RJ levels marking the continuous and jump regimes. Defaults 0.20 and 0.50.
Display toggles — status table, regime tint, significance markers, and reference levels.
Built-in alerts
Significant Jump (95%) — z crosses above 1.96
Strong Jump (99%) — z crosses above 2.58
Extreme Jump (99.9%) — z crosses above 3.09
Entered Jump Regime
Returned to Continuous Regime
All alerts fire on the rising edge of their event — one notification per transition rather than one per bar while the condition holds.
Notes
The decomposition is a property of the chosen window. Different lengths give different splits; shorter windows are more responsive but noisier. The z-statistic is asymptotic, so very short windows can produce inflated values — treat anything below N=10 with care.
Bipower variation is robust to jumps in theory but sensitive to microstructure noise on very fine timeframes. Daily and 5-minute-and-up tend to behave well.
This is a diagnostic tool, not a signal generator. It tells you when variance is being driven by jumps rather than diffusion.
Five years of work on a trading system left me with dozens of indicators that ultimately didn't earn a place in the final build. They're not failures — they're tools that solved problems I no longer needed solved. So instead of shelving them, I'm publishing the majority of them open-source.
If you're a discretionary trader, take what's useful. If you're a systems builder, the source is yours to dissect, modify, and improve. The best return on five years of work is for it to keep working — for someone.
If you use this script — or part of it — in your own work, please credit the original with a link back to my profile.
Note: these indicators have been updated to Pine Script v6 — some manually, some with AI assistance. Indicator

Transfer EntropyTransfer Entropy
A directional information flow detector for two assets, based on Thomas Schreiber's 2000 formulation. Transfer Entropy measures how much knowing the recent past of one series reduces uncertainty about the next move of another — beyond what the second series' own past already explains. Unlike correlation, it's asymmetric: TE(Y → X) and TE(X → Y) are different quantities, so it can speak to lead-lag in a way correlation can't.
How it works
Log returns from both series are symbolized into binary up/down moves. Over a rolling window of N bars, the script estimates the joint distribution of past pairs and future moves, then computes the conditional mutual information that defines TE in bits.
To separate genuine information flow from finite-sample noise, the same calculation is repeated with the reference series circularly shifted by various offsets within the window — surrogates that preserve each series' marginal distribution but break the temporal coupling between them. The mean of those surrogate estimates is the noise floor, which gets subtracted from the raw value to produce Effective Transfer Entropy (Marschinski & Kantz, 2002).
Both directions — Y→X and X→Y — are computed every bar. The main plot is net flow: inflow minus outflow.
How to read it
The colored area is net information flow.
Above zero in cyan: the reference symbol's recent moves carry useful information about the chart symbol's next move.
Below zero in amber: the chart symbol is leading the reference.
The thinner lines on either side are the individual directional components — inflow plotted positive, outflow plotted as its negative for visual symmetry around zero.
The dotted band is the average noise floor. Flow inside the band is statistically indistinguishable from chance; flow outside it isn't. A faint background tint marks bars where net flow has cleared the band.
Inputs
Reference symbol — the second asset (Y). Information flow is measured between this and the chart symbol (X). Default AMEX:SPY.
Window length — number of triplets feeding the joint-distribution estimate. The 8-cell histogram needs many times that to stabilize; 150–300 is reasonable for most markets. Default 200.
Source — input series for the chart symbol's log returns. Default close.
Significance surrogates — number of circular-shift surrogates averaged into the noise floor. More = more stable significance test at modestly higher compute. Default 3.
Visuals — toggles for net flow, directional flows, noise floor band, glow, and regime tint, plus customizable colors for inflow, outflow, and neutral states.
Built-in alerts
Lead flip — Reference leading — net flow crosses above zero
Lead flip — Chart leading — net flow crosses below zero
Significant inflow — net flow rises above the noise floor
Significant outflow — net flow drops below the negative noise floor
Notes
Pick reference symbols with overlapping trading hours. When one series is closed and the other isn't, the closed series' price forward-fills, which shows up as a run of zero returns and biases the estimate.
The binary symbolization (up vs not-up) is intentionally crude. It's robust, requires no parameter tuning, and matches Schreiber's original formulation — but it discards magnitude. For pairs where the size of a move matters more than its direction, this measure won't capture it.
This is a diagnostic tool, not a signal generator. It tells you which side of a pair is leading.
Five years of work on a trading system left me with dozens of indicators that ultimately didn't earn a place in the final build. They're not failures — they're tools that solved problems I no longer needed solved. So instead of shelving them, I'm publishing the majority of them open-source.
If you're a discretionary trader, take what's useful. If you're a systems builder, the source is yours to dissect, modify, and improve. The best return on five years of work is for it to keep working — for someone.
If you use this script — or part of it — in your own work, please credit the original with a link back to my profile.
Note: these indicators have been updated to Pine Script v6 — some manually, some with AI assistance. Indicator

Session Range Candles + 25% Level# Session Range Candles + 25% Level (SRC25)
** Session Range Candles + 25% Level (SRC25)**, also known as The Essence Model, is a multi-session analysis tool for futures and forex traders who use an ICT-influenced or session-based framework. It consolidates the three primary trading sessions — Asia, London, and New York — into a single, clean overlay that surfaces the session structure, key price levels, and historical behavioural statistics without requiring you to switch timeframes or manually draw levels each day.
The indicator is built around one core idea: that understanding the relationship between how Asia and London sessions form relative to each other, and how New York then behaves within that context, gives you a repeatable, statistical basis for anticipating price delivery. Everything the indicator draws and measures flows from that relationship.
---
## How It Works — Core Concepts
### Session Candles
For each of the three sessions, the indicator builds a composite candlestick representing the full session range — open, high, low, and close — updated live as each session progresses. These session candles are displayed to the right of the current price in the chart's future space, positioned side by side so you can see all three sessions at a glance without cluttering the main chart.
Asia runs 18:00–02:00 ET.
London runs 02:00–08:00 ET.
New York runs 08:00–17:00 ET.
Each candle shows its body (semi-transparent fill), upper and lower wicks, and high/low price labels. The candles are monochrome — direction is read from body position (open vs close) rather than colour, keeping the display uncluttered.
**Candle display rules by session phase:**
During the **Asia session**, only the live Asia candle is shown. London and NY slots are empty — no stale prior-day candles carry over into a new cycle.
During the **London session**, the completed Asia candle is shown alongside the live London candle. The NY slot remains empty until NY opens.
During the **NY session**, all three candles are visible: the completed Asia, the completed London, and the live NY updating in real time.
**Between sessions** (after NY closes and before the next Asia opens), all three completed candles remain visible until the next Asia session starts the cycle fresh.
### The 25% Level
For each completed session candle, the indicator calculates a **25% level** based on the candle's body (the open-to-close range), direction-aware:
On a **bullish candle** (close ≥ open), the level sits in the upper quarter of the body — body top minus 25% of the body range. This marks the zone above which the candle is considered to have delivered into premium.
On a **bearish candle** (close < open), the level sits in the lower quarter of the body — body bottom plus 25% of the body range. This marks the zone below which the candle has delivered into discount.
The 25% level appears in two places. First, as a short horizontal tick extending rightward from the candle body in the session candle panel. Second, as a horizontal line drawn across the main price chart, running from the session's opening bar to the current bar, labelled with the session name and "25%".
The chart line is what traders interact with in real time. It shows where the 25% level sits relative to live price action. The stats table then quantifies — historically and filtered by today's regime — how NY tends to interact with that London 25% level, making it the primary reference for intraday entry context.
### Session H/M/L/O Lines
The indicator also draws up to four horizontal reference lines extending from the session's opening bar to the current bar: the session **High**, the session **Mid** (arithmetic midpoint of high and low), the session **Low**, and the session **Open**. Each is independently togglable and labelled at the right edge. These lines give you the most relevant reference prices from completed sessions without needing to draw them manually.
### Session Open Vertical Lines
At the exact bar where each session opens, a vertical line is drawn extending the full height of the chart, labelled with the session name. These act as visual dividers making session boundaries immediately clear.
---
## Session Structure (Regime)
The core analytical concept driving the statistics table is the structural relationship between Asia and London — specifically, how London's high and low relate to Asia's high and low. The indicator classifies each completed Asia→London pair into one of five regimes, compared wick-to-wick (full session highs and lows, not bodies):
**London Engulfs Asia** — London's high exceeded Asia's high AND London's low went below Asia's low. London expanded beyond Asia in both directions.
**Asia Engulfs London** — Asia's high was at or above London's high AND Asia's low was at or below London's low. London formed entirely within Asia's range.
**London Partial Up** — London's high exceeded Asia's high, but London's low held at or above Asia's low. London broke out to the upside only.
**London Partial Down** — London's low went below Asia's low, but London's high stayed at or below Asia's high. London broke out to the downside only.
**Inside** — London's range fell entirely within Asia's range without touching either extreme.
**Important:** the regime is only confirmed once London has fully closed (i.e. when NY opens). During the Asia and London sessions, the Structure row in the stats table displays "Pending (London open)" to prevent showing an incomplete or misleading classification. The regime shown in the table always refers to the completed Asia→London pair for the current trading day.
---
## Stats Table
The stats table is the indicator's most powerful feature. It answers the question: given today's Asia-London structure, how has New York historically behaved?
### How the History Is Built
Each time a full Asia→London→NY cycle completes — detected at the opening bar of the next Asia session — that cycle's data is committed to a historical array. The number of sessions retained is controlled by the Lookback input (default 252, approximately one trading year). Every percentage shown in the table is derived from this rolling history.
The stats loop filters the history to only those cycles where the Asia-London regime **matches today's current regime**, then calculates frequencies across that filtered subset.
### REGIME Section
**Structure** shows today's Asia-London regime classification, or "Pending (London open)" while London is still active.
**Occurrences** shows how many times this regime has appeared in the lookback window, displayed as N / total sessions analysed. This is your sample size indicator — treat regimes with fewer than 15–20 occurrences with caution.
**Asia Range (avg | cur)** shows the average Asia session range across all sessions in the lookback period, followed by today's Asia range in points.
**London Range (avg | cur)** shows the same for London — historical average versus today's current range in points.
### NY BEHAVIOUR Section
All percentages here are filtered to sessions where the Asia-London regime matches today's.
**NY Bullish** — the percentage of matching sessions where NY closed above its open.
**London High Taken** — the percentage where NY's high reached or exceeded London's session high.
**London Low Taken** — the percentage where NY's low reached or went below London's session low.
**Sequential H+L** — the percentage where NY took both London's high and London's low in the same session. A high reading here suggests NY tends to run both sides of the London range under this regime, implying choppier or more two-sided price action.
**NY Open Above Lon Mid** — the percentage where NY's opening price was above the London session midpoint. This can be read alongside NY Bullish to understand whether the open position tends to predict the close direction.
### Wick Interaction Rows
These rows adapt based on whether today's London session closed bullish or bearish, measuring how NY interacted with the London 25% level. The denominator for all wick rows is the number of bullish (or bearish) London sessions within the regime-matched set — not the total regime count.
**When London closed bullish:**
*NY Stays Above Lon 25%* — the percentage of bullish London sessions (within the regime) where NY's low never traded below the London 25% level. NY respected the upper quarter of the London body throughout the session.
*Wick < Lon 25% → Close Above* — NY wicked below the London 25% level at some point but ultimately closed above it. This is the classic liquidity sweep and recovery pattern — historically the most operationally useful row for identifying long entry context when NY trades into that zone.
*Wick < Lon 25% → Close Below* — NY wicked below the London 25% level and failed to recover. A high reading here would warn that trading below the 25% zone is a bearish continuation signal rather than a sweep.
*Wick < Lon Low → Close Above* — NY extended below London's full session low (a complete sweep of the London low) but closed back above it. A high reading here indicates the London low is frequently swept as a stop-hunt before NY recovers.
**When London closed bearish:**
*NY Stays Below Lon 25%* — NY's high never reached the London 25% level. The bearish delivery was uninterrupted.
*Wick > Lon 25% → Close Below* — NY wicked above the London 25% level but closed below it. The mirror of the bullish sweep pattern — potential short entry context when NY rallies into that zone.
*Wick > Lon 25% → Close Above* — NY wicked above the 25% level and failed to close below it. A high reading signals that moves above the 25% zone tend to hold, warning against fading rallies.
*Wick > Lon High → Close Below* — NY extended above London's full high but closed back below it. A high reading indicates the London high is frequently swept before NY resumes lower.
### TODAY Section
**London 25%** — whether the completed London session's close was above its open ("Above (bull)") or below its open ("Below (bear)"). This determines which set of wick interaction rows is shown.
**NY Open** — whether NY's opening price was above or below the London session midpoint. Updated once NY opens.
**London High** — whether NY has taken London's high yet ("Taken ✓") or not yet ("Pending"). Updates live during the NY session.
**London Low** — whether NY has taken London's low yet ("Taken ✓") or not yet ("Pending"). Updates live during the NY session.
---
## Interpreting the Stats Table
**Step 1 — Check the regime and sample size.** Once London closes, read the Structure row. Then check Occurrences. A regime appearing 40 or more times in 252 sessions gives you a meaningful base rate. Fewer than 15 occurrences is too thin to trade mechanically from.
**Step 2 — Read the directional bias.** NY Bullish gives you the baseline expectation for NY's close direction under this regime. Combine it with NY Open Above Lon Mid — if NY opens above the London midpoint AND NY Bullish is high, the probability of a bullish close is further supported by position. If they diverge, the session is more likely to be contested.
**Step 3 — Set the 25% level expectation.** This is the most operationally useful step. If London closed bullish, look at the three wick rows. A high "Wick < Lon 25% → Close Above" reading (e.g. 60%+) tells you that historically, when NY dips below that upper quarter of the London body, it tends to recover above it. This provides a framework for anticipating where NY might seek liquidity before continuing higher, and gives you a probabilistic basis for a long setup in that zone.
**Step 4 — Assess the London level take rates.** High London High Taken combined with low London Low Taken suggests NY tends to run to the upside of the London range. High Sequential H+L suggests NY routinely sweeps both extremes — in that case, plan for multiple liquidity events rather than a clean one-directional move.
**Step 5 — Track the TODAY section during NY.** Once NY is open, the London High and London Low rows tell you in real time whether the key liquidity levels have been swept. Cross-reference with the historical rates from the behaviour section to assess whether NY is behaving consistently with its historical pattern or deviating from it.
---
## Input Configuration
### Asia, London, and NY Sessions
Each session has an identical set of inputs configured independently:
**Show Candle** enables or disables the session candle in the right-side panel.
**Show Session Open Line** draws a vertical line at the moment the session opens. The line colour, style (Solid / Dashed / Dotted), and width are configurable. An optional label can be shown alongside the line, with size options of tiny, small, or normal.
**Show H/M/L/O Lines** enables the horizontal reference lines on the main chart. Each of the four levels — High, Mid, Low, and Open — has its own toggle so you can show only the levels relevant to your workflow. The line colour, style, and width are shared across the four levels for that session. Label size is also configurable.
**Show 25% Line on Chart** enables the horizontal 25% level line on the main chart. Colour, line style, width, and label size are independently configurable per session.
*Note: NY does not have H/M/L/O or 25% chart lines while the NY session is live — those lines only appear once NY has closed, so they do not interfere with reading the active session.*
### Session Candles (shared settings)
**Offset from chart (bars)** — how far to the right of the last price bar the candle panel begins. Increase this if the candles overlap with your price action or labels.
**Candle width (bars)** — the width of each session candle box measured in bar units. Adjust to taste based on your chart zoom level.
**Spacing between candles** — the gap between adjacent session candles in bar units.
**Body fill transparency** — controls how transparent the candle body fill is. 0 is fully opaque, 100 is invisible. Default 85 gives a subtle fill.
**Show wicks** — enables the upper and lower wick lines on each session candle.
**Show high/low labels** — shows price labels at the high and low of each session candle.
**Label size** — applies to the candle price labels (tiny / small / normal).
**Show 25% tick on candle** — draws a short horizontal tick at the 25% level extending rightward from the candle body in the panel.
### Stats Table
**Show Stats Table** — master toggle for the entire table.
**Lookback (sessions)** — the number of completed Asia→London→NY cycles to include in the historical analysis. Default is 252 (approximately one trading year). Minimum 10, maximum 2000. A longer lookback smooths out regime-specific anomalies but may include structural market conditions that are no longer relevant. A shorter lookback is more reactive but produces smaller sample sizes per regime.
**Table Position** — nine position options covering all corners and edge midpoints of the chart.
**Text Size** — Tiny, Small, or Normal. Small is the default and works well on most monitor sizes.
**Background** — background colour and transparency of the table panel.
**Text colour** — colour applied to all table text.
**Border** — colour of the table cell borders and outer frame.
---
## Chart Elements Summary
**Vertical lines** at each session open, labelled Asia, London, or NY — mark the session boundaries across the full chart height.
**Session candle panel** to the right of price — three side-by-side composite candles showing the OHLC of each session, with wicks, price labels, and 25% ticks.
**Horizontal lines on the main chart** — H/M/L/O and 25% lines from completed sessions, each starting from the session's opening bar and extending to the current bar, labelled at the right edge.
**Stats table** — historical frequency analysis conditioned on today's Asia-London regime, showing NY behavioural tendencies and live session tracking.
---
## Recommended Usage
**Timeframe:** The indicator is designed for intraday charts, typically 1-minute through 15-minute. Session detection is time-based, not candle-count-based, so it works correctly on any timeframe as long as your chart covers the relevant session hours.
**Instrument:** Originally developed for NQ (Nasdaq 100 E-mini Futures). Works on any instrument that trades during the defined session windows. All session times are referenced to the America/New_York timezone.
**Daily workflow:**
During Asia — observe the Asia candle building. The H/M/L/O lines begin plotting from the Asia open. Note the range size relative to the historical average shown in the table.
At the London open — Asia is now complete. The regime begins forming as London trades relative to the Asia range. Monitor London's progress.
At the NY open — London is complete. The regime is confirmed and the stats table populates with the full historical analysis. Read the NY Behaviour section to set your expectations for the session. Note whether NY opened above or below the London midpoint, and note the current London 25% level on the chart.
During NY — use the wick interaction rows to frame entries. Watch the London High and London Low rows in the TODAY section to track whether liquidity levels are being swept. Assess NY's behaviour against the historical tendencies for this regime.
---
## Notes and Limitations
**Sample size matters.** Regimes with fewer than 15–20 occurrences in your lookback window should be treated with caution. The percentages are directionally informative but not statistically robust at small sample sizes. Always read Occurrences before relying on the behaviour rows.
**The 25% level uses candle bodies, not wicks.** It measures where price closed relative to the open, not the full session range. This is intentional — body-based levels represent committed directional delivery, while wicked extremes may represent temporary liquidity events that the body then rejected.
**Regime is confirmed at NY open only.** Showing a regime mid-London-session would compare a developing candle against a completed Asia candle, producing classifications that can change as London continues. The "Pending (London open)" display is by design.
**History is built session by session.** If you add the indicator mid-session, the current incomplete session will not be committed to history until the next Asia open. All statistics reflect only fully completed Asia→London→NY cycles.
**The wick interaction row denominators are direction-matched, not regime-total.** The bullish wick rows divide by the count of bullish London sessions within the regime. The bearish wick rows divide by bearish London sessions. This means these rows cannot be compared directly against NY Bullish or the London take-rate rows, which use the full regime count as their denominator. Indicator

Indicator

Indicator

BicoherenceBicoherence
A higher-order spectral measure for detecting nonlinear phase coupling in price returns. Where the standard power spectrum tells you how much energy sits at each frequency, the bispectrum tells you whether the phases of three frequencies (f₁, f₂, and f₁+f₂) are systematically locked together — a textbook signature of nonlinear dynamics. Bicoherence is the bispectrum normalized to : zero means no coupling at that frequency triple, one means perfect phase locking.
Linear (Gaussian) processes sit near zero across the bifrequency plane. When markets transition into regimes where price is driven by genuine nonlinear dynamics — feedback loops, regime shifts, wave-coupling effects — bicoherence rises, often well before conventional indicators move.
How it works
For each bar, the most recent (K−1)·step + N samples of log returns are split into K Hann-windowed segments of length N=32, with configurable overlap (default 50%, the Welch standard). Each segment is transformed by discrete Fourier transform. Triple products X(f₁)·X(f₂)·X*(f₁+f₂) are accumulated across segments for every (f₁, f₂) in the principal non-redundant domain {1 ≤ f₂ ≤ f₁, f₁+f₂ ≤ N/2}, alongside the magnitude products needed for normalization.
Per the standard direct estimator:
b²(f₁, f₂) = |⟨triple⟩|² / (⟨|X(f₁)X(f₂)|²⟩ · ⟨|X(f₁+f₂)|²⟩)
The script reports the mean and peak of b² across that domain on every bar.
How to read it
The thicker line is mean bicoherence — the average of b² over all 64 pairs in the principal domain. The thinner, dimmer line is peak bicoherence — the maximum across the same domain.
The dotted reference is 1/K, the theoretical mean of b² under a linear-Gaussian null hypothesis. Values that consistently sit above this line indicate genuine nonlinear coupling rather than estimation noise.
Line color shifts from cyan (low coupling) through deep purple (high coupling). A faint background tint marks bars where peak bicoherence exceeds 0.7 — the regime where at least one frequency triple is showing exceptional phase locking.
Inputs
Segments (K) — number of Hann-windowed sub-windows averaged per bar. More segments produce a smoother, less variance-prone estimate but require more history (history needed = (K−1)·step + N). Default 4.
Segment overlap — overlap between consecutive segments. 50% is Welch's recommendation and the default.
Source — input series for the log-return calculation. Default close.
Compute over last N bars — Pine has a 40-second runtime budget per script. Bicoherence is heavy, so the calculation is restricted to recent history. Default 1500. Lower this if you hit time-outs.
Visuals — toggles for peak line, baseline reference, glow, and regime tint, plus customizable colors for low/high coupling, peak, and neutral states.
Built-in alerts
Significant nonlinearity — mean bicoherence crosses 1.5× the linear-Gaussian baseline
Strong phase coupling — peak bicoherence crosses 0.5
Extreme phase coupling — peak bicoherence crosses 0.7
Returning to linearity — mean bicoherence drops back below the baseline
Notes
The FFT length is fixed at N=32 — enough for 16 frequency bins below Nyquist while keeping the DFT and triple-product accumulation tractable inside Pine's runtime budget.
Bicoherence assumes a well-mixed input series. Long stretches of zero returns from non-trading hours can produce spurious low-frequency coupling, so prefer active sessions when interpreting the result.
This is a diagnostic tool, not a signal generator. It tells you whether returns are exhibiting nonlinear structure.
Five years of work on a trading system left me with dozens of indicators that ultimately didn't earn a place in the final build. They're not failures — they're tools that solved problems I no longer needed solved. So instead of shelving them, I'm publishing the majority of them open-source.
If you're a discretionary trader, take what's useful. If you're a systems builder, the source is yours to dissect, modify, and improve. The best return on five years of work is for it to keep working — for someone.
If you use this script — or part of it — in your own work, please credit the original with a link back to my profile.
Note: these indicators have been updated to Pine Script v6 — some manually, some with AI assistance. Indicator

Indicator
