RSI Probability Matrix [ChartPrime]RSI Probability Matrix
🔶 OVERVIEW
Traders frequently rely on rigid, fixed overbought and oversold thresholds for the Relative Strength Index, ignoring how historical price action actually responds at different momentum levels. The RSI Probability Matrix introduces a statistical learning engine to your charts. It tracks and measures real-time trade outcomes across 10-point RSI brackets, turning historical momentum reactions into actionable win-rate probabilities.
Instead of guessing whether an overbought or oversold signal holds weight, this indicator dynamically evaluates success and failure rates using an ATR-based target and stop-loss matrix.
🔶 HOW IT WORKS
The indicator executes its statistical and tracking workflow through a multi-stage architecture:
Dynamic Momentum Engine: Calculates a standard RSI and smoothed signal line pair, backed by an Average True Range (ATR) volatility measurement to size structural targets and stops.
Real-Time Trade Tracking Array: Maintains live arrays spanning all 101 RSI index values (0 to 100), recording historical win and loss outcomes whenever buy or sell crossover triggers are hit.
ATR-Based Risk Framework: When an oversold buy or overbought sell signal triggers, the engine projects dynamic target and stop-loss levels based on a custom multiplier of the current ATR value.
Probability Matrix Dashboard: Aggregates the tracked data into 10-point bracket intervals, calculating real-time win percentages for both buy and sell directions across the entire chart history.
🔶 KEY FEATURES
Statistical Matrix Table: A clean, configurable dashboard displaying detailed trade counts and directional win probabilities broken down across structured RSI bands.
Automated Signal & Outcome Markers: Pins clear entry badges onto the chart along with success (✅) or failure (❌) markers when trades hit their target or stop parameters.
Gradient Color Customization: Fluidly shifts RSI line colors across customizable bullish and bearish palettes depending on prevailing momentum zones.
Flexible Target Management: Full control over ATR lookback periods, multiplier thresholds, and overbought/oversold trigger boundaries to fit your strategy.
🔶 TRADING APPLICATIONS
Probability-Weighted Entries: Before taking a trade at a specific RSI level, check the dashboard matrix to see the historical win percentage for that exact momentum bracket. Only take setups backed by favorable statistical odds.
Objective Risk-to-Reward Execution: Utilize the automated ATR target and stop lines to enforce disciplined trade management, allowing the probability engine to accurately record wins and losses.
Momentum Exhaustion Filtering: Combine overbought or oversold crossovers with the matrix summary totals to identify which RSI zones hold the strongest historical defense from institutional participants.
🔶 SETTINGS
Indicator Settings (RSI Length / Signal / OB-OS Levels): Controls the core lookback periods and the boundary thresholds required to trigger buy and sell signals.
Target & Stop Settings (ATR Length / Multiplier): Adjusts the volatility distance used to calculate structural profit targets and stop-loss zones.
Dashboard Settings (Visibility / Position / Size): Configures the placement and layout of the real-time statistical probability matrix table on your workspace.
🔶 CONCLUSION
The RSI Probability Matrix removes the guesswork from momentum trading. By dynamically tracking and grading historical trade success across customized RSI bands, it gives you a data-driven edge built entirely on real market feedback. Indicator

HTF Log-Regression Volume Profile [BigBeluga]🔵 OVERVIEW
The HTF Log-Regression Volume Profile is an advanced technical indicator created by BigBeluga to map higher-timeframe logarithmic regression channels combined with an integrated volume profile distribution. Traditional volume profiles are often fixed to standard horizontal ranges or static session boxes that fail to capture curving price trends and logarithmic growth dynamics. In order to provide a solution to this problem, this indicator calculates adaptive higher-timeframe sessions using logarithmic regression curves and standard deviation boundaries, plotting internal volume histogram bins and Point of Control (POC) lines directly onto the chart.
The indicator aims to visualize institutional volume distribution, equilibrium pricing, and structural value areas across multi-bar sessions. The core element of its calculation involves evaluating logarithmic regression slope and intercept metrics alongside session standard deviations defined as:
= f_log_regression(close, htf_length)
float deviation = ta.stdev(close, htf_length)
where slope and intercept establish the curving regression baseline, and deviation dictates the channel width for the volume profile bounds. Higher values of bin counts and channel width multipliers allow the indicator to filter out minor market noise and isolate major high-volume structural nodes.
🔵 FEATURES
The system utilizes a multi-layered matrix structure to provide actionable market intelligence:
1 — Higher-Timeframe Adaptive Engine
Auto HTF Resolution: Automatically adapts higher-timeframe sessions based on the chart's current resolution or allows manual session customization.
Session Tracking & History: Maintains active session boundaries while archiving historical finished sessions up to a user-defined limit.
2 — Logarithmic Regression Channels & Projections
Regression Bounds: Plots session high, low, and equilibrium midlines curved along a logarithmic regression formula via math.exp(intercept + slope * htf_length) .
Level Extensions: Projects session boundaries and midlines forward into future bars using configurable extension limits.
3 — Integrated Volume Profile & POC Tracking
Horizontal Volume Bins: Projects dynamic volume profile histograms inside the regression channel using custom polylines and color-coded delta metrics.
Point of Control (POC): Highlights the highest-volume price node within the active session via a dedicated POC line and provides an interactive statistics dashboard box.
🔵 HOW TO USE
Apart from the basic visualization of regression channels, this tool can also act in alternative ways to support decision-making:
Identify Value Areas via Volume Profile: Observe the horizontal volume bins and the Point of Control (POC) line to spot where the heaviest volume concentration occurred during the higher-timeframe session.
Trade Channel Rejections: Use the upper and lower logarithmic regression boundaries and their forward extensions as dynamic support and resistance zones.
Monitor Buying and Selling Pressure: Check the integrated statistics label displaying buy volume, sell volume, and net delta percentage to gauge order flow dominance within the active session.
🔵 NOTES
Why this implementation is unique:
It merges logarithmic regression channels with an internal volume profile distribution across higher-timeframe sessions.
The dynamic polyline volume profile engine automatically adapts bin widths to curving regression slopes.
The script is fully optimized for Pine Script version 6, utilizing advanced user-defined types, custom arrays, and polyline rendering for maximum performance.
Indicator

Gaussian Filter Trend [QuantAlgo]🟢 Overview
The Gaussian Filter Trend passes price through a multi-pole Gaussian filter and holds the result inside an adaptive volatility deadband, producing a stepped trend path that advances only once a move has cleared the band. That band is sized by an Efficiency Ratio, tightening when price travels directionally and widening through chop, so the line tracks sustained moves and sits still through noise. Around that path, a star field orbits at two volatility-scaled radii that fade with distance, echoing the decay of the filter's own weighting and making the current trend distinctly recognizable at a glance on any instrument or timeframe.
🟢 How It Works
The indicator's core methodology combines two mechanisms: a cascaded Gaussian filter that smooths the source series, and an efficiency-driven deadband that governs when that smoothed value is permitted to move the trend line.
First, the selected source is passed through one to four cascaded single-pole stages. A beta term derived from the filter length and the pole count sets the smoothing coefficient. Because pole count enters that calculation directly, adding poles rescales the filter response rather than layering more averaging onto the same curve:
beta = (1 - math.cos(2 * math.pi / length)) / (math.pow(1.414, 2.0 / poleCount) - 1)
alpha = -beta + math.sqrt(beta * beta + 2 * beta)
Next, efficiency is measured by comparing net directional movement against the total distance traveled over the efficiency window. The ratio moves toward one when travel is more directional and toward zero when price covers ground without net progress. It is then smoothed, so the deadband width is less likely to shift sharply from one bar to the next:
efficiency_ratio = path_length == 0 ? 0.0 : net_move / path_length
smoothed_efficiency = ta.ema(efficiency_ratio, efficiency_smooth)
The smoothed reading blends between a wider chop multiplier and a tighter trend multiplier, and that result scales Average True Range into the deadband width. Higher readings pull the envelope in, so the line can follow a move more closely. Lower readings push it out, which is intended to reduce flips in conditions where they are more likely. Disabling Adaptive Width bypasses the blend and applies a single fixed multiplier:
width_multiplier = adaptive_width ? chop_multiplier + (trend_multiplier - chop_multiplier) * smoothed_efficiency : fixed_multiplier
trend_width = ta.atr(atr_length) * width_multiplier
Finally, the trend line carries its previous value forward and steps only when the envelope has moved past it. It drops when the upper band falls below the current level and rises when the lower band climbs above it, producing a stepped path rather than a continuous curve:
if upper_band < trend_line
trend_line := upper_band
if lower_band > trend_line
trend_line := lower_band
A persistent direction state records the last step and carries it through flat segments, so the line color, star field, bar coloring and alerts all read from the same value rather than diverging while the line is stationary. The star field orbits that path at a distance scaled to recent average bar range, spreading as ranges expand and drawing in as they compress, so the trend and the volatility it is being measured against are visible in one read.
🟢 Signal Interpretation
▶ Bullish Trend (Long/Buy): When the lower band climbs above the trend line, the line steps higher and the indicator enters bullish state. The trend line and star field switch to the bullish color. This condition identifies potential long or buy opportunities and remains active until the upper band falls below the line and confirms a bearish step.
▶ Bearish Trend (Short/Sell): When the upper band falls below the trend line, the line steps lower and the indicator enters bearish state. The visual elements switch to the bearish color. This condition identifies potential short or sell opportunities and holds until the lower band climbs above the line and confirms a bullish step.
▶ Flat Path (Hold): When price stays inside the deadband, neither band displaces the line and it holds level. Color does not change, so the prior state is carried rather than reconfirmed. Extended flat runs indicate the efficiency reading has widened the band against choppier conditions, and the state resolves only when one side of the envelope clears the line.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover a range of trading styles and timeframes. "Default" uses four poles over a fourteen bar window for a balanced configuration aimed at swing trading on 1-hour and daily charts. "Fast Response" shortens the filter length and drops to two poles for a tighter path on 5-minute to 1-hour charts, which may suit intraday work at the cost of more frequent steps in choppier conditions. "Smooth Trend" lengthens the filter and widens the chop multiplier for a steadier baseline on daily and weekly charts, aimed at position trading. Selecting any preset other than Default overrides every Gaussian Filter and Trend Width input beneath it.
▶ Built-in Alerts: Three alert conditions support automated monitoring of trend transitions. "Bullish Trend Signal" fires on the bar the direction state flips to bullish. "Bearish Trend Signal" fires on the bar it flips to bearish. "Any Trend Change" triggers on either transition for traders who want a single unified alert regardless of direction. All alerts include the exchange, ticker, and timeframe in the message for immediate context.
▶ Visual Customization: Six color presets, Custom, Classic, Aqua, Cosmic, Cyber, and Neon, provide coordinated bullish and bearish color pairings suited to different chart themes and personal preferences. Selecting Custom exposes independent color pickers for both states, alongside an adjustable neutral color used during the initial warmup before the first directional step. Line width is configurable from one for a minimal look up to eight for a heavier path, and the star field toggles separately from the line so either element can be displayed on its own. Optional bar coloring and background shading tint the candles and chart field with the active trend color at configurable transparency levels, reflecting the current state without reading the line directly.
Indicator

Robust Regression Residual Bands [Pineify]Robust Regression Residual Bands
Overview
This overlay fits a rolling line while bounding influence from unusual closes. It shows a robust center, two MAD shells, confirmed extremes, and an optional dashboard. It is context, not a forecast.
Problem Definition
Least-squares channels and standard deviation magnify large errors. One gap, wick, or bad print can rotate the line and widen its bands, changing both the reference and the meaning of “far.” Short windows add noise; long ones preserve distortion. The invariant is that ordinary observations define the path, extremes stay visible, and their influence remains bounded.
Design Rationale
Regression stays because slope and residual distance answer different questions. Finite Huber-style refits replace unrestricted influence: residuals inside a threshold keep full weight; those outside receive progressively less. Hard deletion was rejected because values switch abruptly at a cutoff. Final scale uses median absolute deviation (MAD) times 1.4826. MAD resists isolated extremes but is less efficient for Gaussian errors. Two passes balance refreshed weights with bounded workload; users may select one to three.
Key Features
Rolling regression with bounded influence refits.
Two shells sized from final residual MAD.
Center color for normalized slope.
Confirmed outer-entry diamonds.
Optional bar color and dashboard for residual z, slope/MAD, scale, window, and passes.
How It Works
Each bar loads a chronological rolling window and fits an equal-weight line. It finds every residual, their median, and median absolute distance from that median. MAD times 1.4826 becomes robust scale; minimum tick prevents zero division.
Each distance is compared with clipping threshold times scale. Inside values keep weight 1. Outside values receive threshold divided by distance, smoothly capping influence. The line is refitted for the selected passes; residual median and MAD are then recomputed. Displayed center is the newest fit plus median residual.
Bands equal center plus or minus selected MAD multiples. Residual z divides current distance by scale; slope divided by scale controls color. A full window without missing data is required. Open-bar values can change; markers and alerts require confirmation.
How Multiple Indicators Work Together
These are causal stages, not unrelated indicators. Regression supplies direction but needs clipping to limit leverage. Clipping needs scale, and MAD prevents the same extreme from dominating it. Final residual measures price against the stabilized path; normalized slope separates direction from dispersion. Without refitting, bands inherit a tilted center; without scale, distance is not comparable. All visuals expose one model.
Trading Ideas and Insights
A confirmed outer entry means the close is unusual relative to current path and scale; it does not imply reversal. Alignment with strong slope can describe expansion, while repeated extremes with flattening slope can motivate a balance review. Alternating center crosses expose noise. Compare states with structure, liquidity, events, and risk controls. The script provides no entries, stops, sizing, or expected returns.
Unique Aspects
The contribution couples bounded influence refits with a median-centered MAD field. Common channels let an extreme affect slope and width through squared error. Here distance sets a smooth influence cap, the line is rebuilt, and final residuals size the tunnel. Median residual shifts the newest fit instead of assuming zero arithmetic mean. Center is primary, shells encode distance, and amber diamonds encode confirmed entries—not probability.
How to Use
Add it to a standard chart and wait for a full window.
Choose a window matching the horizon and review several regimes.
Read center color as normalized direction and bands as robust distance.
Use the dashboard to compare raw and scale-relative movement.
Alert on confirmed outer entry or center crossing, then apply independent context and risk rules.
Secondary layers can be disabled without changing the model.
Customization
Short windows adapt faster and vary more; long ones smooth more and retain old regimes. Extra refit passes can limit leverage further but cost computation and may underweight a true break. Lower clipping resists extremes sooner; higher clipping approaches ordinary regression. MAD multiples set tunnel thresholds, with a minimum shell gap enforced. Visual layers and palette are independent. Defaults are not universal optima.
Assumptions and Limitations
The model assumes a useful local line and comparable source data. Curves, breaks, gaps, rolls, illiquidity, adjusted history, and non-standard charts weaken it. Robust weights bound influence but cannot label an extreme as error or regime change. Results lag, parameters matter, and small MAD makes flat markets sensitive to the tick floor.
Open-bar values may change. Confirmed alerts still depend on feed and settings. Missing data restarts warm-up. The script has no volume, order flow, higher-timeframe request, future value, pivot, or simulation. It estimates neither reversal probability nor fair value, execution, risk, or profit. Outer distance is deviation, not proof of return.
Conclusion
Bounded refits stabilize rolling path, MAD stabilizes scale, and the tunnel exposes both. Treat distance and direction as lagging context, not a forecast; use independent confirmation.
Indicator

Black-Litterman Allocator [BackQuant]# Black-Litterman Allocator
IMPORTANT: Concept / Educational Implementation
Black-Litterman Allocator is a research and educational concept that implements a practical version of the Black-Litterman portfolio-allocation framework inside TradingView and Pine Script.
It is intended to demonstrate how equilibrium priors, covariance estimates, subjective investor views, view confidence, mean-variance optimization, portfolio constraints, volatility targeting and portfolio backtesting can be combined into one visual allocation model.
It should not be interpreted as an institutional-grade portfolio optimizer, automated investment product, portfolio recommendation, or guarantee that the resulting allocation is optimal.
The outputs depend heavily on:
The selected asset universe.
The chart timeframe.
The covariance lookback.
The quality and synchronization of TradingView price data.
The chosen prior-weight scheme.
Risk-aversion assumptions.
The investor views entered by the user.
The confidence attached to those views.
Portfolio constraints.
Volatility-target settings.
Transaction-cost assumptions.
The optional regime filter.
The default universe and default views are examples for demonstrating the framework. They are not investment recommendations.
The script is best treated as a portfolio-allocation laboratory : a way to study how changing assumptions about equilibrium, risk, correlations and expected returns can propagate through a Black-Litterman-style allocation process.
Overview
Black-Litterman Allocator is a 15-asset cross-asset portfolio model that starts with a neutral portfolio prior, reverse-engineers the expected returns implied by that prior, optionally incorporates up to five investor views, solves for a new posterior allocation, applies portfolio constraints and volatility targeting, and then simulates the resulting portfolio through time.
The model follows a broad sequence:
Collect return history for the selected 15-asset universe.
Estimate an annualized covariance matrix.
Stabilize that matrix using diagonal covariance shrinkage.
Construct a prior portfolio.
Estimate the market risk-aversion parameter.
Reverse-optimize the prior into implied equilibrium returns.
Convert investor views into the Black-Litterman P, Q and uncertainty structure.
Blend the prior with those views to obtain posterior expected returns.
Optionally calculate posterior covariance.
Solve a mean-variance portfolio from the posterior.
Apply availability, short-selling, gross exposure and position-size constraints.
Target a desired portfolio volatility.
Apply additional leverage and gross-exposure caps.
Rebalance periodically.
Track the resulting equity curve and portfolio statistics.
The script also provides detailed visualizations showing:
Prior versus final active weights.
Equilibrium versus posterior expected returns.
The impact of individual views.
Current gross and net exposure.
Portfolio volatility and scaling.
Turnover.
Portfolio equity versus a benchmark.
Drawdown and daily returns.
A broad set of performance and risk statistics.
Why Black-Litterman exists
Traditional mean-variance optimization has an important practical weakness.
The optimizer is extremely sensitive to expected-return estimates.
Suppose several assets have similar volatility and correlation characteristics, but one asset is assigned an expected return only slightly higher than the others.
A mathematical optimizer can interpret that small difference very aggressively and allocate an unrealistic amount of capital to that asset.
Small estimation errors in expected returns can therefore produce very large changes in portfolio weights.
This is one reason unconstrained mean-variance portfolios often produce allocations that appear unstable or unintuitive.
The Black-Litterman framework was developed by Fischer Black and Robert Litterman as a way of approaching the problem from the opposite direction.
Instead of beginning with a set of independently estimated expected returns, the framework begins with an equilibrium portfolio and asks:
What expected returns would make this portfolio mathematically optimal?
Those implied returns become the prior.
Investor views are then introduced as controlled deviations from that equilibrium rather than replacing the equilibrium assumptions entirely.
This creates a useful distinction:
Prior = what the portfolio implies before the investor expresses a view.
Views = where the investor believes equilibrium is wrong.
Posterior = the combined result after balancing both sources of information.
That is the central idea behind this indicator.
Important distinction: the prior in this script
In textbook Black-Litterman, the equilibrium portfolio is often represented using market-capitalization weights.
This script is intentionally more flexible.
It provides three different prior schemes:
Equal Weight.
Inverse Volatility.
Manual Weights.
For that reason, the word equilibrium should be interpreted carefully.
If Equal Weight or Inverse Volatility is selected, the prior is a user-selected equilibrium proxy , not necessarily the true global market portfolio.
If Manual Weights is selected and the user enters representative market-cap or benchmark weights, the prior can be made closer to the traditional Black-Litterman interpretation.
This flexibility is intentional because TradingView users may want to study Black-Litterman mechanics without first sourcing a complete set of institutional market-cap weights.
Asset universe
The allocator supports fifteen simultaneously selected assets.
The default universe is designed as a broad cross-asset example containing:
Cryptocurrency.
US equities.
International equities.
Precious metals.
Energy.
The US dollar.
Long-duration Treasury exposure.
The default list includes assets such as Bitcoin, Ethereum, Solana, major equity indices, gold, silver, oil, DXY and TLT.
Every symbol can be replaced by the user.
This allows the framework to be adapted to:
Global macro portfolios.
Equity-sector portfolios.
Cryptocurrency portfolios.
ETF portfolios.
Multi-asset portfolios.
However, all assets should represent actual price series .
Market-capitalization series, synthetic quantities or unrelated non-price data should not be inserted as if they were tradable asset prices, because the resulting returns would contaminate the covariance matrix and portfolio calculations.
Data availability protection
A multi-asset allocator has a specific problem when some assets have shorter histories than others.
Suppose fourteen assets have ten years of data but the fifteenth asset was only listed six months ago.
If missing values are simply converted into zeros, the new asset may appear to have:
Almost no volatility.
Artificially stable returns.
Artificial correlations.
This is especially dangerous when using inverse-volatility weighting, because an asset with incorrectly measured near-zero volatility could receive a very large prior allocation.
The script protects against this by maintaining a separate data-availability state for every asset.
An asset is only admitted into the active universe once it has accumulated at least one complete covariance lookback of valid price history.
Until then:
Its active mask remains disabled.
It receives no prior weight.
It receives no optimized weight.
Views referencing it are ignored.
The allocation table displays it as having no usable data.
This makes the universe dynamic.
A newly listed asset can eventually become active once enough genuine history has accumulated.
Return calculations
The allocator uses two forms of return data for different purposes.
Log returns
Log returns are used for covariance estimation:
Log Return = ln(Price / Previous Price)
These are stored in a rolling history matrix.
Simple returns
Simple returns are used when compounding the simulated portfolio:
Simple Return = Price / Previous Price - 1
This distinction is deliberate.
Log returns are convenient for statistical covariance calculations, while simple returns are appropriate for directly multiplying portfolio wealth through time.
Rolling return-history matrix
The script maintains a rolling matrix containing return history for all fifteen assets.
Each row represents a historical bar and each column represents one asset.
Once the requested covariance lookback has been collected, the matrix acts as the input for the covariance engine.
Rather than recalculating years of historical data from scratch on every bar, the script operates the history as a rolling buffer.
The full Black-Litterman calculation is also performed only on rebalance events rather than continuously.
This is important because:
Covariance estimation is computationally expensive.
Matrix multiplication is expensive.
Matrix inversion is expensive.
TradingView imposes execution limits.
The indicator therefore approximates how a real asset-allocation process is normally operated: weights remain relatively stable between scheduled portfolio reviews and are recomputed at discrete intervals.
Covariance matrix
The covariance matrix is one of the central inputs to the entire model.
For N assets, covariance produces an N × N matrix.
The diagonal contains the variance of each asset.
The off-diagonal entries contain covariance between pairs of assets.
Conceptually:
Positive covariance means two assets tend to move in the same direction.
Negative covariance means they tend to move in opposing directions.
Covariance near zero suggests weaker linear co-movement.
The portfolio does not consider the risk of each asset independently.
Instead, portfolio risk depends on:
Individual asset volatility.
Portfolio weights.
The covariance relationships between every pair of assets.
This is why diversification cannot be measured simply by counting positions.
Ten highly correlated assets may behave more like one large risk exposure than ten independent exposures.
Covariance Lookback
The Covariance Lookback controls how many bars are used to estimate the covariance matrix.
Shorter windows:
Adapt more quickly.
Reflect recent correlation changes.
Contain fewer observations.
Produce noisier covariance estimates.
Longer windows:
Provide more observations.
Create more statistically stable estimates.
Adapt more slowly when correlations change.
This parameter is particularly important when the number of assets is large relative to the number of observations.
With fifteen assets, an extremely short covariance window can create a poorly conditioned or nearly singular matrix.
That can make matrix inversion unstable and produce extreme portfolio weights.
Annualization
The covariance matrix is annualized using the Trading Days per Year input.
The script supports:
252 days.
365 days.
252 is generally appropriate for traditional financial markets operating primarily on weekdays.
365 may be more appropriate for a crypto-only daily portfolio.
Mixed universes require judgement because crypto trades continuously while many traditional markets do not.
The annualization setting affects:
Covariance.
Volatility.
Return statistics.
Risk-aversion estimates.
It should therefore be selected consistently with the universe and timeframe being studied.
Covariance shrinkage
Raw sample covariance matrices can be noisy.
This is particularly problematic when:
The lookback is short.
There are many assets.
Several assets are highly correlated.
Market relationships change rapidly.
The script applies a simple fixed-coefficient shrinkage toward a diagonal covariance target.
The diagonal variances are retained.
The off-diagonal covariance terms are multiplied by:
1 - Shrinkage
Therefore:
Shrinkage = 0
leaves the sample covariance relationships largely unchanged.
Shrinkage = 1
removes the off-diagonal covariance terms and effectively treats the assets as uncorrelated for optimization purposes.
Intermediate values partially reduce estimated correlations.
This is best described as Ledoit-Wolf-style diagonal shrinkage , not as a full automatic Ledoit-Wolf estimator.
A true Ledoit-Wolf implementation estimates an optimal shrinkage intensity statistically.
Here, the user directly controls the shrinkage coefficient.
Why shrinkage can help
Portfolio optimization involves matrix inversion.
If covariance estimates are noisy, the inverse matrix can amplify those errors dramatically.
Shrinkage intentionally sacrifices some estimated correlation detail in exchange for greater numerical stability.
A moderate amount of shrinkage can therefore:
Reduce unstable allocations.
Reduce sensitivity to short-term correlation noise.
Improve matrix conditioning.
Too much shrinkage can also remove genuine diversification information.
The parameter is a bias-versus-variance trade-off.
Safe matrix inversion
Black-Litterman requires several matrix inversions.
Matrices can become singular or nearly singular when:
Assets are highly correlated.
Lookbacks are too short.
Data is incomplete.
The script checks whether the matrix is square and sufficiently non-singular before using a standard inverse.
When necessary, it falls back to a pseudo-inverse.
This does not magically make poor data reliable, but it prevents a singular matrix from immediately destroying the calculation.
A pseudo-inverse should still be interpreted cautiously because the underlying portfolio problem may be poorly conditioned.
Prior portfolio
Before Black-Litterman can estimate equilibrium returns, it requires a prior portfolio.
Three schemes are provided.
Equal Weight
Every active asset receives an equal allocation:
Weight = 1 / Number of Active Assets
This is the simplest prior.
It expresses no preference based on:
Market capitalization.
Volatility.
Expected return.
Its strength is simplicity.
Its weakness is that it assumes every asset deserves the same capital allocation regardless of risk.
Inverse Volatility
Inverse Volatility gives greater prior weight to assets with lower historical volatility.
Conceptually:
Raw Weight ∝ 1 / Volatility
The weights are then normalized.
This produces a risk-oriented prior rather than a capital-oriented prior.
Lower-volatility assets receive more weight.
Higher-volatility assets receive less.
This can be useful for diversified macro portfolios, but it has an important implication:
the quietest asset may dominate the prior.
For example, a bond or currency exposure may receive much more prior weight than cryptocurrency simply because its realized volatility is lower.
This is not a bug.
It is the direct consequence of using inverse volatility as the prior definition.
Manual Weights
Manual mode allows the user to enter fifteen raw numbers corresponding to the fifteen selected assets.
The entries are normalized automatically.
This means the values do not need to sum to 100.
The user can enter:
Percentages.
Market capitalizations.
Benchmark weights.
Relative notional values.
Only their proportions matter.
If the intention is to approximate traditional Black-Litterman market equilibrium, Manual Weights can be used to supply actual or approximate market-cap weights.
Reverse optimization
Once the prior weights are known, the model derives the returns that would make those weights consistent with mean-variance equilibrium.
The implied equilibrium excess-return vector is:
Pi = Delta × Sigma × Wprior
where:
Pi = implied equilibrium excess returns.
Delta = risk-aversion coefficient.
Sigma = covariance matrix.
Wprior = prior portfolio weights.
This is called reverse optimization .
Normal portfolio optimization asks:
Given expected returns, what weights should I own?
Reverse optimization asks:
Given the portfolio weights, what expected returns would justify owning them?
That reversal is one of the key ideas behind Black-Litterman.
Why implied returns matter
Expected returns are difficult to estimate directly.
Historical averages are noisy.
Forecast models disagree.
Small errors can create enormous portfolio changes.
Black-Litterman instead begins from a portfolio that the user considers a reasonable neutral starting point.
The model then backs out the expected returns consistent with that portfolio.
These implied returns become the equilibrium prior against which investor opinions are expressed.
Risk aversion: Delta
Delta controls the relationship between expected return and risk.
Higher Delta means:
Greater assumed aversion to risk.
A larger equilibrium return requirement for a given covariance structure and prior.
Lower Delta implies less risk aversion.
The script provides:
Auto (Implied).
Manual.
Manual Delta
Manual mode allows the user to directly select the risk-aversion coefficient.
This is useful when:
A stable assumption is preferred.
The user is reproducing an external Black-Litterman study.
The portfolio prior is known but a particular Delta is desired.
Auto Delta
Auto mode estimates Delta from the current prior portfolio.
The script estimates:
Prior portfolio variance.
An annualized return estimate over the covariance horizon.
The selected risk-free rate.
It then forms an implied risk-aversion estimate from excess return relative to variance.
The value is constrained to a practical range to prevent extreme estimates from destabilizing the optimizer.
This Auto mode is a practical implementation choice for the concept.
It should not be interpreted as a uniquely correct market risk-aversion estimate.
Tau: uncertainty in the prior
Tau is one of the most important Black-Litterman parameters.
It scales uncertainty in the equilibrium prior.
Conceptually:
Prior Uncertainty = Tau × Sigma
A smaller Tau implies stronger confidence in the equilibrium-return prior.
A larger Tau gives the model more freedom to move away from the prior when investor views are introduced.
In practical terms:
Smaller Tau
Makes the prior harder to move.
Reduces the effect of views.
Larger Tau
Increases prior uncertainty.
Allows views to exert more influence.
Tau should not be interpreted in isolation.
Its effect interacts with:
The covariance matrix.
View confidence.
View direction.
The number of views.
Investor views
The script supports up to five simultaneous investor views.
Each view contains:
A view type.
Asset A.
Optional Asset B.
Expected return Q.
Confidence.
Each view can be:
Off.
Absolute.
Relative.
The expected-return input is interpreted as an annualized expected return or annualized relative return .
Absolute views
An absolute view expresses an opinion about one asset.
For example:
“Asset A will return 10% annually.”
In matrix notation, the corresponding row of the P matrix contains:
+1 for Asset A.
0 for all other assets.
Q then contains:
0.10
for a 10% annual view.
Relative views
A relative view expresses one asset relative to another.
For example:
“Asset A will outperform Asset B by 5% annually.”
The corresponding P row contains:
+1 for Asset A.
-1 for Asset B.
0 elsewhere.
Q becomes:
0.05
This does not necessarily mean Asset A itself must return +5%.
It means:
Expected Return A - Expected Return B = 5%
Relative views are one of the most useful features of Black-Litterman because investors are often more confident about relative relationships than exact absolute returns.
It may be easier to hold the view:
“Gold will outperform equities.”
than:
“Gold will return exactly 12.4%.”
P matrix
The P matrix describes which assets each investor view references.
Each row corresponds to one active view.
Each column corresponds to one of the fifteen assets.
An absolute view creates one non-zero exposure.
A relative view creates a long-versus-short pair.
P therefore translates a verbal market opinion into portfolio mathematics.
Q vector
Q contains the expected return associated with each view.
For absolute views:
Q = expected annual asset return.
For relative views:
Q = expected annual outperformance of A relative to B.
The relationship:
P × Returns = Q
defines what the investor believes.
View confidence
Black-Litterman does not require every opinion to be treated as equally reliable.
Each view therefore receives a confidence value.
Confidence controls its uncertainty.
The basic principle is:
Low confidence = large view uncertainty.
High confidence = small view uncertainty.
The script converts intuitive percentage confidence into an Omega uncertainty term using a confidence mapping related to the Idzorek-style approach to expressing subjective confidence. User-specified confidence was developed precisely to make the otherwise difficult view-uncertainty input more interpretable.
Omega
Omega represents uncertainty in the views.
For each active view, the script first measures the variance of the corresponding view portfolio using:
P × TauSigma × P'
It then scales that variance according to confidence:
Omega = ((1 - Confidence) / Confidence) × View Variance
This has intuitive behaviour.
High confidence
If confidence approaches 100%:
(1 - c) / c approaches zero.
Omega becomes small.
The view receives substantial influence.
Low confidence
If confidence approaches zero:
(1 - c) / c becomes very large.
Omega becomes large.
The view has little effect.
The script bounds confidence away from exactly zero and one for numerical stability.
Why confidence matters
Suppose two investors both believe Bitcoin will outperform gold by 10%.
Investor A has 90% confidence.
Investor B has 20% confidence.
Their view Q is identical.
But their portfolio allocations should not necessarily be identical.
The confidence parameter allows the same directional opinion to produce very different posterior tilts.
This is one of the most useful parts of Black-Litterman.
It separates:
What you believe.
How strongly you believe it.
View disagreement: Q - PΠ
The Views table displays:
Q - PΠ
This measures how far the investor view differs from the equilibrium prior.
Suppose equilibrium already implies that Asset A will outperform Asset B by 8%.
If the user enters a relative view of 9%, the disagreement is only 1%.
The posterior may therefore change only slightly.
If the user instead enters 20%, the disagreement with equilibrium is much larger.
The same confidence level will then produce a much larger posterior adjustment.
This quantity is extremely useful because it shows that the impact of a view depends not only on the view itself, but on how different it is from what the prior already expects.
Posterior expected returns
Once P, Q and Omega have been constructed, the script calculates the Black-Litterman posterior expected-return vector.
Conceptually:
Posterior = Prior + Confidence-Weighted Adjustment
The full adjustment depends on:
Tau.
Sigma.
P.
Q.
Omega.
The disagreement Q - PΠ.
The model therefore does not simply overwrite the expected return of the named asset.
The adjustment can propagate across the entire asset universe through covariance relationships.
This is a fundamental feature of Black-Litterman.
If two assets are strongly related, a view about one may alter the posterior expectation of the other even if that second asset was not explicitly named.
Why views propagate
Suppose the user enters a strong bullish view on one equity index.
If several other equity indices are highly correlated with it, the covariance matrix tells the model that those assets are economically related.
The posterior adjustment therefore does not exist in isolation.
This means:
Views influence related assets.
Portfolio effects depend on covariance.
The same view can produce different tilts under different correlation regimes.
That behaviour is intentional.
No active views
If no usable views are active:
Posterior expected returns remain equal to the equilibrium prior returns.
The allocation is then driven by:
The prior.
Covariance.
Risk aversion.
Portfolio constraints.
Volatility targeting.
This makes the script useful even without discretionary views.
It can be used to study how the prior portfolio behaves under the optimization and risk-management layers by itself.
Posterior covariance
The script can optionally include the Black-Litterman posterior covariance adjustment.
Investor views introduce uncertainty about expected returns.
The posterior covariance calculation incorporates additional uncertainty associated with combining the prior and the views.
When enabled, the optimizer uses this adjusted covariance matrix.
When disabled, optimization uses the original covariance estimate.
The practical effect is usually more subtle than changing the expected-return vector, but it can affect:
Position sizes.
Diversification.
Volatility estimates.
View-driven tilts.
Portfolio optimization
After calculating posterior expected returns, the script solves a mean-variance allocation.
The unconstrained portfolio is conceptually:
w* = (Delta × SigmaPosterior)^-1 × PiPosterior
This converts posterior return expectations and covariance into portfolio weights.
If:
There are no views.
The prior and covariance are internally consistent.
No constraints alter the result.
the solution tends toward the prior portfolio.
Views create deviations away from that starting point.
Why unconstrained weights can be extreme
Mean-variance optimization can produce very large positive or negative positions.
This happens because matrix inversion magnifies differences between:
Expected returns.
Volatility.
Correlations.
If two assets are highly correlated but have slightly different expected returns, the optimizer may create a large long position in one and a large short position in the other.
Mathematically this can be valid.
Practically it may be unusable.
The script therefore applies several layers of portfolio constraints after the raw solution.
Data mask
Assets without sufficient price history receive zero weight regardless of what the raw optimizer produces.
This prevents incomplete covariance columns from entering the live portfolio.
Long-only mode
When Allow Short Weights is disabled:
All negative optimizer weights are clipped to zero.
The remaining positive positions are then normalized.
This converts the portfolio into a long-only allocation.
The result is no longer the exact unconstrained analytical Black-Litterman solution.
That is expected.
Real portfolios frequently require constraints that alter the theoretical optimum.
Short-enabled mode
When shorting is enabled, negative posterior weights are permitted.
This allows:
Long-short portfolios.
Relative-value expressions.
Negative allocations to assets receiving sufficiently weak posterior expectations.
Gross exposure becomes especially important in this mode because a portfolio can have low net exposure while still carrying substantial absolute risk.
For example:
+150% long.
-50% short.
= 100% net exposure.
= 200% gross exposure.
Gross Exposure
The Gross Exposure input controls the target sum of absolute portfolio weights before volatility targeting.
Gross exposure is:
Gross = Sum of |Weight|
This differs from net exposure:
Net = Sum of Weight
For long-only portfolios, gross and net are normally similar.
For long-short portfolios, they can differ significantly.
Volatility targeting
After the portfolio has been normalized, the script estimates total portfolio volatility using:
Portfolio Variance = w' × Sigma × w
Portfolio Volatility = sqrt(Portfolio Variance)
This is a full covariance-aware portfolio volatility calculation.
It does not simply average asset volatility.
The model then calculates a volatility scaling factor:
Volatility Scale = Target Volatility / Estimated Portfolio Volatility
subject to minimum and maximum limits.
If estimated portfolio volatility is below target:
Exposure can increase.
If estimated volatility is above target:
Exposure is reduced.
Why portfolio volatility matters
Suppose two assets each have 20% volatility.
A 50/50 portfolio does not necessarily have 20% volatility.
If the assets are weakly correlated, portfolio volatility may be much lower.
If they are highly correlated, it may remain close to 20%.
Using:
sqrt(w'Σw)
allows the volatility target to account for diversification.
Target Volatility
Target Volatility defines the desired annualized risk level of the portfolio before later hard caps are considered.
Examples might conceptually include:
A lower target for a defensive multi-asset portfolio.
A higher target for a crypto-focused portfolio.
The setting is not automatically appropriate simply because the portfolio reaches it.
A volatility target does not account for:
Tail risk.
Liquidity.
Gap risk.
Regime changes.
Nonlinear derivatives.
It is one risk-control dimension.
Maximum volatility-target leverage
A very low-volatility portfolio can theoretically require enormous leverage to reach a high volatility target.
The Max Vol-Target Leverage setting prevents this.
For example, if the mathematical scaling factor is 6× but the maximum leverage is 3×:
The model uses no more than 3×.
This protects against explosive leverage during unusually quiet covariance estimates.
Maximum weight per asset
After volatility targeting, every individual position is subjected to a hard position-size cap.
This ordering is important.
If the position cap were applied before leverage scaling, the volatility scaler could simply increase the capped position again.
Applying the cap afterward ensures the final position magnitude cannot exceed the selected maximum.
For example:
Max Weight = 30%
means no individual position can remain above 30% after the volatility scaling stage.
Maximum gross exposure after volatility targeting
After individual caps are applied, the portfolio is also checked against a maximum total gross exposure.
If gross exposure exceeds that maximum, every position is scaled downward proportionally.
This provides a second portfolio-level safeguard.
The result is a hierarchy:
Generate raw Black-Litterman weights.
Apply long/short rules.
Normalize initial gross exposure.
Apply volatility targeting.
Cap individual positions.
Cap final gross exposure.
Why the target may not be reached
The volatility target is not guaranteed to be achieved exactly.
Suppose the model wants to increase portfolio exposure enough to reach 15% volatility.
If doing so would violate:
Maximum leverage.
Maximum asset weight.
Maximum gross exposure.
the constraints take priority.
The resulting portfolio may therefore have volatility below the requested target.
This is intentional.
Risk limits are allowed to override the target.
Rebalancing
The complete optimizer does not run on every bar.
The user selects a Rebalance Every N Bars interval.
For a daily chart:
Approximately 21 bars corresponds roughly to one trading month.
Longer rebalance intervals:
Reduce turnover.
Reduce computation.
Allow allocations to persist longer.
Shorter intervals:
React faster to new covariance and view conditions.
Increase turnover.
Increase computational load.
The covariance matrix and Black-Litterman solve run only on rebalance events.
Forced rebalances
Two events can trigger a solve outside the normal schedule:
The regime filter changes from CASH back to ACTIVE.
The number of assets with sufficient history changes.
This prevents the portfolio from waiting many bars before responding to a material change in state.
Regime filter
The script includes an optional regime filter based on the chart symbol.
The filter compares:
A fast EMA.
A slow EMA.
When the fast EMA is above the slow EMA:
Regime = ACTIVE
When the fast EMA is not above the slow EMA:
Regime = CASH
This filter applies to the chart symbol , not individually to the fifteen assets.
That distinction is important.
If the indicator is placed on SPX, the regime filter reflects SPX.
If it is placed on Bitcoin, it reflects Bitcoin.
The regime state therefore acts as a global risk-on/risk-off switch for the entire portfolio.
CASH regime
When the regime filter turns off:
The live asset weights are flattened to zero.
The strategy stops compounding asset returns while the regime remains inactive.
When the filter turns ACTIVE again:
A new Black-Litterman solve is forced immediately.
The user should therefore choose the chart symbol intentionally if the regime filter is enabled.
Regime filter limitation
A single chart-symbol EMA regime is an intentionally simple overlay on a much more sophisticated cross-asset model.
It should not be confused with a multi-asset economic-regime model.
It answers only:
Is the fast trend of the chart symbol above its slower trend?
The regime layer can have a very large impact on historical results.
Backtests with and without it are therefore testing materially different systems.
Transaction costs
The script calculates turnover on each committed rebalance:
Turnover = Sum of |New Weight - Previous Weight|
The selected transaction-fee rate is then applied to that turnover.
This is more realistic than assuming rebalancing is free.
However, the cost model remains simplified.
It does not separately model:
Bid-ask spread.
Slippage.
Market impact.
Short borrow fees.
Financing costs.
Taxes.
Different fee schedules by asset.
The fee input should therefore be treated as an approximate portfolio-level trading-cost assumption.
Important backtest implementation note
The current implementation charges transaction fees when a new active portfolio is committed during a rebalance.
The transition that flattens the portfolio when the regime filter enters CASH is not separately charged an explicit turnover fee in the current code.
Therefore, backtests using the regime filter may slightly understate transaction costs associated with risk-off exits.
This is one reason the script should be treated as a concept rather than a production execution simulator.
No-lookahead portfolio return handling
The portfolio return for the current bar is calculated using the weights that were already active before the current rebalance solve.
Only after that return has been calculated does a new set of weights become active.
This prevents the optimizer from using newly calculated current-bar weights to capture a return that occurred before those weights could have existed.
This ordering is essential for a meaningful historical simulation.
Prior versus posterior weight chart
One of the main visual components is the paired horizontal weight chart.
Each asset receives two bars:
Prior weight.
Final active portfolio weight.
The prior represents the selected equilibrium starting allocation.
The active portfolio reflects the portfolio after:
Views.
Optimization.
Short constraints.
Gross normalization.
Volatility targeting.
Position caps.
Final gross caps.
Therefore, the visible gap between the bars represents more than the mathematical Black-Litterman posterior alone.
It represents the complete practical allocation change from prior to final active book .
If the regime filter is currently in CASH, the live active weights may be zero.
This distinction is important when interpreting the chart.
Allocation table
The Allocation Table shows each of the fifteen assets with:
Prior Weight.
Post Weight.
Delta Weight.
Equilibrium Expected Return.
Posterior Expected Return.
Prior Weight
The allocation before investor views and final portfolio construction.
Post Weight
The current active portfolio weight after the complete optimization and risk-control process.
Delta Weight
The difference between the active weight and prior weight.
Positive values indicate the asset has been increased relative to the prior.
Negative values indicate it has been reduced.
Equilibrium E
The implied return derived through reverse optimization.
Posterior E
The expected return after the active investor views have been incorporated.
Comparing equilibrium and posterior expected return is often more informative than looking only at weights.
A return expectation can change substantially while the final weight changes only modestly because:
The asset is highly volatile.
It is highly correlated with another holding.
The maximum-weight constraint binds.
Portfolio volatility limits exposure.
Views table
The Views Table shows each active view and includes:
View description.
Q.
Confidence.
Omega.
Q - PΠ.
This allows the user to inspect not only what the view says, but how strongly it conflicts with equilibrium and how uncertain it is.
Two views with identical Q values may have very different portfolio effects if:
Confidence differs.
Covariance differs.
Equilibrium expectations differ.
Current Book table
The Current Book table provides a compact summary of the active portfolio.
It includes:
ACTIVE or CASH regime.
Prior scheme.
Number of active views.
Number of rebalances.
Gross exposure.
Net exposure.
Number of live assets.
Turnover.
Risk-aversion Delta.
Tau.
Estimated portfolio volatility.
Volatility scaling factor.
This table is useful for diagnosing why the allocator currently looks the way it does.
For example:
Large view changes but small weights
may be explained by a tight volatility target or maximum-weight constraint.
Large gross but low net
may indicate significant long-short exposure.
Few live assets
means part of the universe has not yet accumulated sufficient historical data.
Equity curve
The script maintains a simulated portfolio equity curve beginning from the selected Initial Capital.
Initial Capital affects only the scale of the equity curve.
It does not affect:
Weights.
Sharpe ratio.
Volatility.
Portfolio optimization.
The equity curve compounds the historical portfolio returns generated by the active weights.
The line changes colour according to whether equity increased or decreased from the previous bar.
Benchmark Buy & Hold
A benchmark equity curve can be displayed beside the portfolio.
Both curves begin from the same nominal capital.
The benchmark is also used in:
Beta.
Alpha.
The benchmark can be changed independently from the fifteen-asset universe.
For meaningful interpretation, the benchmark should be relevant to the portfolio being studied.
A broad global macro portfolio compared only with SPX is answering a different question from an equity portfolio compared with SPX.
Daily returns
The script can optionally plot the portfolio’s per-bar percentage return.
This is useful for visually inspecting:
Return clustering.
Large gains.
Large losses.
Regime-filter cash periods.
Because it shares the pane with the equity curve, it is generally best viewed separately.
Rolling drawdown
Drawdown is measured relative to the previous portfolio-equity peak:
Drawdown = (Current Equity - Peak Equity) / Peak Equity
The result is negative while the portfolio remains below its historical high.
The visual fill becomes stronger as drawdown deepens.
The Max DD for Scaling input affects only the visual intensity scale.
It does not limit portfolio losses or modify the allocation.
Performance metrics
The metrics table includes a broad range of return and risk statistics.
Net Profit
Percentage change in portfolio equity from initial capital.
Maximum Drawdown
Largest historical peak-to-trough decline in the simulated portfolio.
Win Rate
Percentage of non-zero portfolio-return bars that were positive.
Flat CASH bars are excluded from the win/loss count.
This prevents periods where the portfolio is deliberately inactive from automatically being classified as losing periods.
Annual Mean Return
Arithmetic average per-bar portfolio return multiplied by the selected annualization factor.
This is not identical to CAGR.
Annual Standard Deviation
Per-bar return standard deviation scaled by the square root of the annualization factor.
Variance
Square of annualized standard deviation.
Sharpe Ratio
Measures annualized excess mean return relative to total return volatility using the selected risk-free rate.
Sortino Ratio
Measures return relative to downside-return variability rather than total volatility.
Omega Ratio
Compares the aggregate positive portfolio returns with the magnitude of aggregate negative portfolio returns.
Gain-to-Pain
Compares net return with the aggregate magnitude of negative returns.
CAGR
Compound annual growth rate based on beginning equity, ending equity and elapsed calendar time.
Calmar Ratio
CAGR divided by absolute maximum drawdown.
Beta
Measures covariance of portfolio returns with benchmark returns relative to benchmark variance.
Alpha
Estimates annualized portfolio return in excess of the return implied by its benchmark Beta and selected risk-free rate.
Skewness
Measures asymmetry of the historical portfolio-return distribution.
Positive skew indicates a longer or heavier positive tail.
Negative skew indicates a more pronounced negative tail.
VaR 95th Percentile
The implementation reports the fifth percentile of historical portfolio returns.
It can be interpreted as the lower-tail return threshold associated with approximately the worst 5% of observations.
It is displayed as a return value rather than converting the loss into a positive number.
Conditional VaR
Conditional VaR averages the returns in the lowest 5% tail.
This provides information about the average severity of outcomes beyond the VaR threshold.
Historical VaR and Conditional VaR rely entirely on the observed backtest sample.
They should not be interpreted as guarantees about future tail losses.
Risk-free rate
The selected Risk-Free Rate influences:
Sharpe.
Alpha.
Auto risk-aversion estimation.
Changing it therefore affects both reported performance statistics and potentially the portfolio itself when Auto Delta is enabled.
Understanding prior versus posterior
The most important conceptual visualization in the script is the difference between the prior and posterior state.
Suppose the prior allocation is:
Asset A: 20%
Asset B: 20%
Asset C: 20%
Asset D: 20%
Asset E: 20%
Now suppose the investor enters:
Asset A will outperform Asset B by 8%, with high confidence.
Black-Litterman does not simply add 8% weight to A and remove 8% from B.
Instead, the model asks:
What did equilibrium already imply about A versus B?
How uncertain is the prior?
How confident is the investor?
What is the covariance of the A-minus-B view?
How are A and B related to the rest of the portfolio?
The resulting posterior return adjustment then passes through the optimizer.
The final weights are subsequently modified by the portfolio constraints.
This explains why Black-Litterman allocations can behave very differently from manually applying arbitrary portfolio tilts.
Example: low-confidence relative view
Suppose equilibrium implies:
Expected A return = 8%
Expected B return = 7%
The equilibrium difference is 1%.
The investor believes:
A will outperform B by 5%
but assigns only 20% confidence.
The view disagrees with equilibrium, but Omega is relatively large because confidence is low.
The posterior therefore moves toward the investor view without fully accepting it.
Example: high-confidence relative view
Using the same equilibrium assumptions, suppose confidence is increased to 90%.
Omega becomes much smaller.
The investor view therefore carries much greater influence.
The posterior A-minus-B expected-return spread moves much closer toward the stated view.
The final weights may then shift significantly, subject to risk and portfolio constraints.
Example: view already priced into equilibrium
Suppose the user believes A will outperform B by 5%.
But the equilibrium prior already implies approximately 5%.
Then:
Q - PΠ ≈ 0
There is little disagreement to resolve.
Even a high-confidence view may produce only a small posterior adjustment.
This is an important property of the model.
Black-Litterman does not reward the user simply for entering a strong opinion.
The opinion must differ from equilibrium before it meaningfully changes the posterior.
Absolute versus relative confidence
Absolute views generally require greater confidence in the expected return level itself.
Relative views can be easier to interpret because the user only needs an opinion about the spread between two assets.
For example:
“Equities will return 14%.”
is a stronger forecasting statement than:
“Equities will outperform bonds by 4%.”
Neither is inherently superior.
The model supports both because portfolio managers frequently express views in both forms.
Why the model is useful conceptually
The value of Black-Litterman is not that it discovers the future.
It provides a disciplined method for converting beliefs into portfolio changes.
Without a framework, an investor may say:
“I like gold.”
“I am bearish equities.”
“Bitcoin should outperform bonds.”
but those statements do not specify:
How much the portfolio should change.
How volatility should affect the position.
How correlated assets should respond.
How conviction should change the allocation.
Black-Litterman forces those opinions into a structured portfolio context.
That is what this indicator is intended to demonstrate.
Important implementation difference from institutional Black-Litterman
The script implements the core Black-Litterman mechanics, but several choices are intentionally simplified for TradingView.
These include:
A fixed maximum universe of fifteen assets.
Up to five investor views.
User-selected fixed covariance shrinkage rather than automatically estimated shrinkage intensity.
Equal-weight and inverse-volatility priors in addition to manual market-style priors.
A simplified Auto Delta estimate.
Discrete bar-based rebalancing.
Simplified transaction costs.
A single chart-symbol regime filter.
Historical covariance from TradingView price data.
These choices make the model practical and interpretable inside Pine Script.
They also mean that results should not be compared directly with a production institutional implementation without understanding the differences.
Mixed-market data considerations
Cross-asset portfolios introduce data-alignment problems.
Cryptocurrency trades continuously.
Equities, commodities and bonds have market sessions and holidays.
Different TradingView symbols may also come from different exchanges or data providers.
The covariance matrix assumes the return observations are meaningfully aligned.
Users should therefore be careful with:
Intraday mixed-asset universes.
Assets from incompatible sessions.
Symbols with limited historical coverage.
Synthetic or non-tradable price series.
Daily or broader timeframes are generally easier to interpret for a macro allocation concept.
Backtest limitations
Historical simulation is useful for understanding behaviour, but this should not be treated as proof of future performance.
The backtest does not model every real-world implementation issue.
Examples include:
Bid-ask spreads.
Market impact.
Execution latency.
Portfolio financing.
Borrow availability.
Short borrow costs.
Taxes.
Different trading sessions.
Rebalancing at exact executable prices.
Changes in instrument availability.
Survivorship effects in a manually selected universe.
The model also uses historical covariance as an estimate of future covariance.
Correlations can change abruptly during stress periods.
The most diversified-looking portfolio based on historical data can become much more concentrated in risk when formerly independent assets begin moving together.
No automatic investment views
The script does not create investor views for the user.
Q and confidence are deliberately manual.
This is important because Black-Litterman is a framework for combining beliefs with equilibrium.
It does not tell the investor what those beliefs should be.
Views could theoretically come from:
Macro analysis.
Valuation models.
Momentum models.
Fundamental research.
Quantitative forecasts.
Discretionary judgement.
The quality of the posterior cannot exceed the quality of the assumptions provided to it.
Parameter interaction
Black-Litterman parameters should not be tuned independently.
Several important interactions exist.
Tau + Confidence
Both influence how aggressively views move the posterior.
Higher prior uncertainty combined with high view confidence can create strong posterior changes.
Covariance Lookback + Shrinkage
A short noisy covariance window may require more shrinkage for stability.
A long sample may tolerate less.
Target Volatility + Leverage Caps
A high volatility target may have little effect if maximum leverage or gross exposure is restrictive.
Views + Max Weight
A strong posterior preference for one asset may never appear fully in the active portfolio if the asset cap is binding.
Shorts + Gross Exposure
Allowing shorts can materially increase gross exposure even when net exposure looks conservative.
Rebalance Frequency + Fees
Frequent optimization allows faster adaptation but increases turnover and assumed trading cost.
Prior selection
The choice of prior is not cosmetic.
It changes the equilibrium return vector itself.
The same investor views can therefore produce different posterior portfolios depending on whether the starting prior is:
Equal Weight.
Inverse Volatility.
Market-like Manual Weights.
Users studying the framework should therefore treat prior construction as one of the primary model assumptions.
Suggested research workflow
A useful way to study the indicator is:
Begin with no investor views.
Choose a prior.
Observe the implied equilibrium returns.
Inspect the covariance-driven allocation.
Add one low-confidence relative view.
Observe Q - PΠ.
Compare equilibrium and posterior returns.
Increase confidence gradually.
Observe how the posterior and weights respond.
Add a second view.
Experiment with Tau.
Enable and disable posterior covariance.
Compare long-only and short-enabled portfolios.
Change the volatility target.
Observe when position or gross caps become binding.
This is generally more informative than immediately entering five aggressive views and trying to interpret the final result.
Example research questions
The allocator can be used to study questions such as:
How much does a 70% confidence view move the portfolio compared with 30% confidence?
How does inverse-volatility equilibrium differ from equal-weight equilibrium?
How does covariance shrinkage change portfolio concentration?
How do relative views propagate into assets not explicitly named?
How much does volatility targeting alter the raw optimizer?
How often do hard position caps bind?
How different are equilibrium expected returns from posterior expected returns?
How much turnover is generated by monthly versus weekly rebalancing?
How does a regime filter alter drawdown and opportunity cost?
These are the types of questions the concept is designed to explore.
Input guide
Initial Capital
Controls the starting dollar value of the simulated equity curve.
It does not change portfolio weights.
Trading Days/Year
Controls annualization.
Use a value consistent with the universe being studied.
Target Volatility
Sets the desired annualized portfolio-volatility target before hard leverage and weight constraints.
Transaction Fees
Approximate fee charged per unit of rebalance turnover.
Rebalance Every N Bars
Controls how frequently the full covariance and Black-Litterman solve occurs.
Allow Short Weights
Allows negative optimized weights.
Max Weight per Asset
Hard cap on individual position magnitude after volatility targeting.
Gross Exposure
Target absolute exposure before volatility scaling.
Max Gross After Vol Target
Final portfolio-level ceiling on gross exposure.
Max Vol-Target Leverage
Maximum scaling multiplier permitted by volatility targeting.
Covariance Lookback
Historical window used for covariance estimation and minimum data availability.
Covariance Shrinkage
Reduces off-diagonal covariance estimates toward zero.
Tau
Controls uncertainty in the equilibrium prior.
Use Posterior Covariance
Allows view uncertainty to modify the covariance matrix used by the optimizer.
Risk Aversion
Selects automatically estimated or manually specified Delta.
Prior Weight Scheme
Selects Equal Weight, Inverse Volatility or Manual Weights.
Investor Views
Supports up to five annualized absolute or relative return views.
Confidence
Controls the uncertainty assigned to each view.
Start Date
Defines the beginning of simulated portfolio equity.
Historical data before the date may still be used to warm up covariance estimates.
Risk-Free Rate
Used in portfolio statistics and Auto Delta estimation.
Benchmark
Used for the buy-and-hold comparison, Alpha and Beta.
Regime Filter
Optional chart-symbol fast/slow EMA filter that moves the portfolio between ACTIVE and CASH.
Prior vs Posterior visualization
Displays the difference between the selected prior allocation and current final portfolio weights.
Strengths
Implements the central Black-Litterman prior-and-views framework directly in Pine.
Supports both absolute and relative investor views.
Allows confidence to directly control view uncertainty.
Uses a complete cross-asset covariance matrix.
Includes diagonal covariance shrinkage.
Supports dynamic asset-data availability.
Provides equal-weight, inverse-volatility and manual priors.
Supports long-only and long-short allocation.
Uses covariance-aware portfolio volatility targeting.
Includes individual and portfolio-level exposure constraints.
Accounts for rebalance turnover fees.
Provides extensive allocation, view and portfolio diagnostics.
Includes a visual prior-versus-final-weight comparison.
Includes portfolio equity, benchmark and risk statistics.
Limitations
This is a concept and educational implementation, not an institutional portfolio-management system.
Historical covariance is only an estimate of future relationships.
The 15-asset universe is fixed in size.
A maximum of five views can be entered.
The prior is only a true market-equilibrium proxy if the selected weights appropriately represent one.
Equal Weight and Inverse Volatility are practical prior substitutes rather than literal global market-cap equilibrium.
The shrinkage coefficient is user-selected rather than statistically estimated.
Auto Delta is a practical approximation.
Portfolio optimization remains sensitive to inputs.
Poor views can produce poor posterior estimates.
High-confidence incorrect views can materially damage the portfolio.
Volatility targeting does not protect against all forms of risk.
Historical volatility can underestimate future crisis volatility.
Hard constraints mean the final portfolio may differ substantially from the analytical unconstrained Black-Litterman optimum.
The final volatility target may not be reached when position, leverage or gross limits bind.
The regime filter is based only on the chart symbol.
The backtest uses simplified transaction costs.
Regime-driven exits to CASH are not separately charged an explicit turnover fee in the current implementation.
Mixed-market TradingView data can contain differing sessions and histories.
Backtested performance does not establish future performance.
Historical and theoretical context
The Black-Litterman framework was developed to address practical problems encountered when applying mean-variance optimization to global portfolios.
Its central contribution is not simply another optimization equation.
It is a different way of constructing expected returns.
Instead of requiring the investor to estimate every asset’s return independently, equilibrium returns provide a coherent starting point. Investor views then alter only the parts of that equilibrium where the investor has an opinion.
This structure can be summarized as:
Start neutral.
Reverse-engineer equilibrium.
State where you disagree.
State how strongly you disagree.
Let covariance propagate those beliefs.
Re-optimize the portfolio.
The original Black-Litterman work emphasized equilibrium as a neutral starting point and allowed investor opinions about absolute or relative performance to tilt that equilibrium according to confidence.
Later work on user-specified confidence made the view-uncertainty problem easier to interpret by expressing conviction in intuitive percentage terms rather than requiring users to manually specify an abstract uncertainty covariance for every view.
This indicator takes those principles and translates them into a practical TradingView research environment.
Summary
Black-Litterman Allocator is an experimental portfolio-allocation framework designed to demonstrate how equilibrium, investor beliefs and portfolio risk can be combined inside TradingView.
The model begins with fifteen selectable assets and estimates their annualized covariance structure using historical log returns. A user-controlled shrinkage process reduces noisy cross-asset covariance estimates, while assets without sufficient historical data are excluded until a complete covariance window becomes available.
The user then selects an Equal Weight, Inverse Volatility or Manual prior portfolio.
That prior is reverse-optimized into implied equilibrium expected returns:
Pi = Delta × Sigma × Prior Weights
Up to five absolute or relative investor views can then be introduced.
Each view specifies:
What the investor expects.
Which assets the view applies to.
How confident the investor is.
Confidence is translated into view uncertainty, allowing weak opinions to create small tilts and high-confidence opinions to exert greater influence.
The Black-Litterman posterior combines those views with equilibrium while accounting for covariance relationships across the entire portfolio.
The resulting posterior expected returns are converted into an optimized allocation, after which the script applies:
Data-availability rules.
Optional long-only constraints.
Gross-exposure normalization.
Portfolio volatility targeting.
Maximum leverage.
Maximum position sizes.
Maximum gross exposure.
The portfolio is then rebalanced through time, transaction costs are approximated, an optional chart-level regime filter can move the book into CASH, and the resulting historical equity curve is compared with a selectable benchmark.
Extensive tables show:
Prior and final weights.
Equilibrium and posterior returns.
View confidence and uncertainty.
View disagreement with equilibrium.
Gross and net exposure.
Portfolio volatility.
Turnover.
Performance and risk statistics.
The purpose of the script is not to claim that Black-Litterman can identify the optimal future portfolio.
Its purpose is to make the framework tangible.
It provides a way to explore how a neutral portfolio can be translated into implied expected returns, how subjective beliefs can be incorporated without completely discarding that prior, how confidence changes the strength of those beliefs, how covariance spreads their effects across the portfolio, and how practical constraints can transform a theoretical posterior into a more realistic active allocation.
Treat the indicator as a concept, a research tool, and a visual implementation of portfolio-allocation theory rather than as an automated investment recommendation.
Indicator

Market Rotor - Phase-Space Rotation Geometry [FibonacciFlux]Third in a series of published experiments. The first script asked whether an observed rotation survives a null. The second asked whether the circulation between price and flow is just the price increment leaking into the flow axis. This one publishes the full phase-space geometry those two were carved out of, and then applies the same treatment to its own headline verdict.
The verdict does not survive. Against a null that breaks only the thing being tested, the orbital-rotation state is not distinguishable from noise on BTCUSDT and is worse than noise on ETHUSDT. The numbers are below and the indicator ships with the state still labelled, because a label you can check is more useful than one quietly removed.
🔶 USAGE
🔹 What is in the pane
Two dimensionless series share one scale by design. C is the signed rotation consistency - net turning divided by total turning over a window, bounded to . S* is a spiral index, tanh-compressed to the same range, positive when the trajectory winds outward. The bands behind them are the regime label; the dots along the top are phase slips.
Angular velocity ω is off by default, and that is a units decision rather than a judgement. C and S* are dimensionless; ω is rad/bar and reaches ‖ω‖ of 1.92 on BTCUSDT 1H against 0.597 for C and 0.768 for S*. Sharing an axis, it sets the scale and flattens the two series the pane exists to show. Turn it on and expect the pane to rescale.
🔹 Where the numbers come from
Every figure below comes from a reimplementation of the core outside Pine, cross-checked against the live script on the same bar, and run over 3856 plotted bars of BINANCE:BTCUSDT and BINANCE:ETHUSDT 1H covering 3 March to 17 August 2026. The null draws use a seeded generator, so they reproduce. Warm-up discards the first 144 bars of each 4000-bar series.
🔹 The background will look like a barcode, and that is the result
These are per-bar labels drawn as bands, not regimes. Over 3856 bars at the defaults the label changes on 34.5% of BTCUSDT 1H bars, with a median unbroken run of 1 bar and a 90th percentile of 6. On ETHUSDT it is 38.0%, again a median run of 1 bar. Nothing here smooths that into looking more stable, because smoothing it would be the lie. The practical reading is blunt: on most bars this tells you nothing. Phase noise alone takes 59.2% of BTCUSDT bars, and the label changes on the next bar about one time in three - the median unbroken run is a single bar because short runs are common, not because most bars are isolated. Use it to look at a stretch of history, not to make a decision on the current bar.
BTCUSDT 1H at the shipped defaults, seven weeks. Three things to look at. The background is stripes rather than blocks, which is the 34.5% figure made visible. The C line - green above zero, pink below - stays well inside the two faint threshold lines at ±0.45 for almost the entire span; the handful of touches are some of the 8 episodes counted below. And the amber S* area is far wider than C, which is why the pane scales the way it does and why ω, wider still, is off by default.
What the bars get called, BTCUSDT / ETHUSDT: phase noise 59.2% / 51.7%, outward spiral 15.7% / 18.3%, inward spiral 13.6% / 16.8%, core 8.7% / 11.3%, phase slip 1.2% / 1.7%, orbital rotation 1.5% / 0.1%. Those last two are lower than the raw |C| rates below, because the cascade tests slip, core and spiral before it ever tests |C|.
🔹 The orbital-rotation verdict, and the null that kills it
The obvious null is to shuffle the second axis. That is the wrong null, and it is the mistake this script shipped with. Shuffling destroys y's autocorrelation as well as its alignment with x - lag-1 goes from 0.545 to 0.034 - and a y that jumps every bar inflates the total turning in the denominator, pushing C toward zero for reasons that have nothing to do with the two axes. A circular shift of y keeps the autocorrelation at 0.543 and breaks only the alignment, which is the thing under test.
Rate of the verdict against the p50 of each null over 20 draws, and p = the share of shift-null draws that match or beat the real rate. 3856 bars, both symbols:
BTCUSDT ETHUSDT
W real shuffle shift p real shuffle shift p
24 6.52% 2.63% 7.68% 0.76 7.09% 3.14% 8.69% 0.90
48 1.84% 0.16% 1.12% 0.29 0.29% 0.13% 1.63% 1.00
96 0.03% 0.00% 0.00% 0.24 0.00% 0.00% 0.00% 1.00
Read the shuffle and shift columns side by side. Against the shuffle the verdict looks like it separates at every window. Against the shift it separates at none: on BTCUSDT the real rate sits inside the bulk of its own null, and on ETHUSDT it sits below every draw. At the window this script originally shipped with, W = 24, the real rate is below the null median on both symbols.
The window was moved from 24 to 48 in an earlier cycle precisely because that drove the shuffle null to zero. What it actually did was widen a gap against a null that had been crippled. It stays at 48 as the more conservative reading, not because it separates anything.
And 71 and 11 are not 71 and 11 independent trials. Adjacent bars share 47 of their 48 turning angles. Counted as contiguous episodes, both symbols enter the state exactly 8 times ; on BTCUSDT a single episode of 30 bars is 42% of every firing bar. The gap between the two symbols is how long one episode lasted.
🔹 Warm-up, alerts and cost
Nothing plots for 3 × the longest window, which now includes the consistency window - 144 bars at the defaults. Four alerts fire on entry into the phase-slip, outward-spiral and orbital-rotation states and on a change of rotation direction; they name the trigger and deliberately say nothing about what price should do next.
Four request.* calls sit at global scope and run every bar whatever the settings say; what is conditional is the timeframe each asks for, so the lower-timeframe pull only requests a real lower timeframe when the order-flow axis is selected. That is not the same as free, and the cost has not been measured. Two chart tabs did go unresponsive on a two-core machine during this work, one of them here during a symbol change - but the order-flow axis was afterwards exercised on 1H without incident and gave genuinely different values from the default. Read those as unexplained, not as a warning about a setting.
On the order-flow axis there is one silent substitution to know about: past the intrabar history limit, or on a plan that cannot serve the chosen lower timeframe, y falls back to the CLV proxy with no visible break, so the plotted history can mix two different second axes.
🔶 DETAILS
🔹 The construction
Both axes are z-scored over a rolling window and passed through a 2×2 whitening Σ^(-1/2), so a merely correlated pair does not draw a tilted ellipse and read as rotation. Turning per bar is the signed angle between successive position vectors, taken from the cross and dot products rather than by differencing φ, and spans inside a central dead zone count as zero turning because the angle there is noise. C is the ratio of the two rolling sums, gated so a window carrying less than π of total turning reports nothing at all.
🔹 The noise floor, measured honestly
median |C| real 0.133 y shuffled 0.097 y circularly shifted 0.123
both null figures are the p50 across 20 draws, not a single draw
Break only the alignment and the level barely moves - and at the window this script originally shipped with, W = 24, it does not move at all: real 0.169 against a shift null of 0.167. Nearly everything you see is the random walk of a partial sum over 48 angles. The earlier "about seventy per cent" reading came from the shuffle column, and was therefore too generous to the indicator.
🔹 Which knobs are load-bearing
One. The lag on the second axis: with no lag, y is close to the derivative of x, the point circles for that reason alone, and median signed consistency comes back at -0.283 against -0.036 at the shipped lag of one bar. Two that are not: moving the dead zone from 0 to 1.0 moves median |C| from 0.144 to 0.128, and turning whitening off moves it from 0.133 to 0.138. Defensible hygiene, neither load-bearing.
🔹 What is not established
Incremental alpha, none of it - no IC against existing signals, no out-of-sample improvement, no PBO or DSR. This is an observer, and on the evidence above it is an observer of something it has not shown to be there. The experimental signal arrows are off by default and stay in only as a comparison: shuffling the second axis barely dented their performance, which points at the plain |x| threshold rather than at anything rotational.
🔶 SETTINGS
🔹 Axes and normalisation
Second axis y - five options: deviation × momentum (default), deviation × order flow from lower-timeframe volume delta, deviation × order flow via a CLV × volume proxy, return × volatility change, and deviation × open-interest change. Momentum is close to the derivative of x, so read the default as the control rather than as the best proxy. Every number in this description is measured on that default axis, deliberately - it is the weakest case, and a statistic that cannot beat its null there has not earned a test on a better axis. The order-flow axis was not re-measured.
Lag on the second axis - default 1. The one setting that decides whether the measurement means anything.
Equilibrium EMA 34, z-score length 40, 2×2 whitening on, z clip 4.0, optional anchored normalisation.
🔹 Windows
Consistency window for C - default 48. Read the window sweep above before changing it - no setting of it separates the verdict from the shift null.
Total-turning gate - default π. Below it, C and S* report na rather than a ratio of two small numbers. It is a safeguard that never bound on the data here: total turning had a median of 27.7 rad and a minimum of 12.6 against a gate of 3.14, so it was open on all 3856 bars of both symbols. Expect no gaps from it.
Central dead zone 0.30, winding window 32, loop-area window 24, warm-up multiplier 3.
🔹 Regimes and display
Thresholds for orbital rotation, spiral, core radius and phase-slip hazard.
C, S*, the regime background and the slip markers are on by default; ω, winding number W, loop area A, the Kuramoto multi-timeframe readout and the experimental arrows are off.
The Kuramoto readout R carries the same units caveat as ω: it lives on and is positive only, so switching it on rescales the pane. It is drawn beneath C so it cannot hide it. Its two higher timeframes now default to 4H and 12H - they were 1H and 4H, and on the shipped 1H chart that made two of the three phases identical and put a floor of 1/3 under R. Keep both above your chart timeframe.
Radius, raw S*, phase-slip hazard, total turning, raw loop area, both axis positions and the regime number are in the Data Window.
Open source under the Mozilla Public License 2.0. Replications and refutations welcome - particularly a symbol, timeframe or axis pair on which the orbital-rotation state does separate from a shift null. I did not find one.
Indicator

Market Rotor - Rotation Artifact Null Test [FibonacciFlux]Market Rotor is the first of a series of published experiments: take a correction that is widely assumed to work, implement it honestly, and find out what it actually does. This one tests the standard artifact correction for cross-sectional rotation - the claim that you can estimate each asset's own autocorrelation, subtract the rotation that autocorrelation implies, and treat whatever is left as genuine lead-lag.
Implemented and measured, it does not do that. The script is published so the test can be repeated and the result attacked.
🔶 USAGE
🔹 What this is for
Before you build on, or believe, a rotation or lead-lag indicator, load your basket here. If an artifact component is identified, an artifact component is present in the rotation this basket produces at this window - which is reason to check whether the indicator you were about to trust is reading the same thing. If nothing is resolved, you have learned that this particular correction cannot tell you either way - which is worth knowing, because the correction is usually assumed to work rather than checked.
🔹 Reading the shading
The background has two states and neither of them is an all-clear:
Amber - R-squared above zero. An artifact component was identified inside the rotation you are looking at.
Grey - R-squared at or below zero. Nothing was resolved. This is not evidence that the rotation is genuine.
Two months of BINANCE:BTCUSDT 1H at the defaults. The two states alternate throughout - there is no long stretch where the correction cleanly resolves anything.
There is deliberately no green state anywhere in this script. A reassuring colour would be the most misleading thing it could draw, because the test is structurally incapable of certifying that an observed rotation is real.
🔹 Reading the plots
Three Frobenius norms share the pane. Grey is the observed rotation, the amber filled area is the artifact estimate, green is the residual. These are matrix norms, not components: they do not sum, and the residual can and often does exceed the observed norm. When it does, subtracting the artifact estimate has added variance rather than removed it - see the noise floor below.
The Data Window carries the quantities that actually matter: R-squared, the residual share, the direction agreement cos(Ω, Ω_art), the mean off-diagonal of G0, the four estimated AR(1) coefficients, the effective sample count, and the legacy statistic from the first version of this script, kept only for comparison.
🔹 Choosing the symbol set
The artifact term is proportional to contemporaneous co-movement. If your four assets barely co-move, or their bars do not align - mixing a stock with 24/7 crypto is the common case - the artifact estimate collapses toward zero for reasons that have nothing to do with lead-lag, and the test silently becomes vacuous. Watch the mean off-diagonal of G0 in the Data Window: if it is small, the reading means nothing.
The same script on NASDAQ:AAPL daily with the three Binance defaults left in place - the first thing most readers will try. Nothing warns you. On the bar shown, the mean off-diagonal of G0 falls from 0.87 to 0.34, the artifact estimate collapses with it to 0.016 against an observed norm of 0.081, cos(Ω, Ω_art) reads -0.85, and the residual ends up larger than the observed rotation it came from. Note what the old v1 statistic does here: 0.20, which under that version's bands was its most reassuring possible reading. The tool's least trustworthy configuration was the one it praised.
Requests use gaps_on, so a symbol with a missing bar yields na and that bar is skipped rather than having a stale return carried into the estimate.
🔹 Warm-up and repainting
Nothing plots until the window is full and W + z-score-length bars have elapsed: 500 bars at the defaults, roughly three weeks of 1H data, but around two years on a daily chart. If the pane is empty, that is why. The accumulator only advances on confirmed bars, so historical values do not repaint.
🔶 DETAILS
🔹 The identity being tested
Let each asset follow its own AR(1) with coefficient phi_i, and let the true cross-asset lead/lag be identically zero:
r = phi_i * r + e
G1 = E [ r * r ] = phi_j * G0
G0 is symmetric, therefore
Om = 0.5 * (phi_j - phi_i) * G0
Exact in population. The proposal it suggests - estimate phi from each asset's own autocorrelation, form the implied artifact, subtract it, call the remainder genuine lead-lag - is what this script implements so that it can be tested rather than assumed.
🔹 Where the numbers come from
The core was reimplemented outside Pine and agrees with this script to five decimal places on the same bar; every figure below comes from that reimplementation. Figures labelled synthetic are generated with a seeded generator and known ground truth, so they reproduce exactly. Real-data figures name the symbol, timeframe and window they were taken on, and the two single-bar readings are marked as such.
🔹 Result 1: the correction is not identified
phi_i estimated from asset i's own autocorrelation cannot distinguish "asset i is autocorrelated" from "asset i is led by asset j", because the second necessarily produces the first. On synthetic data where a genuine lead-lag is injected, the artifact model fits better , not worse: R-squared rises to +0.40 and cos(Ω, Ω_art) to +0.74 at W=250. The correction absorbs precisely the thing it is meant to leave behind.
🔹 Result 2: the subtraction is noise-dominated
Ω is estimated from the off-diagonal of G1; the artifact term from the diagonal of G1 plus G0. Under the null these estimate the same population quantity. If their errors are of comparable size and not strongly correlated, Var(Ω_res) = Var(Ω) + Var(Ω_art) and the residual share tends to sqrt(2) = 1.414 when noise dominates. Both of those are assumptions rather than results - the two estimators are built from the same return pairs over the same window, and the null identity ties them together - so read the measured spread as the test of them, not as a confirmation of the algebra. On synthetic all-artifact data it lands between 1.10 and 1.88, straddling that value, and the finding that survives either way is that the residual is larger than the quantity it was subtracted from. On BINANCE:BTCUSDT 1H with the default basket at W=250, the median R-squared is about -0.7 - near the noise floor of -1.
🔹 What the first version of this script got wrong
Version 1 shaded on ‖Ω_art‖ / ‖Ω‖. That statistic compares magnitudes only and is not a fraction-explained, because the artifact and residual matrices are not orthogonal. It read 0.96 - "almost entirely artifact" - on data whose true explained share was 0.41, while the residual line sat at 77% of the observed line directly beside it. It also produced its most reassuring readings on baskets that barely co-move. Both statistics are exposed in the Data Window now - R-squared and the v1 ratio side by side - so the discrepancy can be inspected rather than taken on trust.
🔹 Implementation and reproducibility
N is fixed at four because the external series are requested at global scope. G0 and G1 are uncentred second moments, not covariances; centring them inside the window was tested and moved R-squared by less than 0.02, so the extra accumulators are not carried. Rolling sums of the sixteen products are maintained by hand in a circular buffer, because built-in series functions keep per-call-site state and return wrong values inside loops. The core was independently reimplemented outside Pine and agrees with this script to five decimal places on the same bar; the synthetic scenarios use a seeded generator so the numbers above are reproducible.
🔶 SETTINGS
🔹 Symbols
Symbol 2, Symbol 3, Symbol 4 - the three series joined to the chart symbol, which is always the first. Defaults are ETHUSDT, SOLUSDT and XRPUSDT on Binance.
🔹 Windows
Rolling window W - length of the moment window, default 250, minimum 100, maximum 1000. Below about 100 the estimates are pure noise and the shading strobes, which is why the minimum is not lower.
Return z-score length - lookback used to standardise each return series, default 250.
🔹 Display
Show ‖Ω‖, ‖Ω_art‖, ‖Ω_res‖ - the three norms.
Shade background when an artifact component is identified - the amber/grey band.
Show residual signal for the chart symbol - off by default, and drawn for inspection only. It is signed and lives on a different scale to the three norms. Result 2 above is the reason not to trade it: this residual is noise-dominated and routinely larger than the observed norm it came from.
Signal display scale - default 0.2. Raising it flattens everything else in the pane.
Open source under the Mozilla Public License 2.0. Replications and refutations are welcome, particularly from anyone who can construct an estimator of the artifact term that stays identified when a genuine lead-lag is present.
Indicator

HTF Auction Candle (Zeiierman)█ Overview
HTF Auction Candle (Zeiierman) is a multi-timeframe auction profiling indicator that reconstructs the currently forming Higher Timeframe candle and analyzes the lower-timeframe activity developing inside it.
Rather than viewing the Higher Timeframe candle only as a single OHLC structure, the indicator breaks its full high-to-low range into individual price cells. It estimates how buying and selling activity is distributed across those levels.
Battle Bubbles provide an additional view of the auction by showing which side is winning across broader price segments and the relative strength of each battle.
█ HTF Auction Structure
The center of the indicator displays the reconstructed Higher Timeframe candle.
⚪ Buy and sell activity is displayed on opposite sides of the candle:
• Sell activity extends to the left.
• Buy activity extends to the right.
The width of each profile section represents the estimated amount of activity concentrated at that price level. Wider areas therefore highlight prices where greater participation occurred during the developing Higher Timeframe auction.
⚪ When Delta Dominance is enabled, each price cell also compares estimated buying and selling activity.
• Positive Delta extends to the right.
• Negative Delta extends to the left.
• Larger Delta cells represent stronger directional imbalance.
⚪ Battle Bubbles summarize buyer-versus-seller control across 20 equal sections of the Higher Timeframe range.
• Green bubbles indicate a buyer win.
• Red bubbles indicate a seller win.
• Larger bubbles represent stronger battles with greater participation.
Together, the Volume Wings, Delta Dominance, and Battle Bubbles provide different views of participation, imbalance, and directional control inside the developing Higher Timeframe candle.
█ How It Works
⚪ Higher Timeframe Reconstruction
The indicator reconstructs the selected Higher Timeframe candle using its live open, high, low, and current close. The high and low are also linked back to the chart bars where those extremes first formed.
⚪ Lower Timeframe Sampling
The internal auction is built from Lower Timeframe candles, using their open, high, low, close, and volume. The selected Lower Timeframe must remain below the Higher Timeframe and cannot exceed the chart timeframe.
⚪ Buy and Sell Volume Estimation
Each Lower Timeframe candle’s volume is divided into estimated buy and sell activity using its close position, candle direction, and wick structure.
buyVolume = volume × buyShare
sellVolume = volume - buyVolume
A stronger bullish structure receives a larger estimated buy share, while a stronger bearish structure receives a larger sell share. This is an estimation model and does not use true bid and ask transaction data.
⚪ Price Cell Distribution
The Higher Timeframe range is divided into Price Cells, with each Lower Timeframe candle contributing activity only to the cells touched by its range.
Buy and sell volume is weighted toward separate directional areas, while Cell Concentration controls how tightly that activity is distributed.
⚪ Volume Wings
Estimated sell activity forms the left profile and buy activity forms the right profile. Wider sections indicate greater participation at that price level.
⚪ Delta Dominance
Delta measures the difference between estimated buy and sell activity inside each Price Cell.
delta = buyVolume - sellVolume
• Positive Delta indicates stronger estimated buying.
• Negative Delta indicates stronger estimated selling.
• Wider Delta areas represent stronger imbalance.
⚪ Battle Bubbles
The Higher Timeframe range is divided into 20 equal Battle segments.
Each segment combines estimated volume Delta with directional Lower Timeframe win consistency to determine buyer or seller control.
• Green bubbles indicate buyer control.
• Red bubbles indicate seller control.
• Larger bubbles represent stronger battles with greater participation.
Bubble size is normalized against the strongest Battle segment in the current Higher Timeframe candle.
⚪ Higher Timeframe Delta
The indicator also calculates estimated Delta across the entire Higher Timeframe candle.
Delta % = 100 × (Buy Volume - Sell Volume) / Total Volume
Positive values indicate overall buying dominance, while negative values indicate selling dominance.
█ How to Use
⚪ Analyze the Developing Higher Timeframe Candle
Use the reconstructed candle to monitor a Higher Timeframe auction without leaving the current chart timeframe.
Instead of waiting for the Higher Timeframe candle to close, traders can observe how its structure and internal participation are developing in realtime.
This can be useful when monitoring larger timeframe candles from lower execution timeframes.
⚪ Identify High-Participation Areas
Wide sections of the Volume Wings show price levels where more estimated activity has accumulated.
These areas can highlight important zones of acceptance, consolidation, support, resistance, or repeated participation within the current Higher Timeframe candle. Narrow profile areas show prices where relatively less activity occurred.
⚪ Use the Control Price
The Control Price identifies the price cell with the highest combined estimated activity.
Traders can use it as a reference for where the current Higher Timeframe auction has concentrated the greatest participation.
Price holding around the Control Price can suggest continued acceptance, while movement away from it can help highlight changes in the developing auction.
⚪ Read Delta Across the Range
Delta Dominance shows which side is stronger at individual price levels.
• Positive Delta highlights areas of stronger estimated buying activity.
• Negative Delta highlights areas of stronger estimated selling activity.
• Large Delta cells highlight stronger directional imbalance.
This can help reveal whether buying or selling pressure is concentrated near specific parts of the Higher Timeframe candle.
For example, strong positive Delta near the upper portion of the range can show aggressive bullish participation, while strong negative Delta near the highs can indicate selling pressure developing into higher prices.
⚪ Read the Battle Bubbles
Battle Bubbles provide a simplified view of which side is winning across different parts of the Higher Timeframe range.
Clusters of larger buyer or seller bubbles can highlight areas where directional control is especially strong, while smaller bubbles indicate weaker or less significant battles.
They can be used alongside the Volume Wings and Delta Dominance to distinguish broad directional control from the more detailed activity occurring inside individual price cells.
█ Settings
Higher Timeframe: Selects the Higher Timeframe candle used for the live auction. It must be greater than the chart timeframe.
Auto LTF: Automatically selects a suitable Lower Timeframe used to build the internal auction.
Manual LTF: Selects the Lower Timeframe manually when Auto LTF is disabled. It must remain below the Higher Timeframe and no higher than the chart timeframe.
Price Cells: Controls how many price levels divide the Higher Timeframe range. More cells provide finer profile and Delta resolution.
Cell Concentration: Controls how tightly estimated buy and sell activity is distributed around each Lower Timeframe candle's directional activity centers.
LTF Sample Capacity: Sets the maximum number of Lower Timeframe samples retained before older samples are compressed to maintain performance.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Indicator

Market Rotor - Increment Contamination Test [FibonacciFlux]Second in a series of published experiments: take a correction that is widely assumed to work, implement it honestly, and find out what it actually does. This one tests the most common way of accidentally manufacturing rotation - putting the same-bar price increment into the second axis and then reading the resulting circulation as structure.
It detects that contamination reliably, though not precisely - the spread is measured below. It cannot do the converse, and the boundary where it starts getting the converse wrong is measured below.
🔶 USAGE
🔹 What this is for
Any indicator that claims rotation, circulation or lead-lag between price and a flow-like series is reading the antisymmetric part of a lag-1 covariance. Load your two axes here first. If the reading comes back near 1, the circulation that indicator is showing you is the increment leaking into its own second axis, and there is nothing else to interpret.
🔹 Reading the shading
Red - the ratio sits within 0.25 of 1. An increment-contamination component accounts for the observed circulation.
Grey - anything else. Not classified. This is not evidence that the rotation is genuine.
BTCUSDT 1H at the defaults. The band is red across effectively the whole span, and that is the finding rather than a rendering quirk: on this data the circulation between price and flow is contamination-shaped nearly all of the time. Note also how much of the pane the amber R_art area occupies relative to the pale R_obs line running through it - the artifact term is routinely larger in magnitude than the thing it is decomposing, which is why the ratio sits above 1 in about two thirds of readings.
There is no green state, for the same reason as in the first script: this test is one-directional. It can find contamination; it cannot certify its absence.
🔹 Reading the plots
The amber filled area is R_art, the circulation Identity I alone accounts for; the pale line inside it is R_obs, the observed circulation; green is R_res, what is left. The verdict band is red rather than amber precisely so that it is not the same colour as the series it is a verdict about.
The ratio is a signed share, not a fraction. R_res is defined as R_obs - R_art, so the additive identity cannot fail and proves nothing by itself; what justifies the split is that LAMBDA is linear in y, so writing y = beta*dx + e gives R_art and R_res exactly as the circulation contributed by each part. Nothing bounds the ratio to , and on real data it usually is not there: on BTCUSDT 1H it exceeds 1 in 66% of readings on the default axis, 79% on the order-flow axis. Read "near 1" as "contamination accounts for it", never as a percentage of it.
The Data Window carries the ratio, beta, corr(y, dx), LAMBDA, T_K and both axes.
🔹 Choosing the second axis
CLV x volume is the default, and deliberately not the best proxy. Order flow from lower-timeframe volume delta is the better second axis. The original reason for not defaulting to it was that a chart tab hung twice while it was selected, once on a daily chart and once on the 1H default, both on a two-core machine.
That attribution has since weakened and this paragraph is the correction. Both of those tabs stopped responding during automated testing, not during ordinary use. The same symptom later appeared twice more with no lower-timeframe request involved at all, and the axis has since been selected and exercised on a 1H chart without incident. Nothing here is attributable to the request. The default stays on CLV as the conservative choice rather than as a fix for a diagnosed problem - select order flow deliberately, not nervously.
What the default does buy you is real, and it is a cost rather than a hazard: request.* must sit at global scope, so the call always runs, but the timeframe it asks for is now conditional. On any axis other than order flow it is pointed at the chart's own timeframe and returns one intrabar per bar instead of sixty.
Volume z-score on its own is the useful control: it carries almost no increment at all (beta +0.016, corr +0.009), and its ratio consequently degenerates - a non-verdict, not a clean bill of health. Momentum is a control, not a choice - it sets y to a difference of return EMAs, which is nearly dx itself. Watch beta when you switch to it, not the ratio: measured on one bar of BTCUSDT 1H the ratio barely moved (1.119 to 1.084) because the default is already saturated near 1, while beta on that same bar jumped from 0.838 to 1.270. The identity is firing; the ratio has no room left to show it.
The four axes disagree, and that is information rather than a defect. On one bar of BTCUSDT 1H: order flow 1.119, CLV x volume 0.965, momentum 1.084 - and volume z-score -2.104, which is not a verdict at all but the signature of a near-zero denominator, discussed below.
🔹 Warm-up and repainting
Nothing plots until 2 x W + z-length + detrend-length bars have elapsed: 574 at the defaults, about 24 days of 1H data.
Two things that will bite you. First, when R_obs is near zero the ratio is meaningless and still prints to five decimals - on the volume z-score axis this was measured at R_obs 0.013 giving a ratio of -2.10 with beta 0.07, that is, no contamination at all and a nonsense ratio. Read LAMBDA first: if there is no circulation, decomposing it means nothing. Second, if you switch to the order-flow axis, set the lower timeframe explicitly before going above 4H - on a daily chart the warm-up needs roughly 14,000 intrabars.
And one silent substitution. Where the lower-timeframe request returns nothing - beyond the intrabar history limit, or on a plan that cannot serve the chosen lower timeframe - y falls back to CLV with no visible break. The plotted history can therefore be a mixture of two different second axes with an invisible switchover, and every Data Window statistic inherits it. Watch corr(y, dx) and beta for a step change if that matters to you.
🔶 DETAILS
🔹 The identity being tested
R_obs = 2 * LAMBDA, LAMBDA = 0.5 * mean_W
if y carries the same-bar increment dx with coefficient beta then
Q(w) = -beta * S_xx(w) * sin(w) appears with no rotation present at all
beta = cov_W(dx, y) / var_W(dx)
R_art = 2 * beta * 0.5 * mean_W
In discrete time x_s(y_{s+1}-y_s) - y_s(x_{s+1}-x_s) collapses exactly to x_s*y_{s+1} - y_s*x_{s+1}, so the circulation needs no angles, no atan2, no origin estimate and no lag operator. An earlier version of this work used atan2 and every one of those was required - each a free parameter able to manufacture the result.
Call it circulation, not a rotation rate: mean is mean , an areal velocity, and it equals a rotation rate only if the squared radius and the angular velocity are uncorrelated.
🔹 What it detects, and what it does not
Reimplemented outside Pine and swept over synthetic series whose truth is known by construction, 5 seeds, W = 250:
y = beta*dx + noise, no rotation at all - the ratio has median 0.94 to 0.97 with a 10th-to-90th percentile spread of roughly 0.77 to 1.17. Centred on 1, but not precise, and independent of the sign of beta.
a clean 2-D rotation with no dx in y at all - the ratio reads 0.46 to 0.83, rising with rotation speed. The test therefore cannot certify that a rotation is genuine.
The false positive depends on persistence at least as much as on speed. The rotation speed at which a clean, uncontaminated rotation starts reading above 0.75 and is reported as contamination, by the AR persistence rho of the rotating system:
rho 0.90 never, up to 1.5 rad/bar
rho 0.95 0.50 - 0.70 rad/bar (~9-13 bar cycle)
rho 0.98 0.25 - 0.40 rad/bar (~16-25 bar cycle)
rho 0.995 0.12 - 0.16 rad/bar (~39-52 bar cycle)
W and the noise level did not move that boundary; persistence moved it by more than 5x.
The sign of beta is deliberately not used for anything. Across more than 50 configurations it tracks the sign of whatever coupling exists, flipping with the direction of a genuine rotation as readily as with the sign of the contamination. Related structural fact, worth checking rather than trusting: LXD is non-positive by construction, so the sign of R_art is fixed by the sign of beta. Measured across synthetic rotation in both directions, synthetic contamination and real data, LXD was positive in 0.0% of readings.
🔹 On real data
Two structurally different flow proxies give the same verdict on 1H crypto, which is the finding worth taking away:
ratio beta corr(y,dx)
CLV x volume BTCUSDT 1.082 +0.49 +0.30
ETHUSDT 1.085 +0.58 +0.36
taker flow BTCUSDT 1.090 +0.79 +0.47
ETHUSDT 1.052 +0.65 +0.39
volume z BTCUSDT 0.664 +0.016 +0.009 <- the control
My own earlier work on this data, which this script reimplements, reported 108.3% with corr +0.377 on its own flow proxy, and the live script on lower-timeframe volume delta reads 1.119 with corr +0.533. Four different constructions of the second axis, one answer: the circulation people read between price and flow is the increment leaking into the flow axis.
🔹 Implementation and reproducibility
Covariances are computed from their definition because Pine has no ta.cov. y is never lagged: an earlier cycle established that lagging it manufactures rotation and reverses the sign of the true antisymmetric lag covariance. The x pipeline was verified against an independent reimplementation - identical to five decimal places on the same bar. The synthetic scenarios use a seeded generator, so every number above is reproducible.
🔶 SETTINGS
🔹 Axes
Second axis y - CLV x volume (default), order flow from lower-timeframe volume delta, volume z, or the momentum control.
Equilibrium EMA - detrends x (default 34).
Z-score length - standardises both axes (default 40).
Lower timeframe for volume delta - blank picks one from the chart timeframe.
🔹 Windows
Rolling window W - LAMBDA, beta and T_K are all estimated over it (default 250, minimum 100; shorter windows make the verdict band fragment into bar-to-bar stripes).
Warm-up multiplier - bars withheld before plotting, as a multiple of W (default 2).
🔹 Display
R_obs, R_art, R_res - the three series.
T_K residual torque - off by default; a volume-weighted detailed-balance statistic that did not survive its own null.
Shade background when contamination is identified - the red band.
T_K display scale - default 30, because T_K is far smaller than the three circulation series and draws as a flat line on zero at 1; 30 is simply what made it readable here.
Open source under the Mozilla Public License 2.0. Replications and refutations welcome, particularly a second-axis construction that stays uncontaminated under a test I have not thought of.
Indicator

Confirmed Structure Transition Map [Pineify]Confirmed Structure Transition Map
Overview
This Pine Script v6 indicator separates confirmed swings, break-of-structure events, and direction candidates. A finite state appears as a stepped price corridor.
Problem Definition
A common baseline finds fractal highs and lows, then labels any crossing BOS or CHoCH. It hides the pivot bar, the later confirmation bar, and the still later break. One level may emit repeated labels, while one counter-break may be called a reversal. Label density replaces a distinction between swing formation, continuation, and transition. This script separates those events and never triggers an earlier break with future information.
Design Rationale
Confirmed pivots provide stable levels; a moving extreme has no fixed identity. Each high and low becomes a one-use rail. A break with the bias is BOS; the first qualified counter-break is only a potential CHoCH. Bias changes after a fresh rail breaks again in that direction. Crossing the frozen opposite rail or age limit cancels the candidate. This rejects immediate reversal on one counter-break. The tradeoff is lag for explicit evidence. ATR scaling filters tiny overruns but does not estimate probability.
Key Features
Optional confirmed HH, LH, HL, and LL labels.
One-use rails that suppress duplicate breaks.
BOS, potential CHoCH, shift, invalidation, and expiry states.
ATR displacement, state corridor, alerts, and dashboard.
How It Works
The script reads chart OHLC and a symmetric pivot window. A pivot is accepted after its right-side bars close. Its price and index are stored, compared with the prior same-type pivot, and armed as a rail. If price already exceeded the required displacement when it became knowable, that rail is consumed without a hindsight event.
Each confirmed bar compares the Close or Wick probe with both rails. Distance beyond a rail is divided by ATR and must meet Minimum Break Displacement. On a two-sided outside bar, the larger normalized wick defines one event. The first event sets bias; a same-direction event is BOS. A counter-event freezes break rail, invalidation rail, displacement, and start bar. Confirmation needs a fresh rail and second break in the candidate direction. Invalidation or expiry ends the candidate. The corridor shows bullish, bearish, pending, or neutral state; early bars stay neutral.
How Multiple Indicators Work Together
This is one dependent state model, not a mashup. Pivot confirmation supplies stable rails; otherwise levels move while tested. ATR displacement separates a tiny overrun from a range-scaled break. The ordered state machine consumes those qualified breaks; otherwise crossings remain a label stream. The corridor encodes the resulting state instead of adding an unrelated signal.
Trading Ideas and Insights
Read BOS as evidence that price cleared a rail with the established bias, not as an entry command. Violet marks a candidate; amber shows why it ended. A wide corridor requires a larger absolute move. Apply separate risk, liquidity, and execution rules: the map does not select stops, size positions, or forecast events.
Unique Aspects
The contribution is an ordered lifecycle. Rails arm only when knowable, each fires once, a counter-break stays provisional, and a second newly armed break is required before bias changes. Invalidation level and age limit freeze at candidate start, so later pivots cannot rewrite the test. One corridor carries bias and transition while labels, wash, bar colors, and table remain optional. This is more than a renamed fractal plot.
How to Use
Begin with Close and default pivots, then check swing density for the market and timeframe. Read rails first: BOS continues state, P-CH opens a candidate, and SHIFT completes the two-break transition. HH/HL locations are revealed after the right-bar delay, not known on their historical bars. Use BOS and shift alerts only within an existing process.
Customization
Pivot Left/Right Bars control granularity and delay: smaller values add noise; larger values add lag. Close requires settlement beyond a rail. Wick uses extremes and resolves outside bars by larger excursion. Minimum Break Displacement sets ATR clearance; Candidate Expiry limits age. Corridor, labels, wash, bar colors, and dashboard are independently configurable.
Assumptions and Limitations
Pivots need future bars for confirmation, so markers appear on pivot bars only after the right-side delay; breaks and shifts remain on confirmation bars. Probes move live, but state and alerts require bar close. ATR and pivot settings are market-sensitive. Gaps can jump rails, Wick mode reduces an outside bar to one event, and chop can repeat candidates. The model reads chart prices, not order flow, news, higher timeframes, or execution quality. A shift is an ordered event, not a guaranteed reversal or profitable trade.
Conclusion
The map turns delayed pivots and breaks into an auditable sequence: location, one-use break, provisional counter-break, then confirmation or invalidation. It provides structural context; interpretation and risk remain with the user.
Indicator

HTF Candles and FVG█ OVERVIEW
HTF Candles and FVG is a highly adaptive indicator that displays candles from a higher timeframe (HTF) directly on a lower-timeframe chart, together with automatically detected Fair Value Gap (FVG) zones.
Instead of switching between timeframes, the user can observe the higher-timeframe candle structure within the current chart layout. The indicator fetches data from the selected HTF and reconstructs its candles while preserving their real position in time.
One of the most important features of the indicator is its high visual flexibility. HTF candles can be displayed directly on the current price candles according to the real time axis, or as a separate candle strip placed beside the chart. This allows the indicator to serve both as a contextual tool and as a more classic HTF overlay.
In Manual layout, candle width can be set automatically from the relationship between the chart timeframe and the selected HTF, so it adapts without manual adjustment whenever the chart timeframe changes. For instruments with non-standard session hours, such as stocks or indices, the Auto-Align mode preserves correct candle boundaries by positioning each HTF candle at its real open and close time rather than a calculated width.
The second analytical layer consists of Fair Value Gaps detected on the higher-timeframe candles. FVGs are identified from a three-candle HTF pattern and are then visualized as zones that extend until they are mitigated.
The indicator also lets the user control how FVG mitigation is recognized — by wick or by close. This allows the definition of "gap fill" to be adjusted to the user's own analysis style.
High visual configurability also makes it possible to create a very minimalist layout. By adjusting the transparency of individual elements, the HTF candles, their bodies and wicks can be practically hidden, leaving mainly the higher-timeframe FVG zones on the price chart.
As a result, HTF Candles and FVG can be used both as a full visual higher-timeframe context and as a discreet tool for placing key FVG zones on the current chart.
█ CONCEPTS
Higher Timeframe Candles
The core element of the indicator is the candles fetched from the selected higher timeframe.
The user can choose a timeframe ranging from short intraday intervals up to D, W and M. The indicator stores the HTF candle history and allows the number of most recent candles to be displayed to be specified.
Candles can be presented in two ways:
- Auto-Align — candles are placed according to their real position on the time axis.
- Manual Mode — candles are arranged as a separate sequence beside the chart, with adjustable width, gap and offset.
This solution allows the presentation style to be adapted to different analysis approaches.
Automatic Width
In Manual layout, the width of each HTF candle can be calculated automatically from the relationship between the chart timeframe and the HTF.
This means the user does not have to manually adjust candle width every time the chart timeframe is changed. In Auto-Align mode this setting does not apply, since candle width is instead derived directly from each candle's real open and close time.
Fair Value Gaps
FVGs are detected from three consecutive HTF candles.
A bullish FVG forms when the low of the third candle is above the high of the first candle. A bearish FVG forms when the high of the third candle is below the low of the first candle.
The FVG zone starts at the corresponding position of the middle candle and remains active until it is mitigated. If the gap has not been mitigated, the zone is kept up to the most recent position available within the displayed range.
FVG Mitigation
FVG mitigation can be defined in two ways:
- Wick — the zone is considered mitigated when the wick of a subsequent HTF candle enters the FVG range.
- Close — the zone is considered mitigated only when the close of an HTF candle enters the FVG range.
This gives the user a choice between a more reactive wick-based approach and a more restrictive close-based approach.
Forming HTF Candle
The indicator can also display the currently forming, still unclosed HTF candle.
This makes it possible to observe in real time how the current higher-timeframe candle develops together with successive lower-timeframe candles.
█ FEATURES
Higher Timeframe
- Higher Timeframe (HTF) – selection of the timeframe from which candles and FVG zones are fetched.
- Number of HTF Candles to Display – specifies how many of the most recent HTF candles are shown on the chart.
Candle Layout
- Automatic Width (Proportional to TF) – in Manual layout, automatically adjusts candle width according to the relationship between the chart timeframe and the selected HTF. Not used in Auto-Align mode, where candle width is derived from each candle's real open and close time.
- Manual Candle Width (bars) – sets the width of an HTF candle in manual mode.
- Auto-Align to Time Axis – places HTF candles at their real position on the time axis, using each candle's actual open and close time, instead of arranging them beside the chart. This keeps candle boundaries accurate even on instruments with non-standard session hours, such as stocks or indices.
- Gap Between Candles (manual mode only) – sets the gap between consecutive HTF candles in manual mode.
- Offset from Last Bar (manual mode only) – shifts the entire HTF candle strip relative to the last chart bar. Negative values allow the strip to be moved to the left.
Current Candle
- Show Forming (Unclosed) Candle – enables or disables the display of the currently forming, unfinished HTF candle.
Candle Appearance
- Bullish Color – colour of HTF candles that close above their open.
- Bearish Color – colour of HTF candles that close below their open.
- Candle Body Fill Transparency (%) – sets the transparency of the HTF candle body fill and of the candle wick.
- Candle Body Border Transparency (%) – sets the transparency of the HTF candle body border.
Wick Appearance
- Wick Line Width – sets the width of the HTF candle wick. Applies in both Manual and Auto-Align mode.
FVG — Fair Value Gap
- Show FVG on HTF Candles – enables or disables the display of Fair Value Gap zones detected on the selected HTF.
- Mitigation Source – defines how FVG mitigation is detected: Wick or Close.
- Bullish Gap Color (gap up) – colour of bullish FVGs.
- Bearish Gap Color (gap down) – colour of bearish FVGs.
- FVG Fill Transparency (%) – sets the transparency of the FVG box fill.
- FVG Border Transparency (%) – sets the transparency of the FVG box border.
Alerts
- Bullish FVG Formed – fires when a new bullish Fair Value Gap is detected on the HTF.
- Bearish FVG Formed – fires when a new bearish Fair Value Gap is detected on the HTF.
- Bullish FVG Mitigated – fires when an active bullish FVG is mitigated.
- Bearish FVG Mitigated – fires when an active bearish FVG is mitigated.
█ APPLICATIONS
Higher-Timeframe Context Analysis
HTF Candles and FVG allows the higher-timeframe structure to be observed without the need to switch the main chart to a different timeframe.
This makes it possible to analyse HTF behaviour while remaining on the lower timeframe used for more precise price observation.
HTF FVG Analysis
Higher-timeframe FVG zones can be used as additional context when analysing the current price movement.
Because each zone is kept until the mitigation condition is met, the user can observe both active and historical imbalance areas.
Minimalist FVG Chart
Independent control of the transparency of individual elements allows the indicator to be adjusted to a very minimalist style.
With appropriate transparency settings for the candle body fill (which also controls the wick), the body border, and the FVG zones, it is possible to leave essentially only the higher-timeframe FVG zones on the price chart.
This enables the indicator to be used as a discreet HTF analysis layer without obscuring the current price action.
Observing the Forming HTF Candle
Enabling the current, unfinished candle makes it possible to watch its development in real time and to assess how its range and direction change with the movement of the lower timeframe.
█ NOTES
- The indicator does not generate BUY/SELL signals. Its main purpose is to provide higher-timeframe context and to visualise HTF FVGs. Indicator

Swing Anchored VWAP Deviation [Pineify]Swing Anchored VWAP Deviation
Overview
Swing Anchored VWAP Deviation maps volume-weighted equilibrium after a swing. Its line, field, marker, and dashboard encode origin, dispersion, zone, and volume status.
Problem Definition
Session VWAP resets by time even when the boundary is unrelated to a contextual swing. Manual anchors require hindsight; naive pivot automation can reset on small zigzags or imply knowledge before confirmation. Fixed-width bands also equate distances across tight and dispersed auctions. The invariant needed is a confirmed anchor, statistics beginning at the real swing without an early signal, and distance scaled by post-anchor volume.
Design Rationale
Confirmed left/right pivots provide structural origins. ATR-scaled distance from the latest opposing pivot filters small candidates; zero disables the gate. After acceptance, a finite replay covers pivot through confirmation, retaining the real statistical origin while delaying visible state until it is knowable. Online weighted moments reduce cancellation versus squared-price sums. Backward plots were rejected as misleading, and reset bars cannot trigger crosses caused only by the new frame.
Key Features
Confirmed swing anchors with an ATR prominence gate.
Online volume-weighted mean, variance, and nested bands.
Stable zone colors with optional markers, bar colors, wash, and dashboard.
Close-confirmed crosses and outer entries that ignore reset bars.
How It Works
HLC3 is the default source. On each closed bar, pivots use left/right windows. Distance from the latest opposing pivot is divided by ATR at the pivot bar; if both types confirm, the larger score wins.
Acceptance clears state and processes pivot through confirmation in order. Valid volume weights each sample. Online updates produce total weight, mean, and second moment; deviation is the square root of moment divided by weight. Later bars extend state once. Missing volume has zero weight, with no fallback.
Bands are AVWAP plus or minus selected deviation multiples. Close-to-AVWAP distance divided by deviation supplies sigma; a one-tick floor prevents zero division. Cyan/blue means positive deviation, orange/pink negative, and gray equilibrium. Low anchors are cyan and highs amber. Markers are placed on the swing after confirmation; bands start or jump at confirmation and never backfill.
How Multiple Indicators Work Together
This is one causal chain, not unrelated signals. Pivot confirmation defines origin; the ATR gate decides replacement; volume weights define equilibrium; weighted variance normalizes distance; and zone state drives visuals and alerts. Without confirmation there is hindsight ambiguity, without the gate there is reset noise, without volume equilibrium changes meaning, and without dispersion raw distances are incomparable.
Trading Ideas and Insights
Treat AVWAP as context for post-swing acceptance or rejection, not an entry command. Sustained closes on one side show where value is forming. An outer visit is large relative to volume-weighted dispersion, but does not choose continuation over mean reversion. Compare it with structure, liquidity, and holding period. Alerts are observation prompts, not orders or performance claims.
Unique Aspects
The contribution is confirmation-to-origin replay. Common automation either starts at the later confirmation bar or draws pivot history where the pivot was unknowable. This state includes genuine pivot-to-confirmation observations, yet changes visuals and alerts only after confirmation. Online weighted moments keep center and dispersion together; the opposing-swing gate limits trivial resets; reset suppression separates price movement from a changed frame.
How to Use
Begin with liquid stocks, futures, or crypto on roughly 15-minute to daily charts. Require Volume Weight ACTIVE in the dashboard. Read AVWAP as current equilibrium, the inner field as ordinary variation, and outer fields as larger normalized displacement. H or L marks the source swing but appears only after the right window completes. Configure each cross and outer-entry alert separately.
Customization
Left and Right Bars set swing scale and confirmation delay; larger values usually mean fewer, later anchors. Minimum Opposing Swing Distance filters in ATR units: raising it extends anchor life, while zero accepts all candidates. Source selects the weighted sample. Inner choices are 0.5, 1.0, and 1.5; outer choices are 2.0, 2.5, and 3.0. Field, markers, extreme wash, bar colors, and dashboard are independent switches, leaving AVWAP readable alone.
Assumptions and Limitations
Pivots arrive after Right Bars; marker location is not discovery time. The realtime bar can change AVWAP, variance, bands, colors, and dashboard, while anchors and alerts require a close. Volume must be reliable: absent, synthetic, delayed, or inconsistent data can remove output or distort the center. Results are path- and parameter-dependent because each anchor replaces the prior distribution. ATR gating can miss small turns or admit noisy large ones. Deviation is descriptive, not a probability guarantee, especially for skewed data. The script does not infer orders, profitability, or future price.
Conclusion
This indicator connects confirmed structure with volume-weighted distance while keeping timing auditable. Statistics originate at the swing, become visible only after confirmation, and expose volume, latency, reset, and realtime limits.
Indicator

Order Flow Profiler (Zeiierman)█ Overview
Order Flow Profiler (Zeiierman) is a price-based volume profiling indicator that estimates how buying and selling activity is distributed across different price levels within a selected chart window.
Rather than displaying only total volume, the indicator divides the selected auction range into individual price cells and estimates how much buying and selling activity occurred inside each area.
Each candle’s volume is separated into estimated buy and sell participation using its close position, candle body direction, and wick structure. That activity is then distributed across the price levels the candle touched.
The result is a two-sided Order Flow Profile that helps visualize where buyers and sellers were most active, where one side dominated, and where significant pressure imbalances developed.
⚪ Order Flow Profile
The profile is divided around a central spine.
Sell activity extends to the left while buy activity extends to the right.
The width of each profile row represents the estimated amount of activity occurring at that price level. Larger profile sections therefore highlight prices where more participation was concentrated.
When Delta Dominance is enabled, the indicator also compares estimated buy and sell activity inside each individual price row.
• Positive Delta extends to the right and highlights prices where buying activity is stronger.
• Negative Delta extends to the left and highlights prices where selling activity is stronger.
• Larger and more prominent Delta cells indicate a stronger imbalance between both sides.
This allows the profile to show both where activity occurred and which side dominated at each price level.
█ How It Works
⚪ Buy and Sell Volume Estimation
Each candle’s volume is divided into estimated buy and sell activity using its close position, body direction, and wick structure.
buyVolume = volume × buyShare
sellVolume = volume - buyVolume
⚪ Price Cell Distribution
The profile range is divided into Price Cells, and each candle’s estimated buy and sell volume is distributed across the prices it traded through.
Cell Concentration controls how tightly that activity is focused around its estimated buy and sell centers.
⚪ Control Price
The Control Price is the price cell with the highest combined buy and sell activity.
Its color shows which side is dominant at that level.
⚪ Acceptance Area
Starting from the Control Price, the indicator expands through neighboring cells until the selected percentage of total profile activity is included.
This produces the Upper Acceptance Level and Lower Acceptance Level shown in the Data Window.
⚪ Delta Dominance
Delta measures the difference between estimated buy and sell activity at each price cell.
delta = buyVolume - sellVolume
• Positive Delta shows buy dominance.
• Negative Delta shows sell dominance.
Stronger imbalances create larger Delta cells.
⚪ Pressure Detection
Pressure Flags detect significant diagonal imbalances between neighboring price cells.
Buy Pressure compares buying activity with sell activity below, while Sell Pressure compares selling activity with buy activity above.
▲ indicates Buy Pressure.
▼ indicates Sell Pressure.
⚪ Active Profile Readout
The live profile is divided into broader price segments that compare total buy and sell activity within each area.
• BUY x MORE shows buyer dominance.
• SELL x MORE shows seller dominance.
• BALANCED shows no meaningful directional advantage.
This provides a faster summary of directional activity across the profile.
⚪ Historical Profiles
Historical Profiles preserve earlier profile snapshots, including the profile wings, Delta, Control Price, range caps, and Pressure Flags.
This allows traders to compare how the auction structure changes over time.
█ How to Use
⚪ Identify High-Volume Areas
Wide sections of the profile show price levels where activity was higher. These areas can help highlight important zones of participation, support, resistance, or consolidation.
⚪ Use the Control Price
The Control Price marks the price level with the highest combined buy and sell activity.
Traders can use it as a key reference level for acceptance, rejection, or potential mean reversion.
⚪ Read Buy and Sell Dominance
The profile wings, Delta cells, and Active Profile Readout help show which side is stronger at different price levels.
• Buy dominance can support bullish continuation or absorption.
• Sell dominance can support bearish continuation or rejection.
• Balanced areas show more even participation between both sides.
⚪ Compare Historical Profiles
Historical Profiles help show how the auction changes over time.
A rising Control Price and stronger buy activity can suggest improving bullish participation, while a falling Control Price and stronger sell activity can suggest increasing bearish participation.
The profile is most useful when combined with price structure, trend, support and resistance, and the surrounding market context.
█ Settings
Lookback Bars: Sets how many chart candles are used to build the profile.
Price Cells: Controls the number of price levels used inside the profile.
Cell Concentration: Controls how tightly estimated buy and sell activity is distributed around each candle’s activity centers.
Pressure Ratio %: Sets how strong a buy or sell imbalance must be before a Pressure Flag can appear.
Historical Profiles: Enables previous profile snapshots on the chart.
Snapshot Every Bars: Sets how often historical profiles are created.
Active Profile Readout: Enables the segmented BUY, SELL, and BALANCED summary beside the live profile.
Segments: Controls how many price sections are used in the Active Profile Readout.
Balanced Below x: Sets how close buy and sell activity must be for a segment to display BALANCED.
Delta Dominance: Shows which side dominates at each individual price cell.
Pressure Flags: Enables buy and sell pressure markers.
Wing Width: Controls the maximum width of the buy and sell profile wings.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Indicator

Indicator

Multi_MADescription:
Multi MA plots four moving averages on a single chart, letting you monitor short-, mid-, and long-term trends at a glance.
Features
Four moving averages with fully customizable lengths (defaults: 7, 21, 60, 120).
Selectable MA type applied to all four lines: SMA, EMA, RMA, WMA, or VWMA. Switch types instantly from a single dropdown.
Adjustable line width for each average, so you can emphasize the ones that matter most to you.
Cross marker that highlights every crossover between the third and fourth averages (default 60 and 120) — a common signal for shifts in the longer-term trend.
How to use
The fast lines (7, 21) track momentum and short-term direction, while the slower lines (60, 120) define the broader trend. When the 60 crosses the 120, a "Cross" label marks the event, helping you spot potential trend transitions. Adjust the lengths and MA type to fit your instrument and timeframe.
Works on any symbol and timeframe. Overlays directly on price. Indicator

Indicator

Divergence + RS Multi-Ticker Scanner 30 (FX + Global Indices)Divergence + RS Multi‑Ticker Scanner 30 (FX & Global Indices)
A multi‑asset scanner designed for macro traders, currency analysts and global index watchers.
It combines divergence detection (RSI / MACD / Price) with Relative Strength (RS) analysis across
30 instruments covering major FX pairs, crosses, EM currencies and global equity indices.
This tool allows you to quickly identify trend strength, weakness, momentum shifts and divergence signals
across the world’s most important markets — all in one place.
Section 1 — Major FX
EURUSD
GBPUSD
USDJPY
USDCHF
USDCAD
AUDUSD
NZDUSD
Section 2 — FX Crosses
EURJPY
EURGBP
GBPJPY
AUDJPY
CHFJPY
Section 3 — Emerging Markets FX
USDZAR
USDMXN
USDTRY
USDPLN
Section 4 — US Indices
S&P 500 (SPX)
Nasdaq 100 (NDX)
Dow Jones (DJI)
Russell 2000 (RUT)
Section 5 — Europe Indices
DAX (DEU40)
FTSE 100
CAC 40
EuroStoxx 50
Section 6 — Asia Indices
Nikkei 225
Hang Seng
Shanghai (SSE)
ASX 200
Section 7 — Volatility
VIX
VXN
Features
Multi‑ticker divergence detection (RSI / MACD / Price)
Relative Strength vs SPX benchmark
Trend and momentum scoring
Color‑coded strength/weakness visualization
Multi‑asset macro overview in one panel
Use cases
Macro trend analysis
FX strength/weakness rotation
Global index comparison
Volatility monitoring
Divergence‑based trade setups
Tags: forex, fx, currencies, indices, globalindices, macro, scanner, divergence, rs, relativeresearch, trendanalysis, spx, nasdaq, dax, nikkei, eurusd, usdjpy, gbpusd, volatility, vix, multiasset, technicalanalysis, tradingstrategy
Categories:
Indicators
Technical Analysis
Forex
Indices
Macro & Economy
Indicator

Divergence + RS Multi-Ticker Scanner 30 (Metals & Commodities)Commodities Macro Scanner
A complete multi‑sector commodity scanner covering 30 instruments across metals, energy, agriculture, softs, ETFs and industrial materials. Includes continuous futures (1!), CFDs and ETFs for stable data and broad macro coverage.
Section 1 — Precious Metals
Gold (XAUUSD)
Silver (XAGUSD)
Platinum (XPTUSD)
Palladium (XPDUSD)
Section 2 — Industrial Metals
Copper (HG1!)
Aluminium (ALUMINIUM1!)
Nickel
Zinc
Lead
Section 3 — Energy
Crude Oil WTI (USOIL)
Crude Oil Brent (UKOIL)
Natural Gas (NG1!)
Section 4 — Agriculture
Wheat
Corn
Soybeans
Section 5 — Soft Commodities
Cocoa
Coffee
Sugar
Cotton
Orange Juice
Section 6 — Commodity ETFs
URA
LIT
DBC
GSG
GLD
SLV
USO
UNG
Section 7 — Industrial Materials
Steel Index
Lumber (LBR1!)
Purpose
Broad commodity market monitoring
Macro trend identification
Sector rotation analysis
Relative Strength workflows
ETF‑based commodity strategies
Multi‑asset portfolio context
Features
Clear sector grouping
Verified TradingView‑compatible tickers
Continuous futures for stable backtesting
Modular structure for easy expansion
Ready for RS, alerts, heatmaps, dashboards
Notes
All tickers verified for availability.
Continuous futures (1!) used for consistency.
Scanner can be expanded with RS ranking, alerts or auto‑sorting.
Tags: commodities, futures, macro, scanner, ETF, energy, metals, agriculture, softs, lumber, naturalgas, crudeoil, gold, silver, technicalanalysis, tradingstrategy
Categories:
Indicators
Technical Analysis
Commodities
Futures
Macro & Economy
Indicator

Indicator

Average Daily & Weekly Ranges ADR & AWR [D4A]The Average Daily Range (ADR)
The Average Daily Range (ADR) is a common metric used to measure volatility in an asset. It calculates the average difference between the highest and lowest price over a time interval – normally five days.
The range is calculated from the daily candle's open.
The Average Weekly Range (AWR)
Similarly, the Average Weekly Range (AWR) is a another metric that helps to gauge volatility in an asset and it works by calculating the average difference between the highest and the lowest price over a longer time interval - normally five weeks. Here, the range is calculated from the weekly candle's open.
This data allows the trader to see how the price of asset is behaving in current day or week compared to previous days and weeks. For example, if it's Wednesday and the weekly range is still below 30%, you can expect (although it's not guaranteed) that Thursday and Friday will try to catch up with the historical average and offer larger price movements.
What does the script do?
- Displays a little widget with ADR and AWR metrics as a percent of average range over selected period of time, eg. 5, 10 or 20 days (or weeks). The tooltip shows average range size for selected period.
- Shows the current day and week range size in given asset's metrics, eg. points for indices, pips for forex and so on.
- Draws the current day and current week range line markers on the right side of the chart (the position is user customizable)
- Draws historical daily and weekly ranges (5, 10 or 20 periods back) when enabled.
How does the script calculate the ranges?
Using request.security() function, the script reads official exchange/data-vendor daily bar — the same high/low you'd see if you switched the chart to a Daily timeframe. It's timeframe-independent (accurate whether you're viewing 1-minute or 1-hour bars) and reflects whatever session scope the data feed uses to build its daily candle (for continuous futures/forex, that's typically the full ~23-24 hour session, including the overnight/electronic session, not just RTH hours).
SETTINGS:
- Lookback Range (Days & Weeks) - select period of time which the script uses for calculation
- Low, Average, High, Very High - widget background colors that reflect current day's range % size: low < 50%, average < 100%, high < 150% and anything higher or equal 150% is marked as very high.
- BG Transparency - background transparency of the widget
- Don't Color Grade, Use One Color - you can use only one color which is independent of the size of the current ADR
- Show Today's Price % - shows the asset's current gain or loss %
- Show Week's Price % - shows the asset's current price gain or loss compared to the price at weekly open
- Up, Down, Even - the colors that symbolize gain, loss or even price
- Widget location - define the location of the widget on the chart
- Show current Average Day Range Marker Lines (ADR) - displays current ADR lines as markers on the right side of the chart
- Show Historical Daily Lines (true day extent) - displays current and historical ADR levels as full length lines
- High/Low - defines ADR+ and ADR- lines
- 1/3 High/Low - defines 1/3 ADR+ and 1/3 ADR- lines
- Offset left and Right - defines the beginning and end of the ADR marker lines
- Show current Average Week Range Marker Lines (AWR) - displays current AWR lines as markers on the right side of the chart
- Show Historical Weekly Lines (true week extent) - displays current and historical AWR levels as full length lines
- High/Low - defines AWR+ and AWR- lines
- 1/3 High/Low - defines 1/3 AWR+ and 1/3 AWR- lines
- Offset left and Right - defines the beginning and end of the AWR marker lines
- Labels - enable labels for the current day & week, define the size of label and right offset
The script should work on all asset types and all timeframes which are below daily timeframe for ADR and weekly timeframe for AWR.
-----------------
Disclaimer
The content provided in this script is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs. Indicator

Structural Liquidity & POC Matrix [BigBeluga]🔵 OVERVIEW
The Structural Liquidity & POC Matrix is a clean, automated price action terminal built to track institutional key levels. It isolates important market highs and lows over a set lookback period and instantly projects them onto your chart as trailing liquidity lines.
Additionally, the script calculates a dynamic volume profile between those major high and low structural markers. Instead of scattering lines everywhere, it neatly draws this volume breakdown on the right side of your workspace to reveal exactly where the heaviest trading occurred and highlights the Point of Control (POC).
🔵 FEATURES
The toolkit maps out key market interaction zones using a streamlined structural tracking framework:
1 — Dynamic Liquidity Range Tracking
Automated Sweep Highs & Lows: The engine scans your chart using a set lookback period ( Liquidity Length ) to find key historical highs and lows, drawing sharp levels right at those turning points.
Smart Fading Level Lines: Once a liquidity line is plotted, it trails forward until it hits a customizable timer limit ( Fade Liquidity ). The line smoothly fades out and resets over time, ensuring your chart stays perfectly clean.
Visual Breakout Diamond Markers: The exact moment price action breaks or shifts out of a previously established liquidity level, the script prints a sharp diamond symbol (◆) to flag the market sweep.
2 — Adaptive Sidebar Volume Profile & Matrix
Right-Side Profile Alignment: To keep your workspace completely clear of clutter, the script shifts the historical volume breakdown out of the way, plotting it onto the right margin of your screen ( Profile Offset ).
Structural Volume Distribution: The engine tallies up all volume traded between the active major high and low blocks. It dynamically projects the results as a clean structural polyline matrix block, colored to match the dominant market flow.
Point of Control (POC) Target Line: The system automatically scans your volume data to pinpoint the absolute heaviest volume node ( Point of Control (POC) ). It stretches a bright line ( POC Color ) from the start of the structure all the way through the profile to reveal major institutional fair value anchors.
// Volume Profile Array Bins & POC Target Index Lookup
volBins = array.new(size, 0.0)
for i = start to bar_index
price = close
binIdx = math.floor((price - profBot) / atr)
if binIdx >= 0 and binIdx < size
array.set(volBins, binIdx, array.get(volBins, binIdx) + volume )
maxVol = array.max(volBins)
pocBinIdx = volBins.indexof(maxVol) // Find the exact index of the POC
🔵 HOW TO USE
Integrating these structural matrix lines into an everyday trading plan follows a clear, step-by-step strategy structure:
Isolate the Active Range Boundaries: Monitor the top orange and bottom blue tracking lines to instantly map the current structural playing field. These trailing boundaries reveal exactly where short-term stops and market liquidity pool rest.
Locate the Institutional Fair Value Anchor: Look for the bright yellow Point of Control line stretching across the chart. This level shows you where the largest amount of volume has changed hands, identifying a strong support or resistance anchor for future retests.
Execute Trades Off Range Sweeps: Watch the chart closely when price sweeps past an outer liquidity line and prints a diamond indicator. If price snaps back inside the range, look to ride the reversal momentum straight across the matrix toward the yellow POC target line.
🔵 NOTES
Why this implementation is unique:
It acts as a compact, self-cleaning support and resistance tool by automatically fading out old level lines before they can crowd your screen.
Rather than forcing you to look at a fixed, unmoving session volume profile, it anchors its volume calculation directly between the active high and low price pivots.
The smart polyline rendering engine keeps your trading window uncluttered by cleanly shifting detailed volume histograms entirely over to the right margin space.
Indicator

Indicator

Uptrick: Adaptive Trend TrailIntroduction
Uptrick: Adaptive Trend Trail is a trend-following overlay indicator that holds one of three states, bullish, bearish or neutral, where neutral applies only before the first confirmed flip on the chart. That state is visualized through a layered ATR trail or volatility bands, colored candles, and reversal labels. Rather than deriving direction from a single crossover, the indicator builds a composite regime score from nine weighted measurements, requires agreement from three internally calculated adaptive Supertrends, and then applies confirmation, cooldown and hysteresis rules whose strictness changes with measured market conditions. It also includes a valuation meter and a set of internal simulation statistics displayed in the Data Window.
The design intent is to require more evidence before accepting a state change when measured directional efficiency is low, rather than to detect every turn as early as possible.
Originality
A trend state can be derived from a single measurement: a moving average cross, one Supertrend, or one oscillator threshold. Each responds to a different aspect of price and each has conditions where it carries less information. A long moving average responds slowly. A single volatility-stop line can change direction repeatedly when price oscillates within its band width. An oscillator carries no information about price structure or volatility state. This script combines measurements that are informative under different conditions, so that no single one can force a state change on its own, and it makes the strictness of the decision depend on measured market conditions rather than holding it fixed.
Why these specific components were chosen :
Directional efficiency (net movement over total path traveled over 10 bars) is used because it distinguishes directional movement from back-and-forth movement covering the same ground. Its inverse, chop, is the central control variable of the script. Chop is not only an input to the score; it directly changes how many Supertrends must agree, how many bars a signal must persist, how wide the hysteresis gate is, and how long the cooldown lasts. This is the mechanism that lets one configuration behave differently in high-efficiency and low-efficiency conditions without the user changing settings.
Three Supertrends at different ATR lengths (fast 9, medium 14, slow 21) are used instead of one because a single Supertrend returns a binary direction with no measure of agreement. Three produce a vote count, which serves both as a gate (how many must agree) and as a continuous input to the composite score (vote difference divided by three). Their ATR multipliers are not fixed: chop and volatility expansion are added on top of the user's base factor, so all three widen as efficiency falls or volatility expands.
Distance from the EMA baseline and momentum are both normalized by ATR rather than used raw. This expresses them relative to recent volatility and reduces their dependence on the instrument's absolute price scale, so the same threshold values remain meaningful on instruments with very different nominal prices.
Baseline slope and a slower HL2 baseline slope are included because distance alone does not distinguish a market moving away from its mean from one moving back toward it. Two slopes at different speeds mean a short-term push against a flat longer-term structure contributes less to the score than an aligned move.
RSI is included with a small weight (0.08) as a momentum cross-check rather than as a signal generator. At that weight it cannot on its own carry the score past the gate.
Candle pressure (body direction and close location within the bar) and structure breaks (close beyond the prior N-bar high or low) are included with small weights (0.05 each) because they respond on the current bar, adding a small amount of immediacy to a score otherwise built from lagging averages.
How they work together : the nine fields are blended into one regime value smoothed by a 3-period EMA. That value must exceed a dynamic gate whose size grows with selectivity, chop and volatility deviation. Price must also be displaced from the baseline. Momentum must have the correct sign. The Supertrend vote must be confirmed and persistent. Only then does a candidate exist, and the candidate must persist for one to three consecutive bars depending on chop, with a cooldown of six to ten bars since the last flip. A separate strong-move path can bypass the candidate persistence requirement and the cooldown when all three Supertrends agree unanimously, the score exceeds the gate by an additional margin, momentum is strong and efficiency is above 0.42. It does not bypass the underlying Supertrend persistence requirement. Finally, a takeover rule requires the fast Supertrend plus at least one slower one to agree with the new direction, so a flip cannot occur against the shorter-term Supertrend structure.
The valuation meter and the internal simulation exist to provide context on the same chart rather than requiring separate indicators: one shows where smoothed RSI currently sits on a segmented scale, the other reports how the script's own state changes would have resolved under a simple trailing-stop assumption.
Features
Single trend state driving all visuals, bullish or bearish once the first flip occurs, neutral before that point
Composite regime score built from nine weighted fields, blended and smoothed with a 3-period EMA
Weighting: baseline distance 0.22, Supertrend consensus 0.20, momentum 0.19, baseline slope 0.14, slow baseline slope 0.10, directional efficiency 0.09, RSI 0.08, candle pressure 0.05, structure break 0.05
Directional efficiency engine measuring net movement against total path over 10 bars, producing a chop value used throughout the script
Volatility regime measurement comparing current ATR to its 50-period EMA, producing expansion and deviation values
Three internally calculated Supertrends (fast, medium, slow) used for logic only and not plotted on the chart
Adaptive Supertrend factors, where chop and volatility expansion are added on top of each user-set base multiplier, with the slow Supertrend receiving the largest adjustment
Vote-based Supertrend consensus requiring two of three in normal conditions and three of three when chop exceeds 0.70
Supertrend persistence requirement of one confirmed bar normally and two when chop exceeds 0.72
Dynamic hysteresis gate that widens with the selectivity input, with chop, and with volatility deviation
Price displacement filter requiring close to be above or below the baseline by an ATR-scaled amount
Momentum sign filter requiring directional momentum beyond a small deadband
Adaptive confirmation requiring one, two or three consecutive candidate bars depending on measured chop
Strong-move path that can bypass the candidate confirmation requirement and the cooldown when all three Supertrends agree, the score clears the gate by an additional 0.26, momentum exceeds 0.16 and efficiency exceeds 0.42, while still requiring Supertrend persistence
Takeover rule requiring the fast Supertrend plus one slower Supertrend to align with the new direction before any flip
Adaptive cooldown of six to ten bars between state changes, scaled by chop
All state changes evaluated on confirmed bars only, so the state does not flip on an unclosed bar
Trail overlay mode with three layers constructed at 0.55, 1.15 and 1.60 ATR multiples from the smoothed baseline, placed below it in bullish states and above it in bearish states, scaled by the width input
Bands overlay mode with three levels on each side of the baseline at 1.30, 2.00 and 2.90 ATR multiples, scaled by the width input, using an additional smoothing stage applied to the already-smoothed baseline and ATR
Overlay None mode that hides the Trail and Bands while leaving the other independently controlled outputs available
Smoothness control applied to the baseline and ATR used for the overlay geometry
Trend candles that recolor the price bars to the active state
Reversal labels printed on the bar where the state changes, placed relative to the outer trail layer
Valuation meter drawn as a table with a segmented scale and a pointer showing where 3-period smoothed RSI(14) currently sits
Four meter sizes: Off, Compact (11 segments), Normal (17 segments) and Large (25 segments)
Six meter positions covering top and bottom, left, center and right
Internal historical trade simulation driven by the script's own state changes, reported in the Data Window
Simulation outputs: return percent, win rate percent, profit factor, maximum drawdown percent and closed trade count
Simulation uses a fixed 10000 starting equity and full-equity sizing, with a fee equal to 0.1 percent of entry equity deducted at entry and a further amount equal to 0.1 percent of that same entry equity applied at exit
Simulation stop is set from the outer trail on the entry bar, constrained to at least one minimum tick beyond the entry close, and thereafter can only move in the position's favorable direction using the previous bar's outer trail value
Simulation return figure includes unrealized profit or loss on any position still open, so it is not a closed-trade-only figure
Two alert conditions, one for the bullish flip and one for the bearish flip, each carrying the ticker in the message
Inputs
Group 01, Trend Engine
Trend Length, default 34, range 10 to 200. Sets the primary EMA baseline used for the overlay, the distance field and the baseline slope field. It also determines two internally derived lengths: the slower HL2 baseline is calculated at approximately 70 percent of this value with a floor of 10, and the structure-break lookback is approximately 12 percent of this value with a floor of 3.
Momentum Length, default 12, range 3 to 100. Lookback used to measure directional momentum before ATR normalization.
Signal Selectivity, default 0.35, range 0.10 to 1.25. Raises both the hysteresis gate and the required price displacement. Higher values produce fewer state changes.
Group 02, Supertrend Confirmation
Fast Length, default 9, range 2 to 100. ATR length of the fast internal Supertrend.
Fast Factor, default 1.45, range 0.25 to 10.0. Base ATR multiplier of the fast internal Supertrend before adaptive widening.
Medium Length, default 14, range 2 to 150. ATR length of the medium internal Supertrend.
Medium Factor, default 1.95, range 0.25 to 10.0. Base ATR multiplier of the medium internal Supertrend.
Slow Length, default 21, range 2 to 200. ATR length of the slow internal Supertrend, acting as the broader continuation confirmation.
Slow Factor, default 2.55, range 0.25 to 10.0. Base ATR multiplier of the slow internal Supertrend.
Group 03, Overlay
Overlay, default Trail, options Trail, Bands, None. Selects which overlay geometry is drawn, or hides both.
Width, default 1.00, range 0.40 to 2.50. Scales the distance of all trail layers and all band levels from the baseline. Because the internal simulation uses the outer trail layer as its stop, this input also changes the Data Window statistics. It does not affect the trend engine.
Smoothness, default 5, range 1 to 20. Smooths the baseline and ATR used to build the overlay geometry, and is applied a second time to those already-smoothed values when Bands mode is selected. Because the outer trail layer is built from these smoothed values, this input also changes the Data Window statistics. It does not affect the trend engine.
Group 04, Valuation
Meter Size, default Normal, options Off, Compact, Normal, Large. Controls whether the meter is shown and how many segments it uses.
Position, default Top Center, options Top Left, Top Center, Top Right, Bottom Left, Bottom Center, Bottom Right.
How It Works
The baseline is an EMA of close over the Trend Length. ATR(14) is the volatility unit and is floored at one tick to avoid division problems on illiquid data.
Directional efficiency is the absolute 10-bar net price change divided by the sum of the absolute bar-to-bar changes over the same window, clamped between 0 and 1. Chop is one minus that value. Efficiency is signed by the 10-bar direction to form the efficiency field.
Volatility regime compares current ATR to its 50-period EMA. Expansion is the amount above one, clamped to 1.25. Deviation is the absolute distance from one, clamped to 1.50.
The three Supertrend factors are the user's base values plus a chop term and a volatility expansion term. Their directions become bullish or bearish votes. The vote requirement is two of three normally and three of three when chop exceeds 0.70, and the confirmed vote must persist for one confirmed bar, or two when chop exceeds 0.72.
Nine fields are then blended. Distance from baseline and momentum are divided by ATR and clamped. Baseline slope and slow baseline slope are three-bar changes divided by ATR and clamped. RSI(14) is centered on 50 and clamped. The Supertrend field is the vote difference divided by three. Candle pressure combines body direction and close location within the bar. Structure is plus one when close breaks the prior N-bar high and minus one when it breaks the prior N-bar low. The weighted sum is smoothed with a 3-period EMA to produce the regime value.
The gate is 0.22 plus selectivity times 0.12, plus chop times 0.085, plus a volatility deviation term capped at 0.06. A bullish candidate exists when the regime exceeds the gate, close is above the baseline by the required ATR displacement, momentum is positive beyond its deadband, and the bullish Supertrend consensus is persistent. The bearish candidate is the mirror.
A candidate must persist for one bar in high-efficiency conditions, two when chop exceeds 0.40, and three when chop exceeds 0.72. The strong-move path can bypass that candidate persistence requirement and the cooldown, but only when all three Supertrends agree, the regime clears the gate by an additional 0.26, momentum exceeds 0.16 in absolute terms and efficiency is above 0.42. Because the strong-move path is itself built on the candidate condition, it does not bypass the Supertrend persistence requirement. It is intended to provide a faster response when directional evidence is unusually strong under the script's own measurements.
Before any flip is accepted, the takeover rule requires the fast Supertrend and at least one of the medium or slow Supertrends to be aligned with the new direction. A cooldown of six bars plus up to four additional bars scaled by chop must also have elapsed since the last flip, unless the strong-move path is active. All of this is evaluated on confirmed bars only.
When the state flips, the counters reset, the label prints, the candles recolor and the overlay switches sides. Before the first flip on a chart the state is neutral, candles are yellow, and the trail layers sit flat on the baseline.
The valuation meter takes RSI(14), smooths it with a 3-period EMA, and maps it onto the selected number of segments with a pointer. It is a positioning display for smoothed RSI and nothing more; it does not measure fair value and is not part of the trend decision.
The Data Window values come from a simplified internal historical trade simulation implemented inside the indicator. The script is an indicator, not a TradingView strategy, so these are not Strategy Tester results and no Strategy Tester properties apply. The simulation opens a position at the close of each flip bar and closes it on either an opposite flip or a stop. The stop is set on the entry bar from the outer trail, constrained to at least one minimum tick beyond the entry close, and thereafter can only move in the position's favorable direction using the previous bar's outer trail value. Starting equity is 10000, the full equity is used on every position, a fee equal to 0.1 percent of entry equity is deducted at entry, and a further amount equal to 0.1 percent of that same entry equity is applied at exit. Win rate and profit factor are classified on the fee-inclusive result of each position. The return figure is calculated from equity including unrealized profit or loss on any position still open, so it is not a closed-trade-only figure.
These assumptions are deliberately simplified. The purpose is to compare the effect of different settings against one another on the same symbol, not to model a tradable account. Full-equity sizing is used so the figures are not dependent on an arbitrary position size choice, and no sizing shown here is being recommended. No slippage, spread, funding cost or gap-through-stop execution is modelled, so the simulation does not reproduce actual execution conditions and may differ materially from live trading. There is no take profit and positions are never partially closed. These values describe the script's own historical state changes under those assumptions and are not evidence about future behavior.
How to Use
Add the indicator to a clean chart and read the current state from the candle color and the overlay side. In Trail mode the layers are constructed below the smoothed baseline while the state is bullish and above it while the state is bearish. In Bands mode the three levels on each side show how far price has extended from the baseline in ATR terms.
Increase Signal Selectivity if you are getting more state changes than you want, or increase Trend Length for a slower baseline. Increase the Supertrend factors to require larger moves before the internal confirmation layer will agree. Reduce the factors and lengths for faster and noisier behavior on lower timeframes.
Width and Smoothness do not affect the trend engine, so flips and alerts are identical regardless of their values. Both do change the Data Window statistics, because the stop used by the internal simulation is drawn from the outer trail layer.
The two alerts fire on confirmed bars when the state changes. Treat the Data Window values as a rough comparison tool between settings on the loaded symbol and history, subject to the assumptions listed above.
Limitations to be aware of: because confirmation, persistence, takeover and cooldown conditions must all be satisfied before a state change is accepted, a flip can occur after price has already moved some distance from where the previous state ended. During lower-efficiency conditions the script requires additional Supertrend agreement and additional confirmation bars, which increases that distance further. These mechanisms intentionally prioritize confirmation over earliest possible detection, and that trade-off cannot be removed by settings, only shifted. Values on the current unclosed bar can change until that bar closes, since state changes are only committed on confirmed bars. The chart begins in a neutral state until the first flip is accepted. Behavior varies substantially between symbols and timeframes, and the defaults are a starting point rather than an optimized configuration.
Conclusion
Uptrick: Adaptive Trend Trail derives a trend state from nine weighted measurements rather than a single crossing, and makes the strictness of that decision a function of measured directional efficiency and volatility through the chop and volatility terms. The overlay, the trend candles, the valuation meter and the internal simulation are there to make that state and its context readable on one chart. It is a decision-support tool for discretionary trend reading and is intended to be used alongside your own analysis and risk management rather than as a standalone system.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice and does not constitute a recommendation to buy or sell any instrument. All trading involves risk and can result in substantial losses. Leveraged products can involve additional risks that depend on the instrument, broker and account structure. Past behavior of this indicator, including any statistics it displays, does not predict or guarantee future results. Signals, statistics and visuals vary across symbols, timeframes and market conditions. You are solely responsible for your own trading decisions and should test any tool thoroughly and apply your own risk management before using it with real capital. Indicator
