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.
อินดิเคเตอร์

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.
อินดิเคเตอร์

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. อินดิเคเตอร์

Return Dispersion Matrix [The Quant Science]Introduction
The Return Dispersion Matrix is a quantitative analysis tool that maps the temporal dependence of returns. In technical terms, performs a two-dimensional, 1-lag autocorrelation analysis, measuring the relationship and relative frequency between the return of the previous session (Yesterday) and that of the current session (Today) within specific volatility ranges.
It answers the key questions:
💭 🔑 “When a candle closes in the green or red, what is the most common range of returns?”
💭 🔑 “When the price did X yesterday, what does it probably do today?”
What does this indicator do?
1. Automatically calculate the probability of future returns for a given range of values and display the result in the right-hand column.
2. Instantly identify the market trend using the quadrants. Calculates the quadrant with the highest number of points and highlights it by lighting it up.
🟢 Q1
A green candle followed by another green candle
High concentration of points indicates that positive days tend to generate immediate additional momentum
Suitable for trend-following and bullish breakout strategies
🟢 Q2
A red candle followed by a green candle
Heavy trading volume indicates a “resilient” market: buyers step in immediately when prices fall (“buy the dip”)
Suitable for accumulation strategies on pullbacks
🔴 Q3
A red candle followed by another red candle
Indicates that sales generate further sales without immediate support
Sign of underlying weakness or persistent downtrends
🔴 Q4
A green candle followed by a red candle
There are many indications that rallies are short-lived and lead to rapid profit-taking in the Suitable for “sell the rally” strategies
The horizontal X-axis represents the return of the previous candle (t-1), while the vertical Y-axis shows the return of the current candle (t). This allows you to visually determine whether a positive or negative day tends to be followed by one of the same sign (persistence) or the opposite sign (mean reversion).
X-axis
To the right of 0: previous candle closed in positive territory (+)
To the left of 0: previous candle closed in negative territory (-)
Y-axis
Above 0: current candle is closing / has closed in positive territory (+)
Below 0: current candle is closing / has closed in negative territory (-)
3. Automatically calculates volatility bands. It identifies the maximum range observed during the analysis period and divides the positive values into bands. These values are displayed in the left column in white.
4. Automatically calculates frequency clusters. The density and transparency of the points immediately reveal where most sessions are concentrated and which events represent anomalies or extreme outliers.
Uses
Identifying the Market Regime
Observing the concentration of points reveals the prevailing nature of the asset:
Q1 / Q3 Prevalence (Trend / Inertia): The market tends toward continuation. The best strategy is to buy on breakouts or sell on support breaks.
Prevalence of Q2 / Q4 (Mean Reversion): Buying at highs is statistically a losing strategy.
Assessment of Asymmetry and Risk Management (Fat Tails)
By comparing the vertical extent of the points on the positive and negative sides:
If, on the negative side (Q3 / Q4), the points frequently reach the extreme ranges (e.g., -L4 or -L5), while on the positive side they stop at +L2, the asset exhibits asymmetric downside volatility (crash risk). Essential for the correct calculation of position sizing and for the strategic placement of stop-loss orders.
Operational Execution Filter (Probabilistic Edge)
The tool acts as a statistical validator before entering the market:
Example: A trader wants to go long on an asset. The matrix shows that, under current conditions, Quadrant Q2 has a frequency of 45% (high probability that a red day will be followed by a green day). Instead of buying during the positive candle, the trader waits for a negative session to close before placing a buy order at the next opening, thereby maximizing expected return.
Settings
Traders can easily adjust the indicator's parameters using the user interface.
Data Points Visualization: adjust the number of points within the matrix
Matrix Offset: move the table to the right on the graph
Levels Color: set the indicator colors
Highlight Dominant Quadrant: apply automatic calculation of the winning quadrant
อินดิเคเตอร์

CAN SLIM CheckerWHAT THIS IS
A single diagnostic table that scores the chart's symbol against William O'Neil's CAN SLIM criteria - 17 pass/fail checks plus 4 informational rows - and tells you plainly which ones it clears, which it fails, and which cannot be evaluated because the data does not exist.
Every row shows three things: the actual value , the threshold it has to clear , and the verdict . The threshold string is generated from the same input the pass/fail test reads, so retuning a setting can never leave the table displaying a stale target.
Every check is evaluated on every bar, not just the last one, so the chart background can be shaded across the whole history wherever the symbol met a threshold you set. That turns a snapshot into a timeline: you can see which stretches of a stock's past actually satisfied CAN SLIM and which did not.
This is a checker, not a signal generator . It plots no entries, no arrows, no alerts. It answers one question - how much of CAN SLIM does this stock actually satisfy right now, and when has it satisfied it before - and shows its working.
WHERE CAN SLIM COMES FROM
CAN SLIM is the growth-stock methodology William J. O'Neil set out in "How to Make Money in Stocks" (1988), derived from a study of the biggest US stock market winners going back to the 1950s. It is an acronym for seven characteristics those winners shared before their major advances:
C - Current quarterly earnings up sharply. O'Neil's floor: +25% year over year; he preferred 40%+.
A - Annual earnings growth of 25%+ in each of the last three years, with return on equity of 17%+.
N - Something New: a new product, new management, or a new price high. O'Neil bought new highs, not bargains.
S - Supply and demand: a smaller float moves further on the same demand, and volume should be flowing in on up days.
L - Leader, not laggard: buy the best-performing stocks, not the cheap ones.
I - Institutional sponsorship: funds should be accumulating it.
M - Market direction: three of four stocks follow the market, so nothing else matters in a correction.
This script implements each letter as one or more concrete tests. Where O'Neil's criterion cannot be computed from data Pine Script can reach, the row says so instead of substituting something weaker and calling it a pass.
HOW EACH LETTER IS CALCULATED
C - Current quarterly earnings
Quarterly EPS (diluted by default, basic as fallback) against the same quarter a year ago, and the same for revenue. Optionally the prior quarter must clear the threshold too, because O'Neil wanted a run of strong quarters rather than one good print. A loss turning into a profit has no percentage growth rate, so it is detected separately and counted as a pass. A fourth row shows whether growth is accelerating quarter over quarter - O'Neil's ideal, not his floor, so it is informational and never scored.
Reaching "four reports ago" needs care. request.financial() returns step series that only change when a filing posts, so the usual change-detection trick fails silently whenever two consecutive reports carry an identical value - which share counts do constantly:
// Breaks when two reports carry the same value - the occurrence is skipped
// and this silently reads 5 or 6 reports back instead of 4.
ta.valuewhen(ta.change(totShares) != 0, totShares, 4)
// One report clock, driven by revenue, which effectively never repeats.
newFQ = f_moved(revFq)
shares4 = ta.valuewhen(newFQ, totShares, 4)
A - Annual earnings
Annual EPS growth in each of the last three fiscal years, all three required. Return on equity from the latest annual report. Debt-to-equity computed from TOTAL_DEBT / TOTAL_EQUITY rather than the packaged ratio field so the units are unambiguous, displayed alongside its own value a year earlier, because O'Neil cared about the direction of leverage as much as the level.
N - New high
Distance below the 52-week high on daily bars, upgrading to NEW HIGH when today sets one. Two informational companions: breakout volume against the 50-day average (only meaningful within 2% of the high), and distance above the 50-day MA as a climax warning - a stand-in for O'Neil's "never chase more than 5% past the pivot", since Pine cannot locate a pivot without base detection.
S - Supply and demand
Free-float share count, share-count change year over year (buybacks pass, dilution fails), and the up/down volume ratio: volume on up-closes divided by volume on down-closes over the lookback.
L - Leader
Three tests:
The stock holding above its own 50- and 200-day moving averages.
The RS line (close divided by the index) at or near its own 52-week high. O'Neil's ideal breakout has the RS line making a new high with or before price.
An IBD-weighted 12-month momentum score - 40% on the 3-month return, 20% each on the 6/9/12-month legs - required to beat the index's own score.
I - Institutional sponsorship
This one is honestly not computable. request.financial() exposes no ownership, fund-count or 13F data, so the row is permanently gray and excluded from the score rather than faked. A liquidity proxy sits beside it - 50-day average dollar volume and a minimum share price - which establishes that institutions COULD hold it, not that they ARE buying it.
M - Market direction
Three rows feeding a three-state gate:
Index structure - the market symbol above its 21-day EMA and 50-day SMA, with the 50 above the 200. Deliberately slow; this is the "is the tide in" question.
Power Trend - IBD's own rule set, and the reason a plain fast-MA cross is the wrong tool for a market gate. It turns ON only when four conditions hold simultaneously: the index LOW has stayed above the 21-day EMA for 10 straight sessions (not merely the close - the index has not even dipped to it), the 21-EMA has held above the 50-SMA for 5 sessions, the 50-SMA is rising, and today closed up. It ends on a 21/50 cross back down, or on a circuit breaker: a close under the 50-SMA while already 10% off the three-month high. Those persistence counters are what stop a fast pair of averages whipsawing the gate.
Distribution days - index closing down 0.2%+ on volume higher than the previous session, counted over a rolling 25-session window, with days retired once the index rallies 5% above the close of that day. IBD treats 5-6 as a correction signal.
Those three produce a state rather than a boolean, because "not a confirmed uptrend" and "get out" are different instructions:
CONFIRMED UPTREND - Power Trend on, distribution contained. Buy normally.
UNDER PRESSURE - One of those failing but the index still holds its 50-day. Smaller size, best setups only.
CORRECTION - Power Trend off with the 50-day lost, or distribution past the danger threshold. The one O'Neil said to sit out.
By default a correction stamps the score row regardless of how good the stock looks, which is what O'Neil meant when he called M the most important letter.
THE BACKGROUND SHADING
The chart is shaded on every bar where the symbol met a CAN SLIM bar you define, so the qualifying windows are visible across history instead of only the latest reading. An optional second shade marks bars where the stock cleared your bar but the market gate vetoed it - the setups worth remembering, where the stock was ready and the tape was not.
Three conditions must all hold, and the third is the one that matters:
An absolute floor on the number of checks passed.
A percentage floor on passed / evaluable.
A data-coverage floor on how many checks resolved at all.
Unresolved rows leave the denominator rather than counting as failures, which is correct for a checker but has a nasty consequence for shading: a symbol with almost no reported financials posts a clean 3 / 3 and would shade its entire chart green on nothing at all. The coverage floor refuses to shade until enough checks actually resolved. Without it the shading would be brightest exactly where the data is thinnest, which is the opposite of useful. Keep that floor high.
What the shading is, and what it is not. It is honest about time: request.financial() delivers each figure on its publication date, so a bar in 2019 only ever sees numbers that were public in 2019. There is no lookahead and the green stretches are real. It is not a backtest . It says "this symbol met your bar here", never "buying here worked" - no entry, no exit, no position and no return is implied or computed anywhere in this script.
Turning the market-gate requirement off is worth doing deliberately: it shows whether a name held up THROUGH a correction, which is where O'Neil looked for the next cycle's leaders.
HOW TO USE IT
Put it on a daily chart of an individual stock. Everything price- and volume-based is pulled from a daily request.security() on the chart's own symbol, so the moving averages, the 52-week high and the momentum legs stay correct on weekly, monthly and intraday charts too. One row - the RS line's own 52-week high - cannot be built that way and grays out on intraday charts rather than reporting a nonsense number.
Read the market state row first. In a correction, the rest of the table is academic.
Read the score as a fraction of what was resolvable , not out of 17. Gray rows leave the denominator rather than being waved through, so 13/13 on a symbol with no financial data means far less than 13/17.
Set the shading thresholds to your own standard, then scroll back. The green stretches tell you how often and for how long this name has actually met that standard. The Shading row in the table explains why the current bar is or is not shaded, and how many bars the current run has lasted.
Use the tooltips. Every row carries the rule it implements, its limitations, and why it fails when it fails. Hover the row name.
Scrub the Data Window for raw numbers on a historical bar. The table itself always reflects the most recent bar.
Best used as the last filter before a watchlist entry, or as a post-mortem on a position that is not working. It will not find candidates for you - point it at names you already like.
SETTINGS
C - Current Quarterly Earnings
Use diluted EPS (on) - Diluted accounts for options and convertibles; basic flatters heavy issuers. Falls back to basic when diluted is unavailable.
Min EPS YoY growth (FQ) % (25) - O'Neil's stated floor. He preferred 40%+.
Require the prior quarter to clear it too (on) - Demands a run of quarters, not one print.
Min Sales YoY growth (FQ) % (20) - EPS growth without revenue behind it is cost-cutting.
A - Annual Earnings Growth
Min annual EPS growth, each of last 3 years % (25) - All three years must clear it.
Min Return on Equity % (17) - O'Neil's efficiency threshold.
Max Debt / Equity (1.0) - Industry-dependent. Utilities and REITs fail this by construction.
N - New High
Max distance below 52-week high % (15) - The buyable zone: basing near highs, not repairing damage.
Min share price (10) - Institutions largely cannot buy below this. Folded into the liquidity row rather than scored separately.
Breakout volume vs 50-day avg (x) (1.4) - O'Neil wanted 40-50%+ above average on the breakout. Informational.
Climax warning: % above 50-day MA (12) - Proxy for "too extended to start". Informational.
S - Supply & Demand
Max float (millions of shares) (100) - O'Neil's 1988 examples used under 25M; floats have inflated since.
Max shares-outstanding growth YoY % (2) - New supply works against the holder.
Up/Down volume lookback (daily bars) (50) - Window for the accumulation ratio.
Min U/D volume ratio (1.0) - 1.0 is neutral; real leaders usually read 1.25+.
L - Leader
Max RS-line distance below its 52-week high % (5) - How close to a new RS high counts as leadership.
Required momentum margin over index (0) - Zero means "merely beating the market", a low bar in a bear market. Raise it to demand real leadership.
I - Institutional (proxy only)
Min avg daily dollar volume ($ millions) (20) - Depth at which funds CAN build a position. Not evidence that they are.
M - Market Direction
Market index (AMEX:SPY) - SPY rather than SPX because distribution days need volume and SPX has none. Use QQQ for tech-heavy portfolios.
Distribution-day window (days) (25) - IBD's trailing count.
Max distribution days (4) - Pass threshold.
Distribution-day decline threshold % (0.2) - How far down counts as distribution.
Expire a distribution day after a rally of % (5) - IBD retires days the index has rallied past. Set 0 to count purely by age.
Power Trend: days the low must hold above the 21-EMA (10) - Persistence condition 1.
Power Trend: days the 21-EMA must hold above the 50-SMA (5) - Persistence condition 2.
Power Trend circuit breaker: % below 3-month high (10) - The rare early exit in a fast decline.
Distribution days that force a correction call (6) - Above the pass threshold but at or below this reads UNDER PRESSURE; beyond it, CORRECTION.
Treat M as a gate (on) - Off makes M ordinary points in the score.
Gate blocks when the market is (Correction only) - Or "Correction or Under Pressure" for a stricter stance.
Background Shading
Shade the chart while the score qualifies (on) - Paints the background on every bar meeting the criteria below.
Min checks passed (12) - Absolute floor, out of 17 scored checks. The main dial.
Min % of evaluable checks passed (70) - Ratio floor on top of the absolute one. Both must be satisfied.
Min evaluable checks, data coverage floor (12) - The guard that makes this honest. Refuses to shade until enough checks actually resolved, so a symbol with no reported financials cannot shade green on a 3 / 3. Keep it high.
Also require the market gate to allow buying (on) - Applies the same three-state gate the score row uses. Off judges the stock alone.
Shade differently when only the market blocks it (on) - A second shade for bars where the stock cleared your bar and the market vetoed it.
Qualifying shade / Stock-only shade - Colour pickers, so you can tune them to your chart theme.
Display
Table position (Top right) - Five anchor points.
Layout (Full) - Full = all 21 rows, 5 columns, plus the Shading status row. Compact = 17 scored rows, shortened labels, informational rows dropped. Minimal (phone) = one row per CAN SLIM letter with that letter's tally, 9 rows total. The score and the shading are identical in all three - layouts hide rows, they do not skip arithmetic.
Table text size (Small) - Auto scales to the chart pane, which is usually what you want on a phone.
Show the "Needs" column (on) - The threshold column. Turning it off collapses the column rather than leaving an empty strip.
LIMITATIONS - READ THESE
The shading is not a backtest and not a strategy. It marks bars where the symbol met a threshold you chose. No entry, exit, position or return is implied or computed anywhere in this script, and a long green stretch is not evidence that trading it would have worked.
Institutional sponsorship cannot be evaluated. No ownership or 13F data exists in Pine. That row is permanently gray by design. Check IBD's Accumulation/Distribution rating or 13F filings directly.
The L rows are not IBD's RS Rating. That rating is a percentile rank across the entire market; a Pine script sees one symbol at a time. The RS line and the weighted momentum score are single-symbol stand-ins, and beating the index is a floor, not a top-20% ranking.
No base or pivot detection. There is no cup-with-handle recognition, no pivot point, no proper buy point. "Within 15% of the high" will keep passing stocks that are 14% down in a downtrend - pair it with the 50/200-day row before trusting it.
Float is an annual figure. TradingView publishes FLOAT_SHARES_OUTSTANDING only as FY, so it can be up to a year stale, and it is missing outright for many symbols.
Annual rows need history. Three years of annual growth requires four annual reports inside the chart's history - roughly five years of bars. Recent listings show gray, and the early years of any chart will sit unshaded for want of data rather than want of quality.
Restatements are not modelled. Each figure appears on its publication date, which is what keeps the history free of lookahead, but a later revision is not reflected back onto the bars it would have changed.
Fundamentals are as reported by TradingView , which is GAAP. IBD works from adjusted operating earnings, so numbers will not match IBD's screens exactly.
Non-equity symbols (indices, forex, crypto) have no financials at all. Most rows will be gray, the score will be small and meaningless, and the coverage floor will correctly refuse to shade anything.
The current day's volume is still forming until the close, so the breakout-volume row and today's distribution-day count can move intraday.
NOTES
Open source - read the code. The header comment documents every design decision and every place a shortcut was taken. Built in Pine Script v6.
This is a research and education tool. It is not financial advice, not a recommendation to buy or sell anything, and no combination of green rows or green bars predicts a future price. CAN SLIM is a rules framework for narrowing a universe, not a system with an edge you can automate. Do your own work.
อินดิเคเตอร์

Vol Premium GaugeIf you sell options, covered calls, puts, condors, whatever, the question is always the same: am I getting paid enough?
Implied vol is what the market thinks will happen. Realized vol is what actually did. The gap between them is the insurance premium sellers collect. When it is fat, great. When it is thin or negative, you are picking up pennies in front of a steamroller.
This applies beyond vanilla options. If you run concentrated liquidity on an automated market maker you are effectively short a straddle, selling gamma in exchange for fees, and the same logic holds: you want to provide liquidity when implied vol is rich relative to realized, because that is when the fees are most likely to outpace the impermanent loss. When the premium is thin you are giving away optionality for very little.
This puts that IV versus RV relationship on your chart.
The IV line pulls a real volatility index, and only a real one: VIX on the S&P, VXN on the Nasdaq, GVZ on gold, OVX on crude, DVOL on bitcoin. The dashboard names the index it used.
If the instrument on your chart has no volatility index of its own, this reports no premium at all. That is deliberate. A premium is the gap between what the market charges and what actually happened, so estimating the first half from the second half measures your own estimator rather than the market. Realized vol still plots in three windows, fast, standard and slow, so you can see whether recent vol is spiking or compressing, and the verdict row reads RV ONLY.
An earlier version scored every non-crypto symbol against VIX, which is the implied vol of the S&P rather than of the stock in front of you. A typical single name realizes well above VIX, so the spread came out negative and it read "cheap" on nearly everything. That is fixed by refusing to guess rather than by guessing better.
The histogram is the spread, IV minus RV. Green when the premium is fat, red when thin. The filled area between the lines makes the relationship obvious at a glance, and price bars colour in the rich and cheap zones so you can read it without switching panes.
The dashboard carries IV Rank and Percentile over the trailing year. High rank plus a fat spread is the sweet spot for selling. Low rank with a thin spread means step aside. The verdict row says it plainly: SELL PREMIUM, AVOID SELLING, or NEUTRAL. Triangles mark state changes.
Implied tends to overstate realized on average, and that structural overpayment is where the money comes from. But it is not constant. Some weeks the spread is wide open, some weeks there is nothing there, and this is for telling the difference quickly.
One caveat that matters: the premium is a condition, not a timing signal. A rich premium can stay rich, and a thin one can persist for weeks. Pair it with a trend or regime read so you are not selling into a move. อินดิเคเตอร์

Implied Sigma Map (by Yulien)Implied Sigma Map transforms option-implied volatility into a practical daily volatility map directly on the price chart.
The indicator uses the previous confirmed daily close as its anchor and calculates expected price distances in standard deviation , or sigma, levels. It supports two IV input methods: Direct Daily ATM IV, for brokers that provide daily implied volatility, and Annualized ATM IV, which is automatically converted into a daily value.
Call and Put ATM IV are entered separately and averaged internally, helping produce a cleaner estimate of the market's implied daily volatility.
The map displays configurable levels from ±0.25σ to ±3σ, allowing traders to quickly see how far price has moved relative to the volatility currently priced by the options market.
The dashboard also tracks Current Sigma, Implied Move Consumed, and the current volatility regime. This makes it easier to distinguish normal price movement from volatility expansion and statistically extended conditions.
The main value of the indicator is context. Instead of simply seeing that a market has moved 20, 40, or 100 points, traders can see that movement in volatility-adjusted terms—for example, +0.4σ, +1σ, or +1.5σ.
Sigma levels are not automatic support, resistance, or trade signals. They are a framework for understanding how much of the market's implied daily move has already been consumed and whether price is trading in balance, expansion, or tail territory.
For best results, use ATM implied volatility from the expiration being analyzed and verify that the Call and Put IV inputs correspond to the intended strike and expiration. อินดิเคเตอร์

Sessions & Killzones with Time Profile [FEELS]Draws your sessions and killzones, then tells you what they have actually done on this symbol: which session takes the day's high most often, which hours of the day the extremes really land on, and how much of that is just chance.
That last part is the whole point. Cut any price series into days and its highs and lows crowd toward the edges of the day on their own, so a plain hour-by-hour count shows a spike at the day boundary even when there is nothing there to find. On Bitcoin the hour that looks busiest on a raw count turns out to be the quietest one once chance is taken out. Every figure in this script has that subtracted first.
FEATURES
- Four sessions you can rename, recolour and re-time, drawn as range boxes
- Labels on closed days naming which session held the day's high and which held its low, thinned so they do not collide
- Rotating notes describing what the day did: sweeps of the previous session, inside sessions, ranges against their own recent normal
- Notes are ranked by how rare they are on this symbol, so you are not reading the same line every day
- Hour profile of where the day's high and low land, measured against a random-walk baseline
- The profile can be stated in words in the panel, drawn as a strip under price, or drawn as a block in the right margin. Words are the default; the two drawn forms are checkboxes and ship switched off
- Session and hour figures always carry the number of days behind them
- On symbols that trade inside a single session the session names drop out of the wording and the hour layer takes over the panel
- Time zone selector for sessions, the day boundary and the profile
- Three alerts
- Tooltips on the inputs that need explaining
HOW TO USE IT
Open it on a symbol you trade and read the panel's first line. That is the standing fact about this instrument: which session holds the day's high most often, and how much of that is just chance. On some symbols the gap is wide. On others there is barely a gap, and that is worth knowing too.
Then the hours. The crowded ones are when this symbol has historically set the extremes of its day; the empty ones are when it has not. That tells you which part of the day is worth sitting at the screen for, and whether a move happening right now is landing in a window where this symbol usually turns or in one where it usually does not.
The rotating lines are the day-to-day layer. They say whether the session that just closed did something unusual here: a sweep of the previous session that was given straight back, a range at a fraction of its normal size, a day whose high and low were both set inside one session.
An example of what the correction is worth. On Bitcoin's hourly history, chance alone would put 11.7% of all daily highs in the 23:00 hour, purely because it sits at the edge of the day. The measured figure is 6.5%. Counted raw it looks like one of the busiest hours on the clock. Counted properly it is the emptiest.
None of it is an instruction to buy or sell. It describes what has already happened, with the sample size attached so you can judge how much weight it carries.
HOW TO READ IT
1. A box is one session's range on one day. The label above or below the day's extreme names the session that produced it.
2. In the profile, a bar rising from a row's centre line means that hour holds the extreme more often than chance would give it. A grey bar hanging below means it holds fewer. The grey is not filler. On most symbols the hour that looks busiest raw is a grey bar once chance is removed.
3. The panel's first line is the standing fact about this symbol: which session holds the high most often, next to what chance alone would produce, with the day count.
4. The lines below it change with the day. They are picked by rarity, so a fact that happens on most days here will rarely be the one shown.
5. Every figure carries its sample size. Sixty days is a hint. Six hundred is a distribution.
HOW IT WORKS
Each closed day is cut into its sessions. The session holding the day's high and the session holding the day's low are recorded, and so is the hour each extreme landed on.
Those counts mean nothing without a baseline. A day is a window, and the extreme of a random walk inside a window is not evenly placed: it sits near the edges far more often than the middle. That is the arcsine law, and it produces a convincing looking pattern out of pure noise. So every bar of every day contributes its own share of that baseline to the hour it sits on, using the discrete arcsine weights for a day of that many bars. Days with missing bars are handled by the same arithmetic.
What the profile shows is the difference: how often an hour actually held the extreme, minus how often chance would have handed it one. An hour with nothing above chance is drawn flat. Flat is information.
Ranges are compared in logarithmic terms against a rolling median of that session's own recent history, so a symbol whose price has tripled does not read as permanently explosive.
ORIGINALITY
Session boxes are common and this script does not claim to draw them better. What it adds is the measurement on top of them, and one specific correction inside that measurement.
Raw percentages are the usual way this is reported, and raw percentages of an extreme inside a window are dominated by the arcsine effect, which is a property of windows rather than of markets. Subtracting a per-day arcsine baseline, accumulating it by clock hour so that uneven days still work, and reporting only the difference is written from scratch here.
One thing worth admitting about how the notes got here. The rarity ranking exists because my first version did not have one and the panel was useless. Whichever family of notes happened to carry the biggest raw numbers led every single day: on a Nasdaq index future it opened with "New York made the day's high" on 41% of days, which is perfectly true and tells you nothing, because on that instrument New York makes the high almost always. Scoring each note by how rare it is on that particular symbol is what turned the panel from wallpaper into something worth reading.
HONESTY
- The day still forming is not counted into anything and gets no labels. It joins the statistics when it closes.
- Statistics are computed from closed days only. A label, and the box of a session that has ended, never change afterwards. The box of the session currently running extends as it runs, which is the one thing on screen that is still moving.
- The figures depend on how much history your chart has loaded, and TradingView loads different depths on different timeframes. The same symbol can honestly show a different day count on 15m than on 1H. The count is on screen for that reason.
- Below the minimum day count the profile is not drawn at all and the panel says so. Sessions, labels and notes still work.
- On a daily or higher timeframe there is no time of day to profile, and the script says so instead of drawing something meaningless.
- The profile describes where extremes have landed. It is not a forecast, and an hour standing above chance is not a reason to expect a turn.
- Each bar is attributed to the first session whose window contains it, so overlapping session definitions resolve to the earlier one instead of being counted twice.
- The arcsine baseline is a theoretical reference for a random walk, not a simulation of this symbol. I checked it against four hundred permutations of real hourly data and the worst disagreement was under one percentage point.
- TradingView allows a script a limited number of boxes and labels and removes the oldest past that, so the history shown is capped by the two day-count settings.
ALERTS
A day closed and the statistics updated. A session traded through the previous session's high or low. The day's extreme landed on an hour that holds them far more, or far less, often than chance.
SETTINGS
The four session windows are arbitrary and are yours to set: the defaults are full trading sessions, and they narrow to any killzone timing you work with, with the time zone switched by a selector. Everything measured follows the windows you set. The other main ones: "Days of session boxes" and "Days of labels" trade history against the drawing budget. "Minimum bars between labels" stops labels colliding on symbols that print few bars per day. "Minimum days before showing statistics" sets how much history the profile insists on. The profile has three independent display checkboxes and they can be combined. Out of the box only the panel wording is on, so switch on "strip" or "block" if you want the drawn forms shown in the screenshots. "Block height" and "Strip height" are separate, so the block can stay large while the strip sits close under price.
This is a descriptive tool for reading session structure. It is not financial advice and it does not predict price.
อินดิเคเตอร์

อินดิเคเตอร์

อินดิเคเตอร์

Squeeze AI - Breakout Direction Probability [Dots3Red]🗜️ SQUEEZE AI - BREAKOUT DIRECTION PROBABILITY
A squeeze tells you volatility is loading. It has never told you which way it's going to release. This script fixes that second half of the problem - not by predicting the future, but by remembering the past. Every completed squeeze on your chart becomes a measured data point, and when a new squeeze fires, the script reports what the most similar past squeezes actually did.
✨ WHY THIS MATTERS
Bollinger-inside-Keltner squeeze detection has existed for years, and every version of it does the same thing: flags that a squeeze is happening, then flags that it released. What happens next has always been left to the trader's judgment.
This script keeps score instead. It records the character of every squeeze that completes — how long it ran, how tight it got, what volume and momentum looked like — and pairs that with what price genuinely did afterward. When the next squeeze fires, it doesn't guess; it looks up the most similar squeezes this chart has actually produced and reports their real outcomes.
📊 ▲ 68% | +2.1 ATR | N=34
That reads as: of the 34 most similar past squeezes on this chart, 68% broke upward, averaging a 2.1 ATR move. Measured history, not a formula assuming squeezes behave a certain way.
⚙️ HOW IT WORKS
🗜️ Squeeze detection — the standard definition: Bollinger Bands (mean ± standard deviation) compress fully inside Keltner Channels (mean ± ATR). The moment BB's upper band drops below KC's upper band and BB's lower band rises above KC's lower band, a squeeze is active. A minimum-duration filter discards brief compressions too short to carry real information.
📐 Compression depth — beyond simple on/off, the script tracks how tight the squeeze actually gets: 0% means BB has barely tucked inside KC, approaching 100% means BB has nearly collapsed to a point. This becomes one of the features used for matching, since a shallow squeeze and an extreme one are genuinely different situations.
🧠 The KNN engine — every completed squeeze is stored as five measurements: duration, compression depth, average volume behavior during the squeeze, momentum at release, and volatility context. When it resolves, the actual outcome — direction and distance in ATR — is recorded against those five measurements. A new squeeze is compared against this stored history, and the K most similar past squeezes vote on direction and expected distance.
🔮 Live anticipation — while a squeeze is still compressing, before it even releases, an optional live label shows the KNN's current lean based on the squeeze's characteristics so far. This updates as the compression develops, so you're not waiting for the release to get a read.
🔒 Non-repainting — squeeze tracking, firing, and outcome grading all happen only on confirmed bars. The live anticipation label is explicitly a live-state readout (clearly distinguished from the historical fire labels) and is deleted and redrawn each update rather than left as a permanent mark.
🧭 HOW TO USE
1️⃣ Wait for the sample count. Early on a fresh chart, fire labels will show "Training… (4/12)" instead of a probability. The engine needs a real base of completed squeezes before its reads mean anything — don't trust a probability built on a handful of samples.
2️⃣ Read the N, not just the percentage. "▲ 68% | N=34" is a meaningfully different statement than "▲ 68% | N=8" — the first is a real pattern, the second could easily be noise. The script always shows N specifically so you can judge that yourself.
3️⃣ Watch the live anticipation label as the squeeze develops. A squeeze's characteristics (duration, compression, volume) can shift the KNN lean while it's still compressing — the live label lets you see that lean forming before release, not just after.
4️⃣ Check the dashboard's global stat for chart-level context. Beyond any single squeeze, the dashboard tracks what percentage of every recorded squeeze on this chart broke upward overall — useful context for whether this instrument has had a directional bias in its squeeze behavior.
5️⃣ Tune the minimum squeeze duration to the timeframe. A 4-bar minimum on a daily chart and a 4-bar minimum on a 1-minute chart represent very different amounts of real compression — adjust it to the timeframe you're actually trading.
🛠️ SETTINGS
🗜️ Squeeze Detection
• BB Length / Multiplier, KC Length / Multiplier — standard Bollinger and Keltner parameters
• Min Squeeze Duration — shortest compression the script will bother recording
📊 KNN Engine
• Outcome Window — bars after release over which direction and distance are measured
• K Neighbors — how many similar past squeezes vote on the current one
• Max / Min Training Samples — memory cap and the minimum before probabilities display
• ATR Baseline Period — the volatility-context window used in matching
🎨 Visualization
• Fill between BB — boolean to control area fill
• Squeeze Background Tint, Squeeze Zone Box — two independent ways to mark the active compression, usable together or separately
• Fire Labels with Probability — the KNN readout shown on release
• Live Anticipation Label — the developing-squeeze readout described above
🖥️ Dashboard
• Show/hide, position — current squeeze state and duration, compression %, live KNN read, and chart-wide sample totals
EXAMPLE (area fill between BB bands)
📝 NOTES
Squeeze frequency varies enormously by instrument and timeframe — a fast-moving asset will accumulate the sample count needed for meaningful probabilities much faster than a slow one. On a new chart, expect several squeezes to pass before the KNN read becomes genuinely informative rather than a placeholder.
⚠️ DISCLAIMER
This is an analytical and visualization tool. It does not generate trade signals and does not constitute financial advice. Historical squeeze outcomes do not guarantee how any future squeeze will resolve. อินดิเคเตอร์

Watermark ProWatermark Pro
Watermark Pro is a visual chart annotation and context overlay designed to help traders document and review their TradingView charts more clearly.
The script does not generate trade signals, does not provide buy or sell recommendations, and does not use price-based calculations to predict market direction. Its purpose is to display configurable chart context, review notes, session information, and optional checklist elements directly on the chart.
What the script does
Watermark Pro allows users to display selected contextual information on their chart, including:
* custom title and subtitle text
* optional user-defined note lines
* date information
* symbol and timeframe information
* optional exchange information
* optional session label
* optional footer note
* optional process checklist
* configurable text size, color, transparency, alignment, spacing, and position
This can help keep chart screenshots, reviews, trading journals, and educational examples more structured and easier to understand later.
How it works
The script uses TradingView table objects to place text-based information in selected chart areas. Users can choose where the main watermark and footer appear, adjust padding and spacing, and decide which elements should be visible.
The footer can show chart context such as the selected symbol, timeframe, date, and optional session label. The session label is determined from user-defined session times and a selected timezone. Users can configure sessions such as Asia, London, NY AM, NY Lunch, and NY PM.
The optional checklist mode lets users define their own process labels and assign simple status markers to each item. This can be used as a visual reminder for a personal review process, for example:
Context ✓ | Timing ✓ | Liquidity • | Entry • | Risk ✓
The checklist is manually configured by the user and does not evaluate market conditions automatically.
Templates and use cases
Watermark Pro includes several display templates to make setup easier:
* Custom: manual configuration
* Minimal: reduced chart context display
* Chart Notes: general note-taking layout
* Trading Journal: layout for trade documentation
* Education: layout for explanation and study charts
* Checklist: process checklist display
* Footer Only: compact chart context footer
* Review Mode: layout for post-trade analysis
These templates change which visual elements are displayed and provide neutral default text. Users can still adjust the content and layout manually.
Originality and usefulness
The script is not a trading signal indicator and is not intended to combine multiple technical indicators. Its usefulness comes from combining chart annotation, footer context, session labeling, and a configurable process checklist into one structured visual overlay.
Instead of only displaying a static watermark, the script provides a configurable documentation layer for chart review. This helps traders keep important non-signal information visible, such as symbol, timeframe, date, session context, and personal review notes.
Important limitations
Watermark Pro does not:
* generate entries or exits
* calculate trend direction
* detect support or resistance
* identify liquidity automatically
* provide alerts
* provide trading recommendations
* manage risk or position sizing
* guarantee improved trading performance
All text fields are manually configured by the user. The checklist is a visual process aid only and should not be interpreted as an automated trading decision system.
Intended purpose
Watermark Pro is intended as a chart documentation, review, and workflow overlay. It is designed to make charts easier to label, review, and understand without adding trade signals or predictive logic.
อินดิเคเตอร์

อินดิเคเตอร์

ไลบรารี

Precedent [ThrowMaster]===============================================================
WHAT IT IS
===============================================================
Precedent does not predict. It measures.
Every time a defined market event confirms on your chart, Precedent
records what price actually did over the following N bars. Once enough
comparable records have accumulated, it displays the empirical
distribution of those recorded outcomes: how far price travelled, how
often it reached a given distance, and how many bars that took.
The question it answers is narrow and deliberately so:
"On this symbol, on this timeframe, when this kind of event happened
at this kind of price level in this kind of market condition, what
followed afterwards, and across how many cases?"
Every number shown is measured from the visible history of the chart you
are looking at. Nothing is imported from another market, no outcome
percentages are hard-coded, and no distribution shape is assumed. If the
chart has not yet produced enough comparable cases, the indicator stays
silent and tells you how many it has.
This is a context tool. It produces no buy or sell signals, no entry
prices, and no stop levels, and it is not designed to be used as one.
Please read the section titled THE MOST IMPORTANT WARNING before using
it on a live chart.
===============================================================
HOW IT WORKS
===============================================================
1. LEVEL MAP
A running inventory of prices that carry structural meaning is
maintained bar by bar:
- Swing pivots confirmed with a symmetrical left/right lookback
(default 21 bars each side for external structure, 5 for internal).
- Equal highs and equal lows: when a new pivot lands within the merge
tolerance of an existing level, that level's touch count increases
rather than a second level being created.
- Unfilled fair value gaps: a three-bar imbalance where the current
bar's low is above the high from two bars ago (or the mirror for
the bearish case). Each additional gap overlapping the same price
adds to that level's weight, so three gaps stacked at one price
are recorded as one level carrying three factors.
- Order blocks: the extreme of the last opposite-coloured candle
immediately before a displacement bar, where displacement means a
body in the top 15 percent of the last 100 bodies AND the move
takes out the most recent internal pivot. Displacement alone is not
enough; it must be tied to a structural break.
- Previous day and previous week high and low, requested with a
one-bar offset so no unclosed higher-timeframe data is used.
Each level accumulates a WEIGHT equal to the number of independent
factors coinciding there, plus a bonus for repeated touches and for age
beyond 200 bars. Two factors closer together than the merge tolerance
(default 0.25 x ATR) are treated as one level with two factors, never as
two levels. This prevents an order block that naturally sits inside a
fair value gap from being counted twice.
A level whose weight reaches the MAJOR threshold (default 4) is
classified MAJOR; weight 1 to 3 is MINOR; anything else is NONE.
Note on interpretation: a heavily touched level is treated as more
SIGNIFICANT, not as stronger. Repeatedly tested highs and lows are
exactly the prices that attract sweeps. The indicator does not assume
which way that resolves; it measures what actually followed.
2. EVENT CLASSES
Six event types are detected. Every one of them locks its state at bar
close.
SWP Sweep Price trades beyond a mapped level and closes back
inside it, with a wick in the top quartile of the
last 100 wicks on that side.
SHF Shift A close beyond the most recent confirmed external
swing, in either direction (break of structure or
change of character).
SQZ Squeeze Bollinger Bands (20, 2.0) contract entirely inside
Keltner Channels (20, 1.5 x ATR) for at least five
consecutive bars, then expand back out.
CLX Climax Volume in the top 5 percent of the last 200 bars
combined with a bar range in the top 10 percent.
Where volume is unavailable, range plus body size is
used instead and the dashboard states which.
REJ Reject A bullish or bearish engulfing bar, or a pin bar with
a wick in the top quartile of the last 100, but only
when it occurs at a mapped level. A rejection candle
floating in empty space is not recorded at all.
DIV Divergence Price makes a lower low while cumulative flow makes a
higher low, or the mirror case, measured at confirmed
pivots. Flow is signed by body position within the
bar range and scaled by volume where volume exists.
Divergence is measured against volume-weighted flow, not against an
oscillator. An oscillator derived from price and then compared back to
price adds no independent information; volume is a separate data source.
Two events of the same class are never recorded closer together than the
full horizon. This is a deliberate statistical constraint: it costs
sample size, and it buys the guarantee that no two stored outcomes share
an overlapping future.
3. CONTEXT SCORE
Three voices contribute to an additive score from 0 to 100. Nothing
gates. No voice can block a signal; each only adds weight.
STRUCTURE 35 Whether the recent sequence of confirmed swing highs
and lows agrees with the event's direction.
FLOW 30 The percentile rank of the bar's signed flow over the
last 200 bars, cut to one fifth when its sign
disagrees with the event direction.
HTF 35 Whether the higher timeframe close sits above or below
its own 50-period EMA, in agreement with the event.
The score is then discounted by regime and renormalised back to a 0-100
scale, so scores remain comparable across regimes:
RANGE structure x 0.70 (structure breaks constantly and means
little inside a range)
TRANSITION higher tf x 0.80 (higher timeframe bias is least
reliable while it is turning)
TREND flow x 0.85 (large volume is ordinary in a trend
and therefore less informative)
One correction is applied automatically: Climax and Divergence are
themselves defined from flow, so for those two classes the flow weight
is halved and the freed weight is split evenly between structure and
higher timeframe. Without this, the flow voice would confirm an event
that flow itself created.
The score is converted into a two-level tier by comparing it to the 60th
percentile of past scores for the same event class on this chart. There
is no fixed cut-off number.
4. SIGNATURE AND BACKOFF
Each recorded event is filed under a discrete key:
event class x location class x regime x direction x score tier
Direction is never merged at any level, because upward and downward
outcomes are not symmetrical.
When a new event confirms, the engine looks for stored outcomes sharing
that key. If fewer than the minimum sample (default 20) exist, it drops
the finest component and looks again:
L3 event + location + regime + direction + tier
L2 event + location + regime + direction
L1 event + regime + direction
L0 event + direction
The first level with a sufficient sample is used, and the dashboard
always states which level was used and how many records it contained.
If even L0 is short, nothing is drawn and the dashboard shows
CALIBRATING with the current count.
Seeing L1 or L0 rather than L3 is normal, not a fault. Non-overlapping
sampling produces a limited number of independent cases per chart, and
the backoff exists precisely to handle that honestly rather than
displaying a percentage built on four observations.
5. OUTCOME STORE
For each recorded event the engine tracks, for the following H bars
(default 24):
- excursion at H/4, H/2, 3H/4 and H, expressed in R where R is the
ATR(14) value at the event bar
- maximum favourable and maximum adverse excursion
- the bar number at which the move first reached +1R, +2R and +3R,
or zero if it never did
The record is written to the store only after H bars have fully elapsed.
A projection displayed today is therefore built exclusively from events
that had already finished before it was issued. This is a structural
property of the design, not a discipline that has to be maintained.
6. WHAT IS DRAWN
- An empirical quantile fan. The outer envelope traces the 5th and
95th percentiles of the matched outcomes at each of the four
checkpoints; the inner envelope traces the 25th and 75th; the
dashed centre line traces the 50th. The shape is asymmetric and
heavy-tailed whenever the underlying data is, because the values
are measured percentiles rather than a fitted curve.
- A target line. The median maximum favourable excursion of the
matched set is converted to a price, then snapped to a mapped
structural level if one lies within half an ATR. Statistics choose
the zone; structure chooses the exact price. The label states
"level" when a snap occurred and "stat" when it did not.
- Hit rate and expected bars. Both are read at the nearest whole R
ring (+1R, +2R or +3R) to the target distance, and the ring is
named on the label. Hit rate is the share of matched records that
reached that ring within H bars. The bar count is the median
first-passage time among those records that reached it.
7. RUN TRACKER
A run begins at a confirmed structure shift and ends at the next
confirmed shift in the opposite direction. Within a run, occurrences of
each event class and direction are counted. When the run closes, one
record per class is stored: how many had occurred before the reversal.
The observation unit is therefore the run, not the event. This matters:
counting events directly would produce heavily overlapping samples,
since several events inside one run share the same future. Counting runs
does not.
The panel answers a question most tools ignore entirely: given that a
third bearish divergence has now printed in this uptrend, in what
fraction of past runs on this chart did the reversal arrive by the
third, and in what fraction did the run extend to a fourth or beyond.
8. SELF-AUDIT
Every displayed projection resolves into exactly one of four states, and
these are never merged:
HIT the target was reached first
ADV the -1R reference was reached first
AMB both were touched inside the same bar, so the order is
unknowable from bar data and the case is discarded rather
than claimed
EXP H bars elapsed with neither touched
The dashboard reports the running counts, and separately compares the
average hit rate the tool projected against the hit rate it actually
realised. If those two numbers diverge, the tool is telling you its own
estimates are miscalibrated on this chart.
Two further panels report whether the classification axes carry any
information at all: median outcome for tier A versus tier B, and median
outcome for MAJOR versus MINOR versus NONE locations. If a pair does not
separate, that axis is not contributing, and you are meant to see that.
===============================================================
WHAT MAKES IT ORIGINAL
===============================================================
- Outcome statistics are conditioned on a discrete event signature
and computed from the chart's own history, rather than assumed from
a parametric distribution or imported as fixed percentages.
- Projection targets are snapped onto mapped structural levels, so
the displayed price is a real level rather than a quantile value
floating in empty space.
- The hierarchical backoff makes sparse conditioning explicit: the
display always names the level of specificity that was achievable
and the sample size behind it.
- Sequence statistics use the completed run as the observation unit,
which removes the sample overlap that direct event counting creates.
- The indicator scores its own past projections against outcomes and
displays projected versus realised hit rate on the chart.
===============================================================
HOW TO READ THE CHART
===============================================================
HORIZONTAL LINES
The image below shows the level map alone, with the projection layer
switched off, so the two grades of level can be compared directly: gold
solid lines mark MAJOR levels, thin dotted lines mark MINOR ones.
Two families of horizontal line exist, and they are drawn so that they
can never be confused with each other.
THE LEVEL MAP owns thin dotted lines and gold:
Gold, solid, width 2 A MAJOR level: four or more independent
structural factors coincide at this price.
Washed white, DOTTED, A MINOR level: one to three factors.
width 1
THE TARGET FAMILY owns solid width-2 lines in mint, coral and slate.
No target line is ever drawn dotted or at width 1.
Mint, solid, width 2, The target of the live projection.
full opacity Extends to the right. Only one is live at
a time.
Coral, dotted, width 1 The -1R adverse reference of the live
projection. Removed the moment the
projection resolves. This is a measurement
boundary used to classify the outcome. It
is NOT a stop loss and must not be used as
one.
Once a projection resolves, its target line keeps its full width and
stays solid. Only its colour and opacity change:
Mint, faded HIT: price reached it within the horizon.
Coral, faded ADV: price reached the -1R reference
first.
Slate blue-grey, faded EXP or AMB: the horizon elapsed with
neither touched, or both were touched in
the same bar and the case was discarded.
Resolved lines are retained deliberately. A price that the statistics
selected, and that was then snapped onto a structural level, often
remains structurally relevant afterwards, and it is useful to see where
those prices were. The number retained is configurable and defaults to
six.
Read the fade as expiry of a claim, not as expiry of the price. The
faded line is a record that this price was once selected as a target and
of what happened next. It is not a live target and carries no ongoing
claim about the future.
The image below shows several resolved projections on one chart, so the
three outcome colours can be compared side by side: a faded mint line
where price reached the target, a faded coral line where it reached the
adverse reference first, and a faded slate line where the horizon
elapsed without either being touched. The markers carry the matching
three-letter outcome. Projections that did not work out are shown here
deliberately; the indicator records its own failures and so should its
description.
Level lines are redrawn on each new bar and only levels within six ATR
of current price are displayed, up to fourteen at a time.
THE FAN
Outer shaded band 5th to 95th percentile of matched
historical outcomes.
Inner shaded band 25th to 75th percentile.
Dashed centre line 50th percentile, the median path.
Teal the event pointed upward.
Coral the event pointed downward.
The fan is frozen at the moment the projection is issued and is never
recalculated. It reaches forward exactly H bars.
The next image shows a single live projection close up: the two shaded
bands, the dashed median path, the mint target line, and the label
carrying hit rate, sample size and remaining bars. Note that the bands
are not symmetrical around the median, because they are measured
percentiles rather than a fitted curve.
EVENT MARKERS
A small label prints at each recorded event, below the bar for upward
events and above for downward ones. It contains a three-letter code and
a number:
SWP sweep SHF shift SQZ squeeze
CLX climax REJ rejection DIV divergence
The number is the count of that event class and direction so far inside
the current run. "DIV 3" means this is the third divergence of that
direction since the last structure shift.
When a projection resolves, its marker gains a suffix and changes
colour:
HIT green target reached first
ADV red the -1R reference reached first
AMB amber both touched in the same bar; discarded
EXP amber the horizon elapsed with neither touched
THE TARGET LABEL
Three lines at the right end of the projection:
line 1 the target price, followed by "level" if it was snapped onto
a mapped structural level or "stat" if no level was near
line 2 hit rate and sample size, for example: hit 61% n=38
line 3 while the projection is live: bars remaining and the R ring
the hit rate refers to. Once it resolves, this line is
replaced by "RESOLVED" followed by HIT, ADV, AMB or EXP, and
the whole label takes the matching colour.
The bar count was frozen when the projection was issued and only counts
down. Nothing behind it is recalculated.
THE DASHBOARD
EVENT class, direction, and sequence number in this run
LOCATION MAJOR / MINOR / NONE and the level weight
REGIME RANGE / TRANS / TREND, the context score, tier
SIGNATURE backoff level used and sample size
WITH q50 q75 q95 terminal excursion quantiles measured ALONG the
event's own direction, in R
AGAINST q25 q05 the same distribution's tail measured AGAINST the
event's direction, in R
TARGET price and hit rate
ETA bars remaining and the R ring, or "no open
projection"
RUN EXT how far the current run has extended, in R
FLOW SOURCE "volume" or "proxy"
SEQ 1 / 2 / 3 / 4+ share of past completed runs that reversed after
that many events of this class
RUNS median median count before reversal, and number of runs
TIER A / B median outcome in R for each tier, with counts
LOC MAJ/MIN/NONE median outcome in R for each location class
LEDGER running totals of hit, adv, amb and exp
CALIBRATION average projected hit rate against realised
The dashboard is reproduced below at readable size, since every claim
made in the HOW IT WORKS section is meant to be verifiable there: the
backoff level actually used, the sample size behind it, the quantiles,
the sequence distribution, the two axis-health rows, and the running
comparison of projected against realised hit rate.
WITH and AGAINST are measured relative to the event's own direction, not
relative to the chart. For a downward event, a WITH value of +1.4R means
price fell by 1.4 ATR, and an AGAINST value of -1.8R means price rose by
1.8 ATR before the horizon closed. AGAINST is the row that tells you how
violent the route can be, and it is the row most worth reading before
deciding on any position size.
===============================================================
THE MOST IMPORTANT WARNING
===============================================================
DO NOT TREAT THE GREEN LINE AS A TARGET TO TRADE TOWARD, AND DO NOT
TREAT ANY MARKER AS AN ENTRY SIGNAL.
You will observe the following, and it is the single most dangerous
thing about this indicator:
The projection expires. The bars run out. The label reads "closed". And
then, twenty or fifty bars later, price finally reaches the green line.
It is tempting to read that as the tool having been right after all. It
was not, and here is why that reading destroys accounts:
1. The green line is snapped to a structural level. Structural levels
get revisited eventually, because that is what they are. Price
arriving there after the horizon has expired is not evidence of
anything. It is what levels do.
2. The expected bar count is a median of the cases that reached the
ring. By definition, roughly half of the successful cases took
longer than that. "The estimate elapsed and it is not there yet"
is an ordinary outcome, not a malfunction.
3. Route is not measured. The indicator records where price ended up
and how far it travelled. It does not promise that the path there
was survivable. Price can travel far against you first, and still
arrive. The AGAINST row is the only place the route appears at all,
and even there it is a summary, not a guarantee.
A faded line is a closed case. It has no ETA, no live claim and no
implication that price is still heading there. If price later reaches a
faded line, that is not a delayed hit. It is a structural level being
revisited, which is what structural levels do.
That third point is what actually costs money. A leveraged position
opened on the strength of a hit rate can be liquidated by an adverse
excursion long before the target is reached. The account is closed; the
target being reached afterwards is irrelevant to it. This is not a
remote scenario. It is the ordinary case whenever leverage is applied to
a statistic that describes destinations rather than routes.
The -1R red line does not protect you either. It is a measurement
boundary chosen so outcomes can be classified consistently. It is not a
risk parameter and was never sized to be one.
Precedent is a context tool. It tells you what has typically followed
this kind of moment on this chart, with the sample size attached. Entry
timing, position size, stop placement, leverage and the decision to
trade at all remain entirely yours and must come from a method this
indicator does not contain and does not attempt to contain.
If the only thing you take from a projection is "hit 61 percent, so buy"
you have misread it. The intended reading is closer to: "in 38
comparable cases on this chart, price reached this level within 24 bars
in 61 percent of them, taking a median of 9 bars, and the adverse tail
of that distribution ran to -1.8R."
===============================================================
LIMITATIONS AND REPAINT POLICY
===============================================================
REPAINT BEHAVIOUR, ELEMENT BY ELEMENT
- Event detection, tier assignment and score sampling are locked at
bar close. They do not change afterwards.
- Swing pivots confirm with a delay equal to the pivot length in bars
(default 21). A level cannot appear before its pivot is confirmed.
That delay is the cost of not looking ahead, and it is not avoided
anywhere in this script.
- Higher timeframe values are requested with a one-bar offset, so
only completed higher timeframe bars are used. On the chart
timeframe this means the higher timeframe bias lags by one higher
timeframe bar.
- The fan, the target line and the adverse line are computed once, at
the confirmed bar that issued them, and are never recalculated.
- The dashboard and the countdown update live within the forming bar
by design. The countdown only subtracts from a number that was
frozen at issue; no statistic behind it is recomputed.
KNOWN LIMITATIONS
- The statistics are descriptive, not predictive. They summarise what
has already happened on the chart in front of you. They are not a
forecast and are not out-of-sample.
- Sample sizes are small by construction. Requiring non-overlapping
outcomes limits the number of independent cases available, which is
why the backoff and the visible sample counts exist.
- Until enough completed outcomes exist, nothing is drawn at all. The
image below shows that state: the dashboard reports CALIBRATING and
the current count against the required minimum, and no fan, target
or hit rate appears anywhere on the chart.
- Chart history is finite. On low timeframes the available bars may
cover only a matter of weeks, and possibly only one market regime.
Treat a large sample drawn from a single regime with caution.
- Outcomes are measured at bar resolution. When a bar touches both
the target and the adverse reference, the order is unknowable and
the case is marked ambiguous and discarded rather than assumed.
- Statistics apply only to events this indicator itself defined. If
you identify a setup it did not mark, no displayed percentage
describes it. Borrowing a number from a different occasion is a
misuse.
- Where a symbol provides no usable volume, flow falls back to a
body-position proxy on the same percentile scale. The dashboard
states which is in use. Mixing the two would corrupt the store, so
the fallback applies to the whole session or not at all.
- Changing the higher timeframe from Auto to Manual changes what the
signature key means. The stored outcomes are therefore cleared and
rebuilt from zero when you do it. This is intentional.
- Nothing here is tuned. There is no optimiser and no fitted weight.
Thresholds are percentiles over disclosed rolling windows. If a
parameter is changed, the level map and the statistics change with
it, and the sample must accumulate again.
===============================================================
DISCLAIMER
===============================================================
This script is published for educational and analytical purposes. It is
not financial advice, not a recommendation to buy or sell any
instrument, and not a trading system. It produces no entry signals, no
stop levels and no position sizing.
Historical measurement does not indicate future results. Markets change
regime, and a distribution measured on past bars may not describe the
next ones. Trading carries risk of loss, and leveraged trading carries
risk of total loss. Any decision taken while this indicator is on the
chart remains entirely the responsibility of the person taking it.
อินดิเคเตอร์

อินดิเคเตอร์

อินดิเคเตอร์

Fair Value Gap (FVG) Statistics with Placebo Control█ OVERVIEW
On the same instrument, measured against a 50% baseline, fair value gaps looked significantly profitable in one period and significantly unprofitable in another. Both readings were artifacts of a baseline that was never 50%.
This indicator measures what actually happens after price returns to a gap, then compares the result against fake, or placebo, zones of the same size placed at bars where no gap occurred. Because a hit rate tells you nothing until you know what a meaningless zone scores on the same chart.
The following description consists of two parts. Part 1 is written in plain English and covers everything most readers need. Part 2 contains the full methodology and results for anyone who wants to examine the numbers in detail.
═══════════════════════════════════════
PART 1 — WHAT THIS IS AND WHY
═══════════════════════════════════════
█ THE PROBLEM
Zone-based tools are everywhere: fair value gaps, order blocks, breakers, imbalances. Yet almost none of them tell you how often a zone actually led anywhere. And when a number is quoted, it is often built on one of three flawed foundations.
1. The zone is counted before it could have been known.
This problem is easiest to see with order blocks. An order block is commonly defined as the last opposite candle before a move that breaks structure. That means the block cannot be identified until the structure break occurs, often several bars later. Yet it is drawn back on the earlier candle as though it had been known at the time.
Any hit rate measured from that earlier candle therefore counts a zone that nobody could actually have traded.
Fair value gaps suffer less from this problem because their three-bar pattern completes quickly, but the same principle applies: a zone becomes active only when it becomes knowable, and nothing before that bar should be counted.
2. Failed zones disappear.
Many tools remove a zone from the chart once price has passed through it. That makes sense for keeping a chart clean. It is disastrous for statistics, because the zones being removed are disproportionately the ones that failed.
Count only what remains on the chart and you are counting the survivors.
3. The hit rate is compared with 50%.
This is the most important problem, and it is extremely common.
The reasoning seems straightforward: if the target and stop are equally far from the entry, then no edge should mean a 50/50 outcome.
But a rule that enters when price reaches a level inherits a baseline from the way price moves. That baseline is not necessarily 50%. It changes with the instrument, direction, and market conditions. Across the three markets tested here, it ranged from roughly 45% to 55%.
A hit rate by itself therefore tells you very little.
What matters is how the same measurement performs on zones that have no informational meaning at all.
█ WHAT THIS INDICATOR DOES
For every real fair value gap the indicator identifies, it also generates placebo zones of the same height, direction, and distance from price, anchored at bars where no fair value gap occurred.
Real and placebo zones are then measured by exactly the same rules.
The difference between them — real minus placebo — is the result that matters.
If real gaps perform like the placebo zones, then the pattern is not adding anything, regardless of how attractive the raw hit rate may look.
The placebo comparison does not ask whether fair value gaps win more than 50% of the time.
It asks a harder question:
Do fair value gaps perform better than comparable zones that carry no fair value gap information at all?
█ HOW THE COMPARISON IS KEPT FAIR
Statistical libraries for Pine already exist, and many indicators will draw fair value gaps. What is not otherwise available is a matched control built into the measurement itself, so that every figure the indicator reports arrives together with the baseline it should be judged against.
Three design choices make that possible, and they only work together.
A matched placebo control. Each placebo zone has the same height, the same direction, and the same distance from price as the real zone it is meant to compare with. Both are scored by identical rules.
Confirmation-honest timing. A zone enters the sample only when it becomes knowable, never earlier. Every confirmed zone remains in the sample from that point onward, including zones that fail immediately.
Bias controls that are reported rather than hidden. Cases that are genuinely difficult to score — such as bars that touch both exits and trades that never resolve — are counted and displayed for real and placebo zones side by side. Ambiguous cases are treated conservatively rather than silently discarded.
The combination matters. A matched control is useful only if both sides are measured under the same timing and scoring rules.
█ WHAT THE TESTS FOUND
Across three asset classes, three timeframes, and two separate periods — fourteen measurements in total — fair value gaps showed no detectable advantage over size-matched zones placed at meaningless bars.
The difference remained below about one percentage point of hit rate, and none of the fourteen individual measurements reached conventional statistical significance.
That is a bound on what was observed, not a claim that the true effect is exactly zero.
A different market or a different period could produce a different result. That is precisely why the comparison is built into the tool rather than left as an assumption or a footnote.
The broader conclusion is more useful:
A hit rate quoted without its baseline does not tell you whether something works. On the same instrument, measured against 50%, this pattern looked significantly profitable in one period and significantly unprofitable in another. Both readings were created by the baseline, not by the gaps.
That lesson applies to zone-based tools generally, not only to fair value gaps.
If you take one thing from this script, take that.
█ HOW IT WAS TESTED
A single result on a single chart is easy to produce and easy to overinterpret. Before publication, the same measurement was therefore repeated while changing one assumption at a time.
Three asset classes — crypto, currencies, and equity index futures
Three timeframes — 5 minutes, 30 minutes, and 1 hour
Two separate, non-overlapping time periods
Three different target and stop distances
Two different limits on how long a trade could remain open
Each of these choices is partly arbitrary. If a finding appears only under one particular setting, it may belong to the setting rather than to the market.
Fourteen separate measurements were made in total.
Two standard statistical tools are used. A confidence interval shows the range in which the underlying value plausibly lies, which is more informative than a single headline estimate. Results from independent markets are also combined so that their evidence can be considered together rather than one chart at a time.
The measurement procedure was additionally checked against artificial data for which the correct answer was known in advance. This allowed the method itself to be tested independently of any market result.
█ HOW TO READ AND USE THE INDICATOR
Add the indicator to any chart. It works on any symbol and any timeframe and needs no configuration to produce a result.
The panel
By default, the panel shows a compact view: the number of zones found, the number revisited by price, the hit rate with its confidence interval, the placebo baseline, and the difference between real and placebo.
Turn off Compact panel for the full breakdown: wins, losses, unresolved cases, the direction split, and side-by-side rates for the cases that are hardest to score.
Everything used to produce the headline result is available for inspection.
Reading the result
Check the sample size first. Below roughly 1000 resolved zones, the confidence interval is usually too wide to conclude much. Recognizing that the sample is inconclusive is a valid result, not a failure of the indicator. Lower timeframes and longer histories both increase the sample.
Then read real − placebo . That is the headline result.
A positive number means the gaps outperformed the placebo zones. A negative number means they underperformed them.
The z-score beside it indicates how far the observed difference sits from what chance alone can produce. As a rough guide, an absolute z-score below 2 is not conventionally distinguishable from noise.
The raw hit rate is shown for context, not as the answer. Judging the pattern from that number alone is the mistake this indicator is designed to expose.
Setting up a measurement
To measure a specific period, turn on Limit to date range and set the dates.
The panel reports the sample actually achieved. This can be shorter than the requested period if the chart has not loaded enough historical data, so scroll left when necessary to load more history.
To check whether a result depends on your choice of exits, change Barrier size and run the measurement again. A finding that appears only at one setting may belong to the setting rather than to the pattern.
As a chart indicator
Zones are drawn as they form and can also be used in the usual visual way.
A zone that price has not yet returned to is drawn solid and continues extending to the right while it remains open.
When price reaches the zone, the box stops extending and fades to a dotted outline. The width of a completed box therefore shows how long that gap survived before price returned to it, while the chart makes it easy to see which zones remain active.
Turning off Draw real zones leaves only the statistics panel.
█ SETTINGS
Measurement — Risk unit selects whether exit distance scales with ATR or with the zone's own height. Barrier size sets that distance. Time limit controls how many bars a trade may remain open before being recorded as unresolved.
Entry price and Evaluate exits on the entry bar provide alternative scoring conventions so their effect can be measured rather than assumed. Both are labeled where they introduce a known bias.
Minimum zone height filters out small gaps. Exclude overlapping zones and Overlap lookback prevent several gaps created by the same move from being treated as independent observations.
Sample — restricts the measurement to a date range, entered as year, month, and day so the sample remains reproducible.
Placebo control — Placebos per zone sets how many comparison zones each real zone generates; more placebos produce a tighter estimate of the baseline. Placebo offset controls how far from the original bar the comparison zones are anchored.
Validation — replaces market price with a random walk so the measurement can be checked against data whose correct answer is known in advance rather than only against real markets.
Display — Compact panel shows the headline rows only; turning it off reveals the full breakdown. Draw real zones toggles the boxes on the chart.
═══════════════════════════════════════
PART 2 — DETAILED ANALYSIS
═══════════════════════════════════════
█ HOW A ZONE IS SCORED
A gap becomes active on the bar after its three-bar pattern closes. From that point onward, every confirmed zone remains in the sample, including zones that fail immediately.
When price returns to a zone, the entry is recorded at that bar's close , not at the zone edge.
This matters more than it may appear.
A touch condition means that price reached or passed the edge, so the bar may have overshot it by an unknown amount. Assuming a fill at the edge while beginning the measurement only from the following bar would start the trade from an artificial price and can systematically distort the result.
Two exits are then placed at equal distances on either side of the entry. Because the exits are symmetric, real and placebo zones can be compared directly.
If one bar touches both exits, its open, high, low, and close do not reveal which level was reached first. Those cases are shown separately and counted as losses, making the published result the conservative one.
Zones that reach neither exit within the time limit are excluded from the hit-rate calculation. They did not resolve, so they provide no evidence for either outcome.
█ RESULTS
Results below use the following settings. The sample ends 1 August 2026.
SETTING VALUE
Risk unit (R) ATR(14) at confirmation
Barrier 2.0 R each side
Time limit 100 bars after entry
Entry close of the touch bar
Overlapping zones excluded
Placebos per zone 3
Three markets, 30-minute charts, 2025-01-01 to 2026-08-01:
INSTRUMENT RAW NAIVE z PLACEBO REAL-PLAC
BTCUSDT 49.5% -0.67 49.0% +0.5
EURUSD 51.4% +1.65 51.7% -0.2
ES1! 49.2% -0.92 49.9% -0.7
POOLED -0.04
The panel on the chart above is not restricted to that fixed window — it runs to the most recent bar — so its figures differ slightly from the table. That is expected: it is a different sample, not a different result.
Read the raw column alone and the markets appear different: 49.5% for crypto versus 51.4% for currencies, a spread of 1.9 percentage points.
Now look at the placebo column. Its spread is 2.7 points.
The apparent difference between markets is therefore better explained by the baseline than by the fair value gaps themselves.
One example makes the problem especially clear:
BTCUSDT, 1 hour, calendar year 2024
Raw hit rate 54.0% (n = 1390)
Naive z vs 50% +2.95 "significant"
Placebo baseline 51.5%
Real minus placebo +2.5% z 1.49, not sig.
Against an assumed 50% baseline, a 54% hit rate gives a p-value near 0.003 — exactly the kind of number that can look compelling when published in isolation.
Against its observed control baseline, however, the evidence is not statistically significant.
The same indicator, on the same instrument, over a different period and with a tighter target, produced a raw hit rate of 48.4% with a z-score of -2.25 — apparently significant in the opposite direction.
Both apparent conclusions arise from comparing with an assumed 50% baseline rather than the observed control baseline.
█ ROBUSTNESS
DIMENSION TESTED RESULT
Barrier size 1R / 2R / 3R no change
Time limit 50 / 100 bars no change
Asset class crypto / FX / index no change
Timeframe 5m / 30m / 1h no change
Period 2024 / 2025-26 no change
Across fourteen separate estimates of real minus placebo, the largest result was 1.49 standard errors from zero.
With fourteen estimates, even if the true effect were zero, the largest absolute result would be expected to reach roughly 1.9 standard errors by chance alone.
Pooled across three independent markets, the estimate was -0.04 percentage points, with a 95% interval of approximately -1.2 to +1.1 points.
█ LIMITATIONS
One symbol and one timeframe can be analyzed per chart. Pine cannot pool results across markets, so each chart represents one sample rather than proof by itself. The pooled figures reported above were combined separately.
Trading costs are not included. Entries assume execution at the bar close with no spread, commission, or slippage. Real-world trading costs would make absolute performance worse.
Ambiguous bars are counted as losses. This lowers both real and placebo hit rates by roughly the ambiguous-case rate and therefore tends to cancel when the difference between them is calculated.
The bull and bear rows should not be interpreted independently in a trending market.
The placebo control matches zone size, direction, and distance from price, but it cannot match the fact that a real gap forms immediately after a strong move in the same direction.
For example, in an uptrend, a fake bearish zone is more likely to be run over by the prevailing trend, whereas a real bearish gap can only form after an actual downward move. These effects work in opposite directions and largely cancel in the combined result.
For that reason, the total should be treated as the primary statistic rather than the directional split.
This limitation was identified during testing and is the main known weakness of the methodology.
Finally, all results come from a sample. Another market or another period may produce a different estimate. That uncertainty is the reason the placebo comparison is built into the indicator rather than assumed away.
█ METHOD AND PRIOR WORK
None of the statistics here are new, and it is worth being clear about that.
Assigning a treatment to units or moments where it did not actually occur, then checking that no effect appears, is a standard falsification test in causal inference, where it is usually called a placebo test. The placebo zones in this indicator are that idea applied to bars instead of subjects.
The trading application is not new either. David Aronson's Evidence-Based Technical Analysis (2006) argues that a rule should be judged against the returns of random entry signals rather than against zero, and uses Monte Carlo permutation and White's Reality Check to do it.
The scoring rule — a target, a stop, and a time limit, whichever is reached first — is the triple-barrier method described by Marcos López de Prado.
What this script adds is not the method but its availability. The control is generated and scored automatically alongside the real zones, on any chart and any symbol, so the baseline arrives together with the number instead of requiring a separate study that most people will never run.
█ OPEN SOURCE
The source is open. Every figure above can be reproduced — or shown to be wrong — by anyone who wants to check it.
Order blocks are next, measured by the same rule: from the bar that breaks structure, not from the earlier candle on which the block is drawn.
อินดิเคเตอร์

Hurst Exponent What the Hurst indicator is actually doing
Imagine you're watching a stock's price bounce around day to day or week to week. Sometimes it keeps moving in the same direction for a while (a real trend). Other times it just zig-zags in place, going nowhere (choppy, directionless). This tool looks at recent history and gives you a single number between roughly 0 and 1 that tells you which of those two things has been happening:
Number above 0.6 → the ticker has had "momentum." Moves tend to keep going the way they started.
Number below 0.4→ the ticker has been chopping back and forth, more likely to mean revert or reverse than continue.
Right around 0.5 → basically a coin flip, no real pattern either way.
It figures this out by looking at the data at several different "zoom levels" — like checking if the pattern holds true over 2 weeks, and 3 weeks, and 5 weeks, and 3 months — and seeing if there's a consistent story across all of them. That's really all the complicated math is doing under the hood.
Now, the dials you can turn — the "inputs"
Think of these like knobs on an old radio. Turning them changes how the tool listens.
1. Lookback Window (N) — default 256
This is: how far back in time does it look each time it checks?
Turn it up (bigger number): It looks at a longer stretch of history — more like judging someone's character over years instead of days. The line gets smoother and steadier, but it's slower to notice a recent change in behavior.
Turn it down (smaller number): It only looks at recent history. More twitchy and reactive, but also more likely to give you false alarms from short-term noise.
2. Minimum Sub-window Size — default 8
This is the smallest "zoom level" it checks.
Bigger: Skips over very short-term wiggles, focuses on sturdier patterns.
Smaller: Includes very short-term wiggles in the analysis — can get noisy, like reading too much into one bad day.
3. Number of Scales — default 10
This is how many different zoom levels it compares (2 weeks vs 1 month vs 3 months, etc.)
More scales: More thorough, more trustworthy answer — like asking 10 friends for their opinion instead of 3. Costs a little more computer effort, but nothing you'd notice.
Fewer scales: Faster, but the answer is based on fewer "opinions," so it can be a little less reliable.
You generally don't need to touch this much — more is just "more careful."
4. H Smoothing Length — default 4
After it calculates the number, this smooths out the wiggles in the line itself, like a moving average.
Bigger: Silkier, calmer-looking line. But it reacts slower to real changes.
Smaller: Jumpier line, but catches changes sooner.
5. Upper Band (Trending) — default 0.60
This is the line where it says "okay, NOW I'm calling this a trend"
Raise it (like 0.70): Makes it pickier — only very strong, obvious trends get flagged.
Lower it (like 0.55): More generous — it'll call things a "trend" more easily, including weaker ones.
6. Lower Band (Mean-Reverting) — default 0.40
Same idea, but for the choppy zone
7. Recalculate Every X Bars — default 1
This one's just about speed/effort, not the meaning of the answer.
Leave it at 1: Recalculates every single time period — most accurate, most work for the computer. Raise it (like 5): Only recalculates every 5th bar and just holds the last answer in between — a shortcut to save computer effort. You'd only bump this up if the indicator is slow to load, which usually only happens if you also cranked up Lookback Window and Number of Scales at the same time.
The simplest way to think about tuning it:
Want a calmer, more trustworthy but slower-to-react reading? Turn up the Lookback Window and Smoothing.
Want a quicker, twitchier reading that catches changes sooner (but with more false alarms)? Turn those down.
อินดิเคเตอร์

ATR-ADR-Vol-CVDATR-ADR-Vol-CVD
**One overlay table for the numbers you check before every stock trade — volatility, position, volume, and cumulative delta flow — with daily context that stays correct even on a 5-minute chart.**
Classic swing-data panels (ADR%, relative volume, 52-week position, RS rating) answer *“how does this stock usually behave?”* This indicator adds **session CVD flow** and a **dual-column layout**: a **Daily** column that never drifts when you drop to intraday, plus a **Chart TF** column for what the current bar timeframe is doing right now.
Open source under **Mozilla Public License 2.0**. Built on swing-data concepts from MikeC, Fred6724, TheScrutiniser, and GlinckEastwoot.
---
## What you get
An on-chart **dashboard table** (overlay — no extra pane) grouped into sections:
| Section | Metrics |
|---------|---------|
| **Volatility** | ATR%, ADR% |
| **Price** | LoD distance, LoD price, % off 52W high, % above 52W low |
| **Volume** | Today vol, avg $ vol, avg vol, projected vol, rel. vol, vol. buzz, U/D ratio |
| **Flow (CVD)** | Bar Δ, session CVD (Daily) + **Z-score σ** (Chart TF) |
| **Strength** | RS rating |
| **Meta** *(optional)* | Market cap, float %, sector |
Signed metrics (52W distance, vol. buzz, CVD, Z-score) use **green / red**; extreme Z-scores highlight **yellow**.
---
## Dual-column modes
The table header shows **Metric | Daily | Chart TF** (e.g. `5`, `15`, `60`).
| Column | What it measures |
|--------|------------------|
| **Daily** | Always computed from the **daily series** (`request.security` on `"D"`) — today’s developing daily bar, daily ATR/ADR, daily volume stats, and live session CVD on intraday charts |
| **Chart TF** | Native **current timeframe** math — bar-level ATR, volume, delta, and projections on whatever resolution you are viewing |
### Auto hide Chart TF on Daily
When you switch the chart to **Daily timeframe**, the **Chart TF column hides automatically**. Daily and Chart TF would show the same thing twice, so the table collapses to **Metric | Daily** only.
- On **5m / 15m / 1H / Weekly**, Chart TF column appears (if enabled).
- On **Daily**, it disappears — no manual toggle needed.
- Toggle **Show chart TF column** in settings to force it off on lower timeframes; Daily still auto-hides regardless.
The table **rebuilds** when column count changes so no stale third column is left behind.
---
## Dashboard display modes
| Mode | Look |
|------|------|
| **Dark panel** *(default)* | Dark header, section bands, alternating row shading, subtle border — easy to scan on busy charts |
| **Transparent** | **Text only**, no cell backgrounds or border — clean overlay like classic ADR / swing-data scripts |
Other dashboard controls:
- **Position** — top/bottom, left/right
- **Text size** — Tiny / Small / Normal
- **Accent text** — default `#5D606B` (TradingView gray)
- **Dim labels** — secondary label color in Dark panel mode
- **Show Daily column** — hide if you only want chart-TF stats (on non-Daily charts)
Each section (Volatility, Price, Volume, CVD, RS, Meta) can be toggled off independently.
---
## CVD flow (Chart TF column)
Session cumulative delta uses **CLV bar delta** by default (close location × volume), with optional **candle-color** mode.
| Row | Daily column | Chart TF column |
|-----|--------------|-----------------|
| **Bar Δ** | Today’s daily bar delta | Current bar delta |
| **Sess CVD** | Session / daily CVD | **Z-score (σ)** vs rolling mean |
**Z-score** = how many standard deviations today’s session CVD is from its recent norm (lookback default 20 bars). Values beyond the **highlight threshold** (default ±2σ) turn yellow.
**RTH-only** *(default on intraday)* — delta and today-volume accumulation ignore pre/post market when enabled. Session timezone: NY (also Chicago / LA).
---
## How to read it (stocks)
### Intraday (5m / 15m)
- **Daily column** = “What kind of *day* is this?” (ADR context, today’s volume vs 50-day avg, daily LoD distance).
- **Chart TF column** = “What is *this bar* doing?” (bar delta, Z-score on session flow).
- **Rel. vol < 100%** on Daily = light day so far; **Vol. buzz** negative = below average pace.
### Daily chart
- Chart TF column **auto hidden** — one clean Daily column.
- **RS rating** shown in Daily column (requires daily history + seed curve).
### Volatility
- **ATR%** at top — how wide is normal movement as % of price?
- **ADR%** — average daily range over the lookback (default 20 sessions).
### Price position
- **LoD dist.** — how far price has recovered from today’s low in ATR units.
- **Off 52W High / Above 52W Low** — structural position in the year.
---
## Settings overview
| Group | Key controls |
|--------|----------------|
| **Dashboard** | Position, size, style (Dark / Transparent), columns, colors |
| **Display** | Toggle each section |
| **Parameters** | ADR length, ATR length, volume MA, U/D lookback |
| **CVD** | Delta method, RTH-only, timezone, Z lookback, Z highlight |
**Defaults:** Dark panel, both columns (Chart TF auto-hides on Daily), CLV delta, RTH-only on intraday, all main sections on, Meta off.
---
## Best used for
- Pre-trade **context card** on individual equities
- Comparing **daily swing stats** while executing on **5m / 15m**
- Spotting **unusual session flow** via CVD Z-score without a separate delta pane
- Pairing with structure / momentum tools — this script does not draw levels or signals
---
## Credits & license
Concepts adapted from community swing-data / ADR work (MikeC, Fred6724, TheScrutiniser, GlinckEastwoot). RS rating uses Fred6725 seed curve logic.
**License:** Mozilla Public License 2.0 — use, modify, and share with attribution. See script header for full terms.
---
## Disclaimer
This indicator is provided for **educational and informational purposes only**. It is **not financial, investment, trading, or tax advice**, and it is not a recommendation to buy, sell, or hold any security.
Volume-based delta and CVD are **proxies**, not exchange-reported order flow. Markets involve risk of loss. You alone are responsible for your trading decisions.
© bl4ckc0ff33
อินดิเคเตอร์

อินดิเคเตอร์

อินดิเคเตอร์

Volume Footprint: Measuring by Math & GeometryIntroduction
Volume tells you how much traded. A footprint tells you where.
A conventional volume bar compresses all trading activity within a candle into a single total. That total measures participation, but it does not show how the activity was distributed through price. Two candles can carry similar volume and range while containing very different internal structures.
A volume footprint restores this missing dimension. It organizes a bar's volume across price levels and separates buying from selling, so the candle becomes a readable column: where activity concentrated, where one side dominated, and where the two sides met.
This price-level structure is the basis for the measurements and diagnostics used throughout this indicator.
1. The volume footprint
As introduced above, a footprint reveals the role and position of the real participants inside a candle. The diagram below illustrates the structure:
The diagram shows the footprint structure of a single candle: volume is distributed across price levels and separated into sell and buy activity. This makes the internal distribution of participation visible instead of reducing the candle to one total volume figure.
The real challenge in constructing a footprint is how buy and sell volume are derived. TradingView’s native Footprint data provides the highest-fidelity source used by this indicator, but it is available only on Premium and Ultimate plans. To make the concept accessible to users on other plans, we therefore estimate buy and sell volume using the alternative methods described below. These methods are approximations, intended to explain and visualize footprint mechanics—not to claim the same precision as TradingView’s native Footprint data.
Buy/Sell Volume Calculation Engines
The indicator uses three methods as engines for calculating buy and sell volume. These engines are selected from the Engine option in the indicator settings and will be explained individually below.
- Geometric
- Intrabar
- Footprint
A. Geometric Calculation Engine
The Geometric engine estimates buy and sell volume from the position of the candle’s close within its high–low range. A close nearer the high assigns a larger share to buying volume, while a close nearer the low assigns a larger share to selling volume.
As shown in the image, the Geometric engine is an estimation model based on the position of the candle’s close within its high–low range. Buy and sell volume are calculated as:
If the candle has no range, volume is divided equally between buying and selling.
It is important to emphasize that this is an estimated representation of buy and sell activity, not true transaction-side volume. However, it can still provide a useful analytical framework for markets where reported volume is incomplete, fragmented, or not representative of a centralized market-wide feed, such as many cryptocurrency markets and spot gold.
B. Intrabar Calculation Engine
The Intrabar engine derives buy and sell volume from lower-timeframe activity inside each chart bar, using TradingView’s official ta library. Instead of estimating the split from the shape of the parent candle, it aggregates the lower-timeframe up and down volume returned by the library.
Higher intrabar resolution generally provides greater precision, but also reduces the amount of historical coverage available. Tick-level data offers the finest resolution where available, while a 1-minute lower timeframe provides a practical alternative that can also be used on lower TradingView plans. On higher chart timeframes, such as 4-hour or daily charts, the 1-minute series can provide a substantially finer approximation of the internal buy/sell structure than calculations based only on the parent candle.
In practical terms, Intrabar provides the middle ground between simple candle-based estimation and native Footprint data: more granular than Geometric, yet still accessible across a wider range of TradingView plans. Its effectiveness ultimately depends on how much lower-timeframe detail is available for the chart being analyzed.
C. Footprint Calculation Engine
The Footprint engine reads TradingView’s native volume-footprint data directly. Unlike the Geometric and Intrabar engines, buy and sell volume are not inferred from candle geometry or lower-timeframe direction; they are obtained from TradingView’s own price-level footprint structure.
This provides the highest-fidelity volume source used by the indicator and serves as the reference engine for footprint-based measurements. Access to this data requires a TradingView Premium or Ultimate plan.
How are the footprint price rows constructed when native row-level data is available only through TradingView’s Footprint engine on Premium and Ultimate plans?
For the native Footprint engine, each price row is read directly from TradingView together with its buy and sell volume. For the Geometric and Intrabar engines, only bar-level buy and sell totals are available, so these totals must be distributed across the candle’s price range. To accomplish this, the indicator uses a Gaussian distribution model.
What Is the Gaussian Distribution Model?
A Gaussian distribution is a bell-shaped mathematical model in which the greatest weight is concentrated around a central value and progressively decreases as distance from that center increases. In this indicator, it is used as a weighting model to distribute a bar’s total buy and sell volume across its price rows, rather than assigning the same amount of volume to every level.
The simplified diagrams below illustrate the basic idea before we apply it separately to the buy and sell sides of a candle.
Figure 1 — A single bell distributes one total; no volume is created or lost
Figure 2 — Both bells cover the full range; only their centers differ, and each sums back to its own total
As the Volume Engine and its role in the settings menu were explained earlier, we will follow the same approach here for the Footprint structure and Gaussian model. The relevant settings will be introduced alongside these concepts so their practical effect on the indicator can be understood directly.
Ticks Per Row
This setting controls the row size only for TradingView’s native Footprint engine. A value of 1 creates the finest available structure, with each row representing one minimum price increment of the symbol. Higher values group multiple ticks into wider native Footprint rows.
For the Geometric and Intrabar engines, this setting is not used. Their Gaussian price distribution is calculated on the indicator’s fixed one-tick price lattice, where each row corresponds to syminfo.mintick. This keeps their modeled price-level structure at the highest available symbol resolution.
Window Bars
This setting determines how many valid candle columns the footprint table displays. Its default value is 5, and it can be set from 2 to 60.
The important point is that Window Bars does not simply mean the last N consecutive candles. Starting from the current bar, the indicator scans backward and accepts a candle only when:
the active Volume Engine provides valid volume data for that candle,
its total calculated volume is greater than zero, and
its price range overlaps the price area currently displayed by the footprint table.
If a candle does not satisfy these conditions, it is skipped and the search continues farther back until the requested number of columns is collected.
This same selection logic applies to all three engines. The practical difference is only data availability: Geometric normally has data wherever chart volume exists, Intrabar is limited by the lower-timeframe history available to the selected plan, and Footprint requires valid native Footprint data for the candle.
The search can extend up to 5,000 historical bars. Therefore, Window Bars controls the number of qualifying columns displayed, not the chronological lookback period itself.
Ticks Above/Below
This setting defines the vertical price span of the footprint table around the current price. The default value is 5, with an adjustable range from 1 to 50.
A useful way to understand this behavior is to think of an analog aircraft altimeter. The reference point remains centered while the scale moves around it. In the same way, the indicator keeps the current price on the central row while the surrounding price ladder shifts as the market moves.
The selected value determines how many one-tick rows are shown above and below that center:
Visible Rows = (2 × Ticks Above/Below) + 1
For example, a value of 5 displays 11 price rows: five above the current price, five below it, and the central row itself.
This setting applies to all three Volume Engines and controls only the visible price frame. It does not alter the underlying volume calculation or the native row grouping of the Footprint engine. Volume outside the visible frame remains outside the display and is not merged into the boundary rows.
Like an analog altimeter — the needle stays put while the dial turns behind it
Volume Concentration
This setting controls the width of the Gaussian distributions used by the indicator. Its default value is 3.0, with an adjustable range from 1.0 to 10.0 in steps of 0.5.
The relationship is:
σ = (High − Low) / Volume Concentration
Therefore, a higher value produces a smaller σ and concentrates more volume around the center of each bell. A lower value produces a larger σ and spreads the volume more broadly toward the candle’s extremes.
For the footprint table, this setting affects the Gaussian price-row construction used by the Geometric and Intrabar engines. It does not modify the native price rows when the Footprint engine is selected, because those rows are read directly from TradingView.
The same setting is also used later in the indicator’s Volume Profile construction. There, the common Gaussian profile model uses this concentration parameter regardless of which Volume Engine supplied the underlying buy and sell totals—including the Footprint engine.
Figure 1 — Higher concentration → narrower bell → more volume at the center row
Figure 2 — Concentration reshapes the row distribution, never the bar's total volume
Show Table
This setting controls whether the footprint table itself is displayed on the chart. It is enabled by default.
When Show Table is turned on, the price ladder and its candle columns are drawn according to the current footprint settings. Turning it off removes this table from the chart and provides a cleaner visual workspace.
Importantly, this option controls display only. It does not change the selected Volume Engine or the buy/sell volume values calculated by the indicator. Those volume figures remain available in TradingView’s Data Window even when the footprint table is hidden.
Table Text Size & Table Position
Table Text Size controls the font size used inside the footprint table, allowing the display to be adjusted for readability or to accommodate larger tables.
Table Position determines where the footprint table is anchored on the chart by combining its vertical and horizontal placement options.
2. Point of Control (POC)
Now that the footprint structure and the distribution of buy and sell volume across price levels have been established, we can begin examining the information that can be derived from that structure. One of the most important of these concepts is the Point of Control (POC).
What Is the Point of Control?
The Point of Control is the price level at which the greatest total volume has traded within the analyzed distribution.
At each price level, buy and sell volume are combined:
Total Volume at Price = Buy Volume + Sell Volume
The price level with the highest resulting total becomes the POC.
The importance of the POC comes from what it represents: it identifies the price where market participation was most concentrated. In other words, within the analyzed structure, this is the level where the largest amount of business was conducted and therefore where price received the greatest volume-based acceptance.
The POC should not, however, be interpreted as a directional signal by itself. It identifies where the greatest activity occurred, not whether buyers or sellers dominated that activity. Directional information must be derived from the buy/sell composition and other footprint measurements surrounding that level.
Because the POC is calculated from a defined group of price-level data, its location also depends on the period or footprint window being analyzed. As the underlying volume distribution changes, the POC can shift to a different price level.
The POC marks where business concentrated — not which side won it
How the Indicator Uses the POC
Now that the meaning of the POC is clear, we can look one level deeper and see exactly how the indicator uses it. The POC is not treated as a single decorative level; it is calculated separately for the footprint table and the chart profile, then reused in several parts of the indicator.
A. Dashboard POC
Inside the footprint table, the indicator first sums the buy and sell volume of each visible price row across all qualifying Window Bars:
Row Volume = Σ Buy Volume + Σ Sell Volume
The visible price row with the largest combined volume becomes the Dashboard POC. This means the Dashboard POC belongs specifically to the footprint window currently being analyzed, not to the entire chart history.
B. POC marker and color in the table
The selected row is marked with ● POC in the Metrics column.
Its color describes the composition of that same price level:
Buy volume greater than sell volume → Buy color
Sell volume greater than buy volume → Sell color
Equal buy and sell volume → Neutral color
The color does not redefine the POC as bullish or bearish. The POC is still selected only by total volume; the color simply shows which side contributed more volume at that level.
The row information also retains the individual Sell, Buy, and Total volumes so the user can see what produced the POC.
C. Chart POC
The POC drawn beside the Volume Profile is calculated independently from the Dashboard POC.
Across the selected profile period, the indicator evaluates the Buy and Sell profile curves at successive price samples and combines them:
Combined Profile Intensity = Buy Density + Sell Density
The sampled price where this combined profile reaches its maximum becomes the Chart POC.
This distinction is important: the Dashboard POC is derived from the footprint table's visible price rows and Window Bars, while the Chart POC belongs to the separate Volume Profile period and its sampled profile structure. They can therefore appear at different prices without either calculation being incorrect.
D. POC and profile resolution
Because the Chart POC is found from the sampled Volume Profile curve, the profile's resolution determines how finely the indicator searches for its maximum. Increasing profile resolution provides a denser set of price samples and therefore a finer localization of the Chart POC, without changing the underlying volume itself.
E. POC as the starting point of Value Area
POC also has a structural role in the next concept we will discuss: Value Area.
Rather than finding Value Area independently, the indicator begins from the POC and expands outward through neighboring price levels until the selected percentage of volume has been accumulated. In this sense, POC is not only a displayed level; it is also the anchor from which the Value Area structure is built.
F. POC settings
The Point of Control setting determines where the metric is used:
Off
Dashboard
Chart
Dashboard and Chart
The accompanying offset controls how far the Chart POC line extends beyond the Volume Profile before its label is placed. It affects presentation, not the calculated POC price.
G. POC as an output level
The indicator also publishes the Dashboard POC and Chart POC as separate level series. This allows TradingView's standard alert conditions—such as crossing, crossing up, or crossing down—to be applied to either level. We will return to this functionality in the Alerts section.
The key point is that when you see a POC in this indicator, you can identify exactly which dataset produced it, how its price was selected, what its color means, and where that level is used elsewhere in the calculation.
3. Value Area (VAH / VAL)
Once the POC identifies the price where volume is most concentrated, the next question is:
how far does that concentration extend?
The Value Area answers this by defining the price range that contains a selected share of the analyzed volume, commonly 70%.
The calculation begins at the POC and expands outward through neighboring price levels. At each step, the side containing the greater adjacent volume is added first. This process continues until the required percentage of total volume has been included.
The resulting boundaries are:
VAH — Value Area High: the upper boundary of the Value Area.
VAL — Value Area Low: the lower boundary of the Value Area.
Conceptually, the structure can be pictured as:
VAL ← accepted volume ← POC → accepted volume → VAH
The POC marks the center of greatest volume concentration, while VAH and VAL define the broader region around it where most of the analyzed trading activity took place.
Prices inside this range represent the market’s main area of volume acceptance for the selected dataset; prices outside it belong to the lower-volume remainder of the distribution.
POC sits at the peak of the combined curve; VAH and VAL mark its 70% edges
How Value Area Appears in the Indicator
The same Value Area concept is presented in two analytical contexts:
Dashboard:
The calculation uses the volume distribution of the current Footprint Window. Starting from its POC, the indicator expands toward neighboring rows until the selected volume percentage is reached. The resulting boundaries are marked directly in the Metrics column as ▲ VAH and ▼ VAL, so the accepted-volume region can be read against the footprint price ladder.
Chart:
The chart uses the Volume Profile period rather than the Footprint Window. Its own POC becomes the starting reference, and the Value Area is calculated from the profile’s volume distribution. The resulting VAH and VAL are then drawn as horizontal levels around the profile, making the high-volume acceptance range visible directly on the chart.
Because the Dashboard and Chart analyze different datasets, their POC, VAH, and VAL levels do not necessarily have to coincide.
The Value Area setting determines whether these levels are calculated and displayed in the Dashboard, Chart, Dashboard and Chart, or turned Off. The percentage beside it defines the target share of volume, with 70% as the default.
4. Volume Imbalance
Once we know where volume concentrated, the next question is whether one side became unusually dominant at a particular price. Volume Imbalance is designed to identify exactly that condition.
Unlike a simple comparison of Buy and Sell volume on the same row, footprint imbalance is measured diagonally between neighboring price levels:
Buy Imbalance:
Buy volume at a price is compared with Sell volume one row below.
Sell Imbalance:
Sell volume at a price is compared with Buy volume one row above.
With the default threshold of 300%, the dominant side must exceed the opposing diagonal volume by more than three times before the level is classified as imbalanced.
Conceptually:
Buy Imbalance:
Buy(current row) > Sell(row below) × Threshold
Sell Imbalance:
Sell(current row) > Buy(row above) × Threshold
This diagonal comparison is important because it compares opposing activity across the neighboring prices where buyers and sellers effectively meet, rather than treating each row as an isolated number.
How the Indicator Uses Imbalance
Geometric and Intrabar:
The same diagonal rule is applied to the price rows constructed by the indicator.
Footprint:
When the native Footprint engine is selected, the indicator uses TradingView's own per-row Buy and Sell imbalance results. The selected Imbalance percentage is passed directly into the native Footprint request.
Footprint Table:
An imbalanced Buy or Sell cell receives a directional marker and stronger visual emphasis, making individual imbalances visible inside each candle column.
Dashboard Metrics:
The indicator also evaluates the combined Buy and Sell distribution across the complete Footprint Window. Price levels that satisfy the diagonal imbalance rule at the window level are marked in the Metrics column, allowing isolated candle imbalances to be distinguished from imbalance that persists across the broader window.
Chart:
For the Volume Profile period, imbalance is evaluated from the profile's Buy and Sell distribution and qualifying levels are shown as dotted horizontal marks on the chart.
Imbalance Setting
The Imbalance setting enables or disables these measurements, while the percentage beside it controls how strong the diagonal dominance must be. The default is 300%; increasing it requires a stronger imbalance, while decreasing it makes the measurement more sensitive.
The important distinction is that imbalance identifies relative dominance at specific neighboring prices. It does not simply tell us which side has more total volume across the candle or profile.
Figure 1 — Buy vs sell one row below · sell vs buy one row above · threshold 300%
Figure 2 — A buy imbalance needs the buy row to beat the sell row below it by the threshold
Figure 3 — Sell(P) > Buy(P + 1) × threshold · the buy rule flipped upside down
5. Delta and Totals
After identifying where volume is concentrated and where local imbalances appear, the same Buy/Sell data can be summarized through two direct measurements: Total Volume and Delta.
Total Volume shows how much activity occurred:
Total = Buy Volume + Sell Volume
Delta shows the difference between the two sides:
Delta = Buy Volume − Sell Volume
A positive Delta means Buy volume was greater, while a negative Delta means Sell volume was greater. A value near zero indicates that the two sides contributed similar amounts of volume.
The important distinction is that Delta measures volume dominance, not price direction. A candle can rise while having negative Delta, or fall while having positive Delta, because price movement and Buy/Sell volume balance describe different aspects of market activity.
How They Appear in the Dashboard
At the bottom of each Footprint candle column, the indicator displays:
Total: the complete Buy + Sell volume of that candle.
Delta: the Buy − Sell difference for that candle.
Positive Delta is displayed in the Buy color and negative Delta in the Sell color, while Total remains neutral.
The Sum column applies the same calculation to the entire Footprint Window. It combines the Buy and Sell totals of all qualifying Window Bars and reports:
Window Total = Σ Buy + Σ Sell
Window Delta = Σ Buy − Σ Sell
This allows the user to compare the balance of an individual candle with the broader balance of the complete Footprint Window.
Current-Bar Summary
The status bar at the top of the table also provides a live summary of the current candle, including its Total Volume, Sell Volume, Buy Volume, and the side currently leading.
The lead percentage measures how large the Buy/Sell difference is relative to the candle's total volume:
Lead % = |Buy − Sell| / Total × 100
This makes it possible to distinguish between a small numerical advantage and a genuinely meaningful difference in participation.
The background color of this status bar follows the candle's price change, not its Delta. Therefore, price direction and volume dominance remain intentionally separate.
On the Chart
Total and Delta are not drawn as independent horizontal levels on the chart. Instead, their underlying Buy and Sell volumes continue into the Volume Profile calculations, where the distribution and broader balance between the two sides are analyzed in greater detail.
So while Imbalance asks where one side became unusually dominant at specific neighboring prices, Delta answers a broader question:
Which side carried more volume over this candle or window, and by how much?
6. The Volume Profile
The Footprint shows volume inside individual candles. The Volume Profile takes the next step and combines that information across a selected period to show where Buy and Sell activity accumulated through price.
Instead of one conventional profile, the indicator builds two separate distributions:
Buy Profile
Sell Profile
For every bar in the selected period, its Buy and Sell totals are distributed through that bar’s High–Low range using the same Gaussian framework introduced earlier. These individual distributions are then added together to create the two final profile curves.
An important distinction is that this common profile model is used for all three Volume Engines. Even when the Footprint engine is selected, the chart profile is constructed from its bar-level Buy and Sell totals rather than directly reproducing TradingView’s native footprint rows. This gives all engines the same mathematical basis for profile comparison.
How It Appears on the Chart
The profile spans from the lowest Low to the highest High of the selected period and is drawn to the right of the latest candle.
Both curves grow from the same baseline and use the same horizontal scale, so their relative widths remain meaningful:
Wider Buy curve → greater Buy intensity at that price
Wider Sell curve → greater Sell intensity at that price
Where the two filled curves overlap, the chart also makes the shared price territory visually apparent.
This profile becomes the foundation for several measurements already introduced or still to come, including Chart POC, VAH/VAL, profile Imbalances, OVL, Balance Tilt, and the Residual self-check.
Main Profile Settings
Profile Period: number of bars included in the calculation.
Profile Width: horizontal drawing size of the profile.
Profile Resolution: number of price samples used to trace the curves; higher values produce finer visual resolution without changing the underlying volume model.
Buy / Sell visibility, Fill and Colors: control presentation only.
In short, the Footprint answers what happened inside each candle, while the Volume Profile reorganizes the same Buy/Sell information around price across an entire period.
Same horizontal scale on both sides — so relative widths are directly comparable
7. Overlapping Coefficient (OVL) and Balance Tilt
The Buy and Sell profiles tell us where each side was active. The next question is:
how much did they operate at the same prices?
The Overlapping Coefficient (OVL) measures this shared price territory.
Before comparison, the Buy and Sell profiles are normalized so that differences in total volume do not distort their shapes. The indicator then measures the common area between the two distributions.
Conceptually:
OVL = Shared Area of the Normalized Buy and Sell Profiles
Its range is:
0.00 → almost no overlap
1.00 → complete overlap
A high OVL means Buy and Sell activity occurred largely at the same prices. A low OVL means the two sides occupied increasingly different price regions.
How the Indicator Interprets OVL
The indicator uses 0.75 as its balance boundary:
OVL ≥ 0.75 → BALANCED
OVL < 0.75 → OFF BALANCE
But OVL alone tells us only that the distributions have separated; it does not tell us which side carried more total volume. For that, the indicator uses Balance Tilt:
Balance Tilt = (Buy Volume − Sell Volume) / Total Volume × 100
Positive values lean toward Buy, while negative values lean toward Sell.
The Balance Tilt % setting determines how large this difference must be before a direction is named. Its default is 5%.
Therefore, when OVL is below 0.75, the chart can report:
OFF BALANCE TO BUY
OFF BALANCE TO SELL
OFF BALANCE — when the volume difference is too small to assign a direction confidently.
On the Chart
The OVL reading appears at the top of the Volume Profile and reports both the coefficient and its interpretation.
This gives two complementary pieces of information:
OVL → Are Buy and Sell occurring at the same prices?
Tilt → If not, which side carries more total volume?
OVL: how much do buy and sell share the same prices?
Balance Tilt: which side carried more total volume
Two questions, answered in order
OVL asks how much the sides share the same prices; Tilt names the heavier side only when OVL says off balance
OVL measures shared prices · Tilt classifies direction when off balance · together they read the profile's balance
8. Residual Self-Check (RES)
Because the Volume Profile is built mathematically, the indicator also verifies that its own reconstruction has not created or lost meaningful volume.
For each side, it compares the original Buy or Sell total with the volume recovered from the complete profile model—including the Gaussian curves and any zero-range bars represented as point masses.
Conceptually:
Residual = Difference between original volume and reconstructed profile volume
The Buy and Sell errors are combined and expressed in parts per million (PPM). A value close to zero means the profile reproduces its source volume with extremely small numerical error.
How It Appears on the Chart
The RES reading is displayed beneath the Volume Profile:
EXACT — Residual is within the permitted tolerance.
DRIFT — Residual exceeds that tolerance.
The default Residual Tolerance is 1 PPM. Lower values make the self-check stricter; higher values allow more numerical deviation.
RES is therefore not a market signal. It is a diagnostic of the indicator itself: a confirmation that the profile you are analyzing remains mathematically consistent with the volume from which it was constructed.
9. Remaining Settings
Most analytical settings have already been explained alongside the concepts they control. Only a few display-related controls remain:
Balance Tilt % sets the minimum Buy/Sell volume difference required before an off-balance profile is labeled toward Buy or Sell. The default is 5%.
Residual Tolerance PPM defines the maximum RES value still classified as EXACT. The default is 1 PPM.
Label Merge Ticks controls how close chart labels may be before they are combined to prevent overlap. A value of 0 keeps nearby labels separate.
Frame Lines control only the color, thickness, and style of the Volume Profile boundary lines.
The remaining profile visibility, colors, fill opacity, width, and resolution settings affect presentation only and were introduced with the Volume Profile itself.
10. Alerts
The indicator does not impose a predefined trading signal. Instead, it publishes its two POC levels as separate series so they can be used directly inside TradingView’s standard Alert dialog:
Dashboard POC — the POC calculated from the current Footprint Window.
Chart POC — the POC calculated from the Volume Profile period.
After selecting either series as the alert source, TradingView’s normal conditions can be applied, including actions such as:
Crossing · Crossing Up · Crossing Down · Greater Than · Less Than
This keeps the alert logic flexible. The indicator provides the calculated level; the user decides what interaction between price and that level is important for the strategy being monitored.
For example:
Price crosses above Chart POC → Crossing Up
Price crosses below Dashboard POC → Crossing Down
Dashboard POC and Chart POC remain independent, so an alert can be built around either the short footprint window or the broader profile structure.
Publisher’s Note
Volume is one of the fundamental dimensions of market analysis because it reveals the level of participation behind price and helps us understand where trading activity is taking place.
This indicator was created first to make Footprint concepts accessible across TradingView plans. The Geometric and Intrabar engines provide approximate Buy/Sell representations, while the Footprint engine uses TradingView’s official native price-level data where available.
An important part of the project was to place these different data sources inside a common mathematical framework. TradingView’s native Footprint presents its price-level structure directly as footprint rows, while this indicator also uses Gaussian mathematics and price geometry to construct a comparable Buy/Sell Volume Profile from the bar-level totals of all three engines. In this way, different sources can be examined through the same analytical language rather than through unrelated visual forms.
The purpose is not to claim that an approximation is equivalent to native data. It is to make the differences measurable, understandable, and comparable. For users who enjoy investigating how markets are represented—and how different methods arrive at their results—the three engines can themselves become an interesting field of study.
Ultimately, the goal is simple: to move from merely seeing volume to understanding its structure. อินดิเคเตอร์
