Nqaba Probable High/Low{Larry Method}The Probable High/Low indicator is an advanced tool inspired by Larry R. Williams’ original projection formulas.
It calculates probable daily highs and lows based on the prior day’s open, high, low, and close, allowing traders to anticipate key intraday price levels with precision.
This version provides full control over visibility, styling, and historical analysis — making it both educational and powerful for active traders.
Statistics
Nqaba Probable High/Low — Overshoot/Undershoot{Larry Method)This Probable High/Low indicator is an advanced tool inspired by Larry R. Williams’ original projection formulas.
It calculates probable daily highs and lows based on the prior day’s open, high, low, and close, allowing traders to anticipate key intraday price levels with precision.
Central Limit Theorem Reversion IndicatorDear TV community, let me introduce you to the first-ever Central Limit Theorem indicator on TradingView.
The Central Limit Theorem is used in statistics and it can be quite useful in quant trading and understanding market behaviors.
In short, the CLT states: "When you take repeated samples from any population and calculate their averages, those averages will form a normal (bell curve) distribution—no matter what the original data looks like."
In this CLT indicator, I use statistical theory to identify high-probability mean reversion opportunities in the markets. It calculates statistical confidence bands and z-scores to identify when price movements deviate significantly from their expected distribution, signaling potential reversion opportunities with quantifiable probability levels.
Mathematical Foundation
The Central Limit Theorem (CLT) says that when you average many data points together, those averages will form a predictable bell-curve pattern, even if the original data is completely random and unpredictable (which often is in the markets). This works no matter what you're measuring, and it gets more reliable as you use more data points.
Why using it for trading?
Individual price movements seem random and chaotic, but when we look at the average of many price movements, we can actually predict how they should behave statistically. This lets us spot when prices have moved "too far" from what's normal—and those extreme moves tend to snap back (mean reversion).
Key Formula:
Z = (X̄ - μ) / (σ / √n)
Where:
- X̄ = Sample mean (average return over n periods)
- μ = Population mean (long-term expected return)
- σ = Population standard deviation (volatility)
- n = Sample size
- σ/√n = Standard error of the mean
How I Apply CLT
Step 1: Calculate Returns
Measures how much price changed from one bar to the next (using logarithms for better statistical properties)
Step 2: Average Recent Returns
Takes the average of the last n returns (e.g., last 100 bars). This is your "sample mean."
Step 3: Find What's "Normal"
Looks at historical data to determine: a) What the typical average return should be (the long-term mean) and b) How volatile the market usually is (standard deviation)
Step 4: Calculate Standard Error
Determines how much sample averages naturally vary. Larger samples = smaller expected variation.
Step 5: Calculate Z-Score
Measures how unusual the current situation is.
Step 6: Draw Confidence Bands
Converts these statistical boundaries into actual price levels on your chart, showing where price is statistically expected to stay 95% and 99% of the time.
Interpretation & Usage
The Z-Score:
The z-score tells you how statistically unusual the current price deviation is:
|Z| < 1.0 → Normal behavior, no action
|Z| = 1.0 to 1.96 → Moderate deviation, watch closely
|Z| = 1.96 to 2.58 → Significant deviation (95%+), consider entry
|Z| > 2.58 → Extreme deviation (99%+), high probability setup
The Confidence Bands
- Upper Red Bands: 95% and 99% overbought zones → Expect mean reversion downward as the price is not likely to cross these lines.
- Center Gray Line: Statistical expectation (fair value)
- Lower Blue Bands: 95% and 99% oversold zones → Expect mean reversion upward
Trading Logic:
- When price exceeds the upper 95% band (z-score > +1.96), there's only a 5% probability this is random noise → Strong sell/short signal
- When price falls below the lower 95% band (z-score < -1.96), there's a 95% statistical expectation of upward reversion → Strong buy/long signal
Background Gradient
The background color provides real-time visual feedback:
- Blue shades: Oversold conditions, expect upward reversion
- Red shades: Overbought conditions, expect downward reversion
- Intensity: Darker colors indicate stronger statistical significance
Trading Strategy Examples
Hypothetically, this is how the indicator could be used:
- Long: Z-score < -1.96 (below 95% confidence band)
- Short: Z-score > +1.96 (above 95% confidence band)
- Take profit when price returns to center line (Z ≈ 0)
Input Parameters
Sample Size (n) - Default: 100
Lookback Period (m) - Default: 100
You can also create alerts based on the indicator.
Final notes:
- The indicator uses logarithmic returns for better statistical properties
- Converts statistical bands back to price space for practical use
- Adaptive volatility: Bands automatically widen in high volatility, narrow in low volatility
- No repainting: yay! All calculations use historical data only
Feedback is more than welcome!
Henri
Continuation Probability (0–100)This indicator helps measure how likely the current candle trend will continue or reverse, giving a probability score between 0–100.
It combines multiple market factors trend, candle strength, volume, and volatility to create a single, intuitive signal.
Stablecoin Liquidity Delta (Aggregate Market Cap Flow)Hi All,
This indicator visualizes the bar-to-bar change in the aggregate market capitalization of major stablecoins, including USDT, USDC, DAI, and others. It serves as a proxy for monitoring on-chain liquidity and measuring capital inflows or outflows across the crypto market.
Stablecoins are the primary liquidity layer of the crypto economy. Their combined market capitalization acts as a mirror of the available fiat-denominated liquidity in digital markets:
🟩 An increase in the total stablecoin market capitalization indicates new issuance (capital entering the market).
🟥 A decrease reflects redemption or burning (liquidity exiting the system).
Tracking these flows helps anticipate macro-level liquidity trends that often lead overall market direction, providing context for broader price movements.
All values are derived from TradingView’s public CRYPTOCAP tickers, which represent the market capitalization of each stablecoin. While minor deviations can occur due to small price fluctuations around the $1 peg, these figures serve as a proxy for circulating supply and net issuance across the stablecoin ecosystem.
Vandan V2Vandan V2 is an automated trend-following strategy for NASDAQ E-mini Futures (NQ1!).
It uses multi-timeframe momentum and volatility filters to identify high-probability entries.
Includes dynamic risk management and trailing logic optimized for intraday trading.
Simple FloatFloat Display Indicator
A simple, clean indicator that displays the current float (shares outstanding float) for any stock directly in your indicator status line at the top left of the chart.
Features:
- Shows the float value with automatic K/M formatting for thousands and millions
- No chart clutter - value only appears in the status line, nothing plotted on the chart
- Works on any stock that has float data available
- Lightweight and efficient
Perfect for traders who want quick access to float information without switching between windows or cluttering their charts.
Note: Float data availability depends on TradingView's financial data for the specific ticker. Some tickers may not have this data available.
Risk Position Sizer (Entry=Close, Stop=Daily Low)This is for trading stocks/shares. Its main goal is to help you gauge how big or how small of a position you should add based on your account size.
LibVPrfLibrary "LibVPrf"
This library provides an object-oriented framework for volume
profile analysis in Pine Script®. It is built around the `VProf`
User-Defined Type (UDT), which encapsulates all data, settings,
and statistical metrics for a single profile, enabling stateful
analysis with on-demand calculations.
Key Features:
1. **Object-Oriented Design (UDT):** The library is built around
the `VProf` UDT. This object encapsulates all profile data
and provides methods for its full lifecycle management,
including creation, cloning, clearing, and merging of profiles.
2. **Volume Allocation (`AllotMode`):** Offers two methods for
allocating a bar's volume:
- **Classic:** Assigns the entire bar's volume to the close
price bucket.
- **PDF:** Distributes volume across the bar's range using a
statistical price distribution model from the `LibBrSt` library.
3. **Buy/Sell Volume Splitting (`SplitMode`):** Provides methods
for classifying volume into buying and selling pressure:
- **Classic:** Classifies volume based on the bar's color (Close vs. Open).
- **Dynamic:** A specific model that analyzes candle structure
(body vs. wicks) and a short-term trend factor to
estimate the buy/sell share at each price level.
4. **Statistical Analysis (On-Demand):** Offers a suite of
statistical metrics calculated using a "Lazy Evaluation"
pattern (computed only when requested via `get...` methods):
- **Central Tendency:** Point of Control (POC), VWAP, and Median.
- **Dispersion:** Value Area (VA) and Population Standard Deviation.
- **Shape:** Skewness and Excess Kurtosis.
- **Delta:** Cumulative Volume Delta, including its
historical high/low watermarks.
5. **Structural Analysis:** Includes a parameter-free method
(`getSegments`) to decompose a profile into its fundamental
unimodal segments, allowing for modality detection (e.g.,
identifying bimodal profiles).
6. **Dynamic Profile Management:**
- **Auto-Fitting:** Profiles set to `dynamic = true` will
automatically expand their price range to fit new data.
- **Manipulation:** The resolution, price range, and Value Area
of a dynamic profile can be changed at any time. This
triggers a resampling process that uses a **linear
interpolation model** to re-bucket existing volume.
- **Assumption:** Non-dynamic profiles are fixed and will throw
a `runtime.error` if `addBar` is called with data
outside their initial range.
7. **Bucket-Level Access:** Provides getter methods for direct
iteration and analysis of the raw buy/sell volume and price
boundaries of each individual price bucket.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
create(buckets, rangeUp, rangeLo, dynamic, valueArea, allot, estimator, cdfSteps, split, trendLen)
Construct a new `VProf` object with fixed bucket count & range.
Parameters:
buckets (int) : series int number of price buckets ≥ 1
rangeUp (float) : series float upper price bound (absolute)
rangeLo (float) : series float lower price bound (absolute)
dynamic (bool) : series bool Flag for dynamic adaption of profile ranges
valueArea (int) : series int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : series AllotMode Allocation mode `classic` or `pdf` (default `classic`)
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : series LibBrSt.PriceEst PDF model when `model == PDF`. (deflault = 'uniform')
cdfSteps (int) : series int even #sub-intervals for Simpson rule (default 20)
split (series SplitMode) : series SplitMode Buy/Sell determination (default `classic`)
trendLen (int) : series int Look‑back bars for trend factor (default 3)
Returns: VProf freshly initialised profile
method clone(self)
Create a deep copy of the volume profile.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object to copy
Returns: VProf A new, independent copy of the profile
method clear(self)
Reset all bucket tallies while keeping configuration intact.
Namespace types: VProf
Parameters:
self (VProf) : VProf profile object
Returns: VProf cleared profile (chaining)
method merge(self, srcABuy, srcASell, srcRangeUp, srcRangeLo, srcCvd, srcCvdHi, srcCvdLo)
Merges volume data from a source profile into the current profile.
If resizing is needed, it performs a high-fidelity re-bucketing of existing
volume using a linear interpolation model inferred from neighboring buckets,
preventing aliasing artifacts and ensuring accurate volume preservation.
Namespace types: VProf
Parameters:
self (VProf) : VProf The target profile object to merge into.
srcABuy (array) : array The source profile's buy volume bucket array.
srcASell (array) : array The source profile's sell volume bucket array.
srcRangeUp (float) : series float The upper price bound of the source profile.
srcRangeLo (float) : series float The lower price bound of the source profile.
srcCvd (float) : series float The final Cumulative Volume Delta (CVD) value of the source profile.
srcCvdHi (float) : series float The historical high-water mark of the CVD from the source profile.
srcCvdLo (float) : series float The historical low-water mark of the CVD from the source profile.
Returns: VProf `self` (chaining), now containing the merged data.
method addBar(self, offset)
Add current bar’s volume to the profile (call once per realtime bar).
classic mode: allocates all volume to the close bucket and classifies
by `close >= open`. PDF mode: distributes volume across buckets by the
estimator’s CDF mass. For `split = dynamic`, the buy/sell share per
price is computed via context-driven piecewise s(u).
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
offset (int) : series int To offset the calculated bar
Returns: VProf `self` (method chaining)
method setBuckets(self, buckets)
Sets the number of buckets for the volume profile.
Behavior depends on the `isDynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing to a new resolution.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
buckets (int) : series int The new number of buckets
Returns: VProf `self` (chaining)
method setRanges(self, rangeUp, rangeLo)
Sets the price range for the volume profile.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing existing volume.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
rangeUp (float) : series float The new upper price bound
rangeLo (float) : series float The new lower price bound
Returns: VProf `self` (chaining)
method setValueArea(self, valueArea)
Set the percentage of volume for the Value Area. If the value
changes, the profile is finalized again.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
valueArea (int) : series int The new Value Area percentage (0..100)
Returns: VProf `self` (chaining)
method getBktBuyVol(self, idx)
Get Buy volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Buy volume ≥ 0
method getBktSellVol(self, idx)
Get Sell volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Sell volume ≥ 0
method getBktBnds(self, idx)
Get Bounds of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns:
up series float The upper price bound of the bucket.
lo series float The lower price bound of the bucket.
method getPoc(self)
Get POC information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
pocIndex series int The index of the Point of Control (POC) bucket.
pocPrice. series float The mid-price of the Point of Control (POC) bucket.
method getVA(self)
Get Value Area (VA) information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
vaUpIndex series int The index of the upper bound bucket of the Value Area.
vaUpPrice series float The upper price bound of the Value Area.
vaLoIndex series int The index of the lower bound bucket of the Value Area.
vaLoPrice series float The lower price bound of the Value Area.
method getMedian(self)
Get the profile's median price and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
medianIndex series int The index of the bucket containing the Median.
medianPrice series float The Median price of the profile.
method getVwap(self)
Get the profile's VWAP and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
vwapIndex series int The index of the bucket containing the VWAP.
vwapPrice series float The Volume Weighted Average Price of the profile.
method getStdDev(self)
Get the profile's volume-weighted standard deviation. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Standard deviation of the profile.
method getSkewness(self)
Get the profile's skewness. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Skewness of the profile.
method getKurtosis(self)
Get the profile's excess kurtosis. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Kurtosis of the profile.
method getSegments(self)
Get the profile's fundamental unimodal segments. Calculates on-demand if stale.
Uses a parameter-free, pivot-based recursive algorithm.
Namespace types: VProf
Parameters:
self (VProf) : VProf The profile object.
Returns: matrix A 2-column matrix where each row is an pair.
method getCvd(self)
Cumulative Volume Delta (CVD) like metric over all buckets.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
cvd series float The final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi series float The running high-water mark of the CVD as volume was added.
cvdLo series float The running low-water mark of the CVD as volume was added.
VProf
VProf Bucketed Buy/Sell volume profile plus meta information.
Fields:
buckets (series int) : int Number of price buckets (granularity ≥1)
rangeUp (series float) : float Upper price range (absolute)
rangeLo (series float) : float Lower price range (absolute)
dynamic (series bool) : bool Flag for dynamic adaption of profile ranges
valueArea (series int) : int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : AllotMode Allocation mode `classic` or `pdf`
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : LibBrSt.PriceEst Price density model when `model == PDF`
cdfSteps (series int) : int Simpson integration resolution (even ≥2)
split (series SplitMode) : SplitMode Buy/Sell split strategy per bar
trendLen (series int) : int Look‑back length for trend factor (≥1)
maxBkt (series int) : int User-defined number of buckets (unclamped)
aBuy (array) : array Buy volume per bucket
aSell (array) : array Sell volume per bucket
cvd (series float) : float Final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi (series float) : float Running high-water mark of the CVD as volume was added.
cvdLo (series float) : float Running low-water mark of the CVD as volume was added.
poc (series int) : int Index of max‑volume bucket (POC). Is `na` until calculated.
vaUp (series int) : int Index of upper Value‑Area bound. Is `na` until calculated.
vaLo (series int) : int Index of lower value‑Area bound. Is `na` until calculated.
median (series float) : float Median price of the volume distribution. Is `na` until calculated.
vwap (series float) : float Profile VWAP (Volume Weighted Average Price). Is `na` until calculated.
stdDev (series float) : float Standard Deviation of volume around the VWAP. Is `na` until calculated.
skewness (series float) : float Skewness of the volume distribution. Is `na` until calculated.
kurtosis (series float) : float Excess Kurtosis of the volume distribution. Is `na` until calculated.
segments (matrix) : matrix A 2-column matrix where each row is an pair. Is `na` until calculated.
LibBrStLibrary "LibBrSt"
This is a library for quantitative analysis, designed to estimate
the statistical properties of price movements *within* a single
OHLC bar, without requiring access to tick data. It provides a
suite of estimators based on various statistical and econometric
models, allowing for analysis of intra-bar volatility and
price distribution.
Key Capabilities:
1. **Price Distribution Models (`PriceEst`):** Provides a selection
of estimators that model intra-bar price action as a probability
distribution over the range. This allows for the
calculation of the intra-bar mean (`priceMean`) and standard
deviation (`priceStdDev`) in absolute price units. Models include:
- **Symmetric Models:** `uniform`, `triangular`, `arcsine`,
`betaSym`, and `t4Sym` (Student-t with fat tails).
- **Skewed Models:** `betaSkew` and `t4Skew`, which adjust
their shape based on the Open/Close position.
- **Model Assumptions:** The skewed models rely on specific
internal constants. `betaSkew` uses a fixed concentration
parameter (`BETA_SKEW_CONCENTRATION = 4.0`), and `t4Sym`/`t4Skew`
use a heuristic scaling factor (`T4_SHAPE_FACTOR`)
to map the distribution.
2. **Econometric Log-Return Estimators (`LogEst`):** Includes a set of
econometric estimators for calculating the volatility (`logStdDev`)
and drift (`logMean`) of logarithmic returns within a single bar.
These are unit-less measures. Models include:
- **Parkinson (1980):** A High-Low range estimator.
- **Garman-Klass (1980):** An OHLC-based estimator.
- **Rogers-Satchell (1991):** An OHLC estimator that accounts
for non-zero drift.
3. **Distribution Analysis (PDF/CDF):** Provides functions to work
with the Probability Density Function (`pricePdf`) and
Cumulative Distribution Function (`priceCdf`) of the
chosen price model.
- **Note on `priceCdf`:** This function uses analytical (exact)
calculations for the `uniform`, `triangular`, and `arcsine`
models. For all other models (e.g., `betaSkew`, `t4Skew`),
it uses **numerical integration (Simpson's rule)** as
an approximation of the cumulative probability.
4. **Mathematical Functions:** The library's Beta distribution
models (`betaSym`, `betaSkew`) are supported by an internal
implementation of the natural log-gamma function, which is
based on the Lanczos approximation.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
priceStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) *in price units* for the current
bar, according to the chosen `PriceEst` distribution assumption.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ ≥ 0 ; `na` if undefined (e.g. zero range).
priceMean(estimator, offset)
Estimates **μ̂** (mean price) for the chosen `PriceEst` within the
current bar.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ in price units.
pricePdf(estimator, price, offset)
Probability-density under the chosen `PriceEst` model.
**Returns 0** when `p` is outside the current bar’s .
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
price (float) : series float Price level to evaluate.
offset (int) : series int To offset the calculated bar
Returns: series float Density value.
priceCdf(estimator, upper, lower, steps, offset)
Cumulative probability **between** `upper` and `lower` under
the chosen `PriceEst` model. Outside-bar regions contribute zero.
Uses a fast, analytical calculation for Uniform, Triangular, and
Arcsine distributions, and defaults to numerical integration
(Simpson's rule) for more complex models.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
upper (float) : series float Upper Integration Boundary.
lower (float) : series float Lower Integration Boundary.
steps (int) : series int # of sub-intervals for numerical integration (if used).
offset (int) : series int To offset the calculated bar.
Returns: series float Probability mass ∈ .
logStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) of *log-returns* for the current bar.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ (unit-less); `na` if undefined.
logMean(estimator, offset)
Estimates μ̂ (mean log-return / drift) for the chosen `LogEst`.
The returned value is consistent with the assumptions of the
selected volatility estimator.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ (unit-less log-return).
Scientific Correlation Testing FrameworkScientific Correlation Testing Framework - Comprehensive Guide
Introduction to Correlation Analysis
What is Correlation?
Correlation is a statistical measure that describes the degree to which two assets move in relation to each other. Think of it like measuring how closely two dancers move together on a dance floor.
Perfect Positive Correlation (+1.0): Both dancers move in perfect sync, same direction, same speed
Perfect Negative Correlation (-1.0): Both dancers move in perfect sync but in opposite directions
Zero Correlation (0): The dancers move completely independently of each other
In financial markets, correlation helps us understand relationships between different assets, which is crucial for:
Portfolio diversification
Risk management
Pairs trading strategies
Hedging positions
Market analysis
Why This Script is Special
This script goes beyond simple correlation calculations by providing:
Two different correlation methods (Pearson and Spearman)
Statistical significance testing to ensure results are meaningful
Rolling correlation analysis to track how relationships change over time
Visual representation for easy interpretation
Comprehensive statistics table with detailed metrics
Deep Dive into the Script's Components
1. Input Parameters Explained-
Symbol Selection:
This allows you to select the second asset to compare with the chart's primary asset
Default is Apple (NASDAQ:AAPL), but you can change this to any symbol
Example: If you're viewing a Bitcoin chart, you might set this to "NASDAQ:TSLA" to see if Bitcoin and Tesla are correlated
Correlation Window (60): This is the number of periods used to calculate the main correlation
Larger values (e.g., 100-500) provide more stable, long-term correlation measures
Smaller values (e.g., 10-50) are more responsive to recent price movements
60 is a good balance for most daily charts (about 3 months of trading days)
Rolling Correlation Window (20): A shorter window to detect recent changes in correlation
This helps identify when the relationship between assets is strengthening or weakening
Default of 20 is roughly one month of trading days
Return Type: This determines how price changes are calculated
Simple Returns: (Today's Price - Yesterday's Price) / Yesterday's Price
Easy to understand: "The asset went up 2% today"
Log Returns: Natural logarithm of (Today's Price / Yesterday's Price)
More mathematically elegant for statistical analysis
Better for time-additive properties (returns over multiple periods)
Less sensitive to extreme values.
Confidence Level (95%): This determines how certain we want to be about our results
95% confidence means we accept a 5% chance of being wrong (false positive)
Higher confidence (e.g., 99%) makes the test more strict
Lower confidence (e.g., 90%) makes the test more lenient
95% is the standard in most scientific research
Show Statistical Significance: When enabled, the script will test if the correlation is statistically significant or just due to random chance.
Display options control what you see on the chart:
Show Pearson/Spearman/Rolling Correlation: Toggle each correlation type on/off
Show Scatter Plot: Displays a scatter plot of returns (limited to recent points to avoid performance issues)
Show Statistical Tests: Enables the detailed statistics table
Table Text Size: Adjusts the size of text in the statistics table
2.Functions explained-
calcReturns():
This function calculates price returns based on your selected method:
Log Returns:
Formula: ln(Price_t / Price_t-1)
Example: If a stock goes from $100 to $101, the log return is ln(101/100) = ln(1.01) ≈ 0.00995 or 0.995%
Benefits: More symmetric, time-additive, and better for statistical modeling
Simple Returns:
Formula: (Price_t - Price_t-1) / Price_t-1
Example: If a stock goes from $100 to $101, the simple return is (101-100)/100 = 0.01 or 1%
Benefits: More intuitive and easier to understand
rankArray():
This function calculates the rank of each value in an array, which is used for Spearman correlation:
How ranking works:
The smallest value gets rank 1
The second smallest gets rank 2, and so on
For ties (equal values), they get the average of their ranks
Example: For values
Sorted:
Ranks: (the two 2s tie for ranks 1 and 2, so they both get 1.5)
Why this matters: Spearman correlation uses ranks instead of actual values, making it less sensitive to outliers and non-linear relationships.
pearsonCorr():
This function calculates the Pearson correlation coefficient:
Mathematical Formula:
r = (nΣxy - ΣxΣy) / √
Where x and y are the two variables, and n is the sample size
What it measures:
The strength and direction of the linear relationship between two variables
Values range from -1 (perfect negative linear relationship) to +1 (perfect positive linear relationship)
0 indicates no linear relationship
Example:
If two stocks have a Pearson correlation of 0.8, they have a strong positive linear relationship
When one stock goes up, the other tends to go up in a fairly consistent proportion
spearmanCorr():
This function calculates the Spearman rank correlation:
How it works:
Convert each value in both datasets to its rank
Calculate the Pearson correlation on the ranks instead of the original values
What it measures:
The strength and direction of the monotonic relationship between two variables
A monotonic relationship is one where as one variable increases, the other either consistently increases or decreases
It doesn't require the relationship to be linear
When to use it instead of Pearson:
When the relationship is monotonic but not linear
When there are significant outliers in the data
When the data is ordinal (ranked) rather than interval/ratio
Example:
If two stocks have a Spearman correlation of 0.7, they have a strong positive monotonic relationship
When one stock goes up, the other tends to go up, but not necessarily in a straight-line relationship
tStatistic():
This function calculates the t-statistic for correlation:
Mathematical Formula: t = r × √((n-2)/(1-r²))
Where r is the correlation coefficient and n is the sample size
What it measures:
How many standard errors the correlation is away from zero
Used to test the null hypothesis that the true correlation is zero
Interpretation:
Larger absolute t-values indicate stronger evidence against the null hypothesis
Generally, a t-value greater than 2 (in absolute terms) is considered statistically significant at the 95% confidence level
criticalT() and pValue():
These functions provide approximations for statistical significance testing:
criticalT():
Returns the critical t-value for a given degrees of freedom (df) and significance level
The critical value is the threshold that the t-statistic must exceed to be considered statistically significant
Uses approximations since Pine Script doesn't have built-in statistical distribution functions
pValue():
Estimates the p-value for a given t-statistic and degrees of freedom
The p-value is the probability of observing a correlation as strong as the one calculated, assuming the true correlation is zero
Smaller p-values indicate stronger evidence against the null hypothesis
Standard interpretation:
p < 0.01: Very strong evidence (marked with **)
p < 0.05: Strong evidence (marked with *)
p ≥ 0.05: Weak evidence, not statistically significant
stdev():
This function calculates the standard deviation of a dataset:
Mathematical Formula: σ = √(Σ(x-μ)²/(n-1))
Where x is each value, μ is the mean, and n is the sample size
What it measures:
The amount of variation or dispersion in a set of values
A low standard deviation indicates that the values tend to be close to the mean
A high standard deviation indicates that the values are spread out over a wider range
Why it matters for correlation:
Standard deviation is used in calculating the correlation coefficient
It also provides information about the volatility of each asset's returns
Comparing standard deviations helps understand the relative riskiness of the two assets.
3.Getting Price Data-
price1: The closing price of the primary asset (the chart you're viewing)
price2: The closing price of the secondary asset (the one you selected in the input parameters)
Returns are used instead of raw prices because:
Returns are typically stationary (mean and variance stay constant over time)
Returns normalize for price levels, allowing comparison between assets of different values
Returns represent what investors actually care about: percentage changes in value
4.Information Table-
Creates a table to display statistics
Only shows on the last bar to avoid performance issues
Positioned in the top right of the chart
Has 2 columns and 15 rows
Populating the Table
The script then populates the table with various statistics:
Header Row: "Metric" and "Value"
Sample Information: Sample size and return type
Pearson Correlation: Value, t-statistic, p-value, and significance
Spearman Correlation: Value, t-statistic, p-value, and significance
Rolling Correlation: Current value
Standard Deviations: For both assets
Interpretation: Text description of the correlation strength
The table uses color coding to highlight important information:
Green for significant positive results
Red for significant negative results
Yellow for borderline significance
Color-coded headers for each section
=> Practical Applications and Interpretation
How to Interpret the Results
Correlation Strength
0.0 to 0.3 (or 0.0 to -0.3): Weak or no correlation
The assets move mostly independently of each other
Good for diversification purposes
0.3 to 0.7 (or -0.3 to -0.7): Moderate correlation
The assets show some tendency to move together (or in opposite directions)
May be useful for certain trading strategies but not extremely reliable
0.7 to 1.0 (or -0.7 to -1.0): Strong correlation
The assets show a strong tendency to move together (or in opposite directions)
Can be useful for pairs trading, hedging, or as a market indicator
Statistical Significance
p < 0.01: Very strong evidence that the correlation is real
Marked with ** in the table
Very unlikely to be due to random chance
p < 0.05: Strong evidence that the correlation is real
Marked with * in the table
Unlikely to be due to random chance
p ≥ 0.05: Weak evidence that the correlation is real
Not marked in the table
Could easily be due to random chance
Rolling Correlation
The rolling correlation shows how the relationship between assets changes over time
If the rolling correlation is much different from the long-term correlation, it suggests the relationship is changing
This can indicate:
A shift in market regime
Changing fundamentals of one or both assets
Temporary market dislocations that might present trading opportunities
Trading Applications
1. Portfolio Diversification
Goal: Reduce overall portfolio risk by combining assets that don't move together
Strategy: Look for assets with low or negative correlations
Example: If you hold tech stocks, you might add some utilities or bonds that have low correlation with tech
2. Pairs Trading
Goal: Profit from the relative price movements of two correlated assets
Strategy:
Find two assets with strong historical correlation
When their prices diverge (one goes up while the other goes down)
Buy the underperforming asset and short the outperforming asset
Close the positions when they converge back to their normal relationship
Example: If Coca-Cola and Pepsi are highly correlated but Coca-Cola drops while Pepsi rises, you might buy Coca-Cola and short Pepsi
3. Hedging
Goal: Reduce risk by taking an offsetting position in a negatively correlated asset
Strategy: Find assets that tend to move in opposite directions
Example: If you hold a portfolio of stocks, you might buy some gold or government bonds that tend to rise when stocks fall
4. Market Analysis
Goal: Understand market dynamics and interrelationships
Strategy: Analyze correlations between different sectors or asset classes
Example:
If tech stocks and semiconductor stocks are highly correlated, movements in one might predict movements in the other
If the correlation between stocks and bonds changes, it might signal a shift in market expectations
5. Risk Management
Goal: Understand and manage portfolio risk
Strategy: Monitor correlations to identify when diversification benefits might be breaking down
Example: During market crises, many assets that normally have low correlations can become highly correlated (correlation convergence), reducing diversification benefits
Advanced Interpretation and Caveats
Correlation vs. Causation
Important Note: Correlation does not imply causation
Example: Ice cream sales and drowning incidents are correlated (both increase in summer), but one doesn't cause the other
Implication: Just because two assets move together doesn't mean one causes the other to move
Solution: Look for fundamental economic reasons why assets might be correlated
Non-Stationary Correlations
Problem: Correlations between assets can change over time
Causes:
Changing market conditions
Shifts in monetary policy
Structural changes in the economy
Changes in the underlying businesses
Solution: Use rolling correlations to monitor how relationships change over time
Outliers and Extreme Events
Problem: Extreme market events can distort correlation measurements
Example: During a market crash, many assets may move in the same direction regardless of their normal relationship
Solution:
Use Spearman correlation, which is less sensitive to outliers
Be cautious when interpreting correlations during extreme market conditions
Sample Size Considerations
Problem: Small sample sizes can produce unreliable correlation estimates
Rule of Thumb: Use at least 30 data points for a rough estimate, 60+ for more reliable results
Solution:
Use the default correlation length of 60 or higher
Be skeptical of correlations calculated with small samples
Timeframe Considerations
Problem: Correlations can vary across different timeframes
Example: Two assets might be positively correlated on a daily basis but negatively correlated on a weekly basis
Solution:
Test correlations on multiple timeframes
Use the timeframe that matches your trading horizon
Look-Ahead Bias
Problem: Using information that wouldn't have been available at the time of trading
Example: Calculating correlation using future data
Solution: This script avoids look-ahead bias by using only historical data
Best Practices for Using This Script
1. Appropriate Parameter Selection
Correlation Window:
For short-term trading: 20-50 periods
For medium-term analysis: 50-100 periods
For long-term analysis: 100-500 periods
Rolling Window:
Should be shorter than the main correlation window
Typically 1/3 to 1/2 of the main window
Return Type:
For most applications: Log Returns (better statistical properties)
For simplicity: Simple Returns (easier to interpret)
2. Validation and Testing
Out-of-Sample Testing:
Calculate correlations on one time period
Test if they hold in a different time period
Multiple Timeframes:
Check if correlations are consistent across different timeframes
Economic Rationale:
Ensure there's a logical reason why assets should be correlated
3. Monitoring and Maintenance
Regular Review:
Correlations can change, so review them regularly
Alerts:
Set up alerts for significant correlation changes
Documentation:
Keep notes on why certain assets are correlated and what might change that relationship
4. Integration with Other Analysis
Fundamental Analysis:
Combine correlation analysis with fundamental factors
Technical Analysis:
Use correlation analysis alongside technical indicators
Market Context:
Consider how market conditions might affect correlations
Conclusion
This Scientific Correlation Testing Framework provides a comprehensive tool for analyzing relationships between financial assets. By offering both Pearson and Spearman correlation methods, statistical significance testing, and rolling correlation analysis, it goes beyond simple correlation measures to provide deeper insights.
For beginners, this script might seem complex, but it's built on fundamental statistical concepts that become clearer with use. Start with the default settings and focus on interpreting the main correlation lines and the statistics table. As you become more comfortable, you can adjust the parameters and explore more advanced applications.
Remember that correlation analysis is just one tool in a trader's toolkit. It should be used in conjunction with other forms of analysis and with a clear understanding of its limitations. When used properly, it can provide valuable insights for portfolio construction, risk management, and pair trading strategy development.
LibWghtLibrary "LibWght"
This is a library of mathematical and statistical functions
designed for quantitative analysis in Pine Script. Its core
principle is the integration of a custom weighting series
(e.g., volume) into a wide array of standard technical
analysis calculations.
Key Capabilities:
1. **Universal Weighting:** All exported functions accept a `weight`
parameter. This allows standard calculations (like moving
averages, RSI, and standard deviation) to be influenced by an
external data series, such as volume or tick count.
2. **Weighted Averages and Indicators:** Includes a comprehensive
collection of weighted functions:
- **Moving Averages:** `wSma`, `wEma`, `wWma`, `wRma` (Wilder's),
`wHma` (Hull), and `wLSma` (Least Squares / Linear Regression).
- **Oscillators & Ranges:** `wRsi`, `wAtr` (Average True Range),
`wTr` (True Range), and `wR` (High-Low Range).
3. **Volatility Decomposition:** Provides functions to decompose
total variance into distinct components for market analysis.
- **Two-Way Decomposition (`wTotVar`):** Separates variance into
**between-bar** (directional) and **within-bar** (noise)
components.
- **Three-Way Decomposition (`wLRTotVar`):** Decomposes variance
relative to a linear regression into **Trend** (explained by
the LR slope), **Residual** (mean-reversion around the
LR line), and **Within-Bar** (noise) components.
- **Local Volatility (`wLRLocTotStdDev`):** Measures the total
"noise" (within-bar + residual) around the trend line.
4. **Weighted Statistics and Regression:** Provides a robust
function for Weighted Linear Regression (`wLinReg`) and a
full suite of related statistical measures:
- **Between-Bar Stats:** `wBtwVar`, `wBtwStdDev`, `wBtwStdErr`.
- **Residual Stats:** `wResVar`, `wResStdDev`, `wResStdErr`.
5. **Fallback Mechanism:** All functions are designed for reliability.
If the total weight over the lookback period is zero (e.g., in
a no-volume period), the algorithms automatically fall back to
their unweighted, uniform-weight equivalents (e.g., `wSma`
becomes a standard `ta.sma`), preventing errors and ensuring
continuous calculation.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
wSma(source, weight, length)
Weighted Simple Moving Average (linear kernel).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Linear-kernel weighted mean; falls back to
the arithmetic mean if Σweight = 0.
wEma(source, weight, length)
Weighted EMA (exponential kernel).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (simple int) : simple int Look-back length ≥ 1.
Returns: series float Exponential-kernel weighted mean; falls
back to classic EMA if Σweight = 0.
wWma(source, weight, length)
Weighted WMA (linear kernel).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Linear-kernel weighted mean; falls back to
classic WMA if Σweight = 0.
wRma(source, weight, length)
Weighted RMA (Wilder kernel, α = 1/len).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (simple int) : simple int Look-back length ≥ 1.
Returns: series float Wilder-kernel weighted mean; falls back to
classic RMA if Σweight = 0.
wHma(source, weight, length)
Weighted HMA (linear kernel).
Parameters:
source (float) : series float Data to average.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Linear-kernel weighted mean; falls back to
classic HMA if Σweight = 0.
wRsi(source, weight, length)
Weighted Relative Strength Index.
Parameters:
source (float) : series float Price series.
weight (float) : series float Weight series.
length (simple int) : simple int Look-back length ≥ 1.
Returns: series float Weighted RSI; uniform if Σw = 0.
wAtr(tr, weight, length)
Weighted ATR (Average True Range).
Implemented as WRMA on *true range*.
Parameters:
tr (float) : series float True Range series.
weight (float) : series float Weight series.
length (simple int) : simple int Look-back length ≥ 1.
Returns: series float Weighted ATR; uniform weights if Σw = 0.
wTr(tr, weight, length)
Weighted True Range over a window.
Parameters:
tr (float) : series float True Range series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Weighted mean of TR; uniform if Σw = 0.
wR(r, weight, length)
Weighted High-Low Range over a window.
Parameters:
r (float) : series float High-Low per bar.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 1.
Returns: series float Weighted mean of range; uniform if Σw = 0.
wBtwVar(source, weight, length, biased)
Weighted Between Variance (biased/unbiased).
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns:
variance series float The calculated between-bar variance (σ²btw), either biased or unbiased.
sumW series float The sum of weights over the lookback period (Σw).
sumW2 series float The sum of squared weights over the lookback period (Σw²).
wBtwStdDev(source, weight, length, biased)
Weighted Between Standard Deviation.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float σbtw uniform if Σw = 0.
wBtwStdErr(source, weight, length, biased)
Weighted Between Standard Error.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float √(σ²btw / N_eff) uniform if Σw = 0.
wTotVar(mu, sigma, weight, length, biased)
Weighted Total Variance (= between-group + within-group).
Useful when each bar represents an aggregate with its own
mean* and pre-estimated σ (e.g., second-level ranges inside a
1-minute bar). Assumes the *weight* series applies to both the
group means and their σ estimates.
Parameters:
mu (float) : series float Group means (e.g., HL2 of 1-second bars).
sigma (float) : series float Pre-estimated σ of each group (same basis).
weight (float) : series float Weight series (volume, ticks, …).
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns:
varBtw series float The between-bar variance component (σ²btw).
varWtn series float The within-bar variance component (σ²wtn).
sumW series float The sum of weights over the lookback period (Σw).
sumW2 series float The sum of squared weights over the lookback period (Σw²).
wTotStdDev(mu, sigma, weight, length, biased)
Weighted Total Standard Deviation.
Parameters:
mu (float) : series float Group means (e.g., HL2 of 1-second bars).
sigma (float) : series float Pre-estimated σ of each group (same basis).
weight (float) : series float Weight series (volume, ticks, …).
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float σtot.
wTotStdErr(mu, sigma, weight, length, biased)
Weighted Total Standard Error.
SE = √( total variance / N_eff ) with the same effective sample
size logic as `wster()`.
Parameters:
mu (float) : series float Group means (e.g., HL2 of 1-second bars).
sigma (float) : series float Pre-estimated σ of each group (same basis).
weight (float) : series float Weight series (volume, ticks, …).
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float √(σ²tot / N_eff).
wLinReg(source, weight, length)
Weighted Linear Regression.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
Returns:
mid series float The estimated value of the regression line at the most recent bar.
slope series float The slope of the regression line.
intercept series float The intercept of the regression line.
wResVar(source, weight, midLine, slope, length, biased)
Weighted Residual Variance.
linear regression – optionally biased (population) or
unbiased (sample).
Parameters:
source (float) : series float Data series.
weight (float) : series float Weighting series (volume, etc.).
midLine (float) : series float Regression value at the last bar.
slope (float) : series float Slope per bar.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population variance (σ²_P), denominator ≈ N_eff.
false → sample variance (σ²_S), denominator ≈ N_eff - 2.
(Adjusts for 2 degrees of freedom lost to the regression).
Returns:
variance series float The calculated residual variance (σ²res), either biased or unbiased.
sumW series float The sum of weights over the lookback period (Σw).
sumW2 series float The sum of squared weights over the lookback period (Σw²).
wResStdDev(source, weight, midLine, slope, length, biased)
Weighted Residual Standard Deviation.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
midLine (float) : series float Regression value at the last bar.
slope (float) : series float Slope per bar.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float σres; uniform if Σw = 0.
wResStdErr(source, weight, midLine, slope, length, biased)
Weighted Residual Standard Error.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
midLine (float) : series float Regression value at the last bar.
slope (float) : series float Slope per bar.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population (biased); false → sample.
Returns: series float √(σ²res / N_eff); uniform if Σw = 0.
wLRTotVar(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Total Variance **around the
window’s weighted mean μ**.
σ²_tot = E_w ⟶ *within-group variance*
+ Var_w ⟶ *residual variance*
+ Var_w ⟶ *trend variance*
where each bar i in the look-back window contributes
m_i = *mean* (e.g. 1-sec HL2)
σ_i = *sigma* (pre-estimated intrabar σ)
w_i = *weight* (volume, ticks, …)
ŷ_i = b₀ + b₁·x (value of the weighted LR line)
r_i = m_i − ŷ_i (orthogonal residual)
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns:
varRes series float The residual variance component (σ²res).
varWtn series float The within-bar variance component (σ²wtn).
varTrd series float The trend variance component (σ²trd), explained by the linear regression.
sumW series float The sum of weights over the lookback period (Σw).
sumW2 series float The sum of squared weights over the lookback period (Σw²).
wLRTotStdDev(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Total Standard Deviation.
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns: series float √(σ²tot).
wLRTotStdErr(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Total Standard Error.
SE = √( σ²_tot / N_eff ) with N_eff = Σw² / Σw² (like in wster()).
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns: series float √((σ²res, σ²wtn, σ²trd) / N_eff).
wLRLocTotStdDev(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Local Total Standard Deviation.
Measures the total "noise" (within-bar + residual) around the trend.
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns: series float √(σ²wtn + σ²res).
wLRLocTotStdErr(mu, sigma, weight, midLine, slope, length, biased)
Weighted Linear-Regression Local Total Standard Error.
Parameters:
mu (float) : series float Per-bar mean m_i.
sigma (float) : series float Pre-estimated σ_i of each bar.
weight (float) : series float Weight series w_i (≥ 0).
midLine (float) : series float Regression value at the latest bar (ŷₙ₋₁).
slope (float) : series float Slope b₁ of the regression line.
length (int) : series int Look-back length ≥ 2.
biased (bool) : series bool true → population; false → sample.
Returns: series float √((σ²wtn + σ²res) / N_eff).
wLSma(source, weight, length)
Weighted Least Square Moving Average.
Parameters:
source (float) : series float Data series.
weight (float) : series float Weight series.
length (int) : series int Look-back length ≥ 2.
Returns: series float Least square weighted mean. Falls back
to unweighted regression if Σw = 0.
sensex 9-18-50 + VWAP (VWAP-close confirmation)Description:
This script plots EMA 9, 18, and 50 along with VWAP to identify directional bias in Sensex. A buy or sell signal is generated only when all three EMAs align in sequence and a confirmed 7-minute candle closes above or below the VWAP, helping filter trades with institutional bias confirmation.
Mirpapa_Lib_boxLibrary "Mirpapa_Lib_box"
AddFVG(boxes, htfTimeframe, htfBarIndex, top, bottom, isBull, _text)
AddFVG
@description FVG 박스 데이터 추가
Parameters:
boxes (array) : array 박스 배열
htfTimeframe (string) : string HTF 시간대 ("60", "240", "D")
htfBarIndex (int) : int HTF bar_index
top (float) : float 상단 가격
bottom (float) : float 하단 가격
isBull (bool) : bool 방향 (true=상승, false=하락)
_text (string)
Returns: void
AddOB(boxes, htfTimeframe, htfBarIndex, top, bottom, isBull, _text)
AddOB
@description OB 박스 데이터 추가
Parameters:
boxes (array) : array 박스 배열
htfTimeframe (string) : string HTF 시간대
htfBarIndex (int) : int HTF bar_index
top (float) : float 상단 가격
bottom (float) : float 하단 가격
isBull (bool) : bool 방향
_text (string)
Returns: void
AddBB(boxes, htfTimeframe, htfBarIndex, top, bottom, isBull, _text)
AddBB
@description BB 박스 데이터 추가
Parameters:
boxes (array) : array 박스 배열
htfTimeframe (string) : string HTF 시간대
htfBarIndex (int) : int HTF bar_index
top (float) : float 상단 가격
bottom (float) : float 하단 가격
isBull (bool) : bool 방향
_text (string)
Returns: void
AddRB(boxes, htfTimeframe, htfBarIndex, top, bottom, isBull, _text)
AddRB
@description RB 박스 데이터 추가
Parameters:
boxes (array) : array 박스 배열
htfTimeframe (string) : string HTF 시간대
htfBarIndex (int) : int HTF bar_index
top (float) : float 상단 가격
bottom (float) : float 하단 가격
isBull (bool) : bool 방향
_text (string)
Returns: void
ProcessBoxes(boxes, boxType, colorBull, colorBear, closeCount, useLine, textAlignH, textAlignV, closeColor)
ProcessBoxes
@description 박스 배열 처리 (생성→확장→터치→종료)
Parameters:
boxes (array) : array 박스 배열
boxType (string) : string 박스 타입 ("FVG", "OB", "BB", "RB")
colorBull (color) : color 상승 색상
colorBear (color) : color 하락 색상
closeCount (int) : int 터치 종료 횟수
useLine (bool) : bool 중간라인 사용 여부
textAlignH (string) : string 수평 정렬
textAlignV (string) : string 수직 정렬
closeColor (color) : color 종료 색상
Returns: void
GetActiveBoxCount(boxes)
GetActiveBoxCount
@description 활성 박스 개수 반환
Parameters:
boxes (array) : array 박스 배열
Returns: int 활성 박스 개수
ClearInactiveBoxes(boxes)
ClearInactiveBoxes
@description 비활성 박스 제거 (메모리 절약)
Parameters:
boxes (array) : array 박스 배열
Returns: void
BoxData
BoxData
Fields:
_isActive (series bool) : 박스 활성화 상태
_isBull (series bool) : 방향 (true=상승, false=하락)
_boxTop (series float) : 상단 가격
_boxBot (series float) : 하단 가격
_basePoint (series float) : 터치 감지 기준점
_stage (series int) : 터치 횟수 카운터
_type (series string) : 박스 타입 ("FVG", "OB", "BB", "RB")
_htfTimeframe (series string) : HTF 시간대 ("60", "240", "D")
_htfBarIndex (series int) : HTF 기준 bar_index
_text (series string) : 사용자 추가 텍스트
_box (series box) : 박스 객체 (ProcessBoxes에서 생성)
_line (series line) : 라인 객체 (ProcessBoxes에서 생성)
Info Box⚙️ Purpose
Shows useful trade and event-related data such as:
% Distance from stop levels (D, DH)
Earnings countdown in bars
All displayed in a single floating info box (table) on the chart.
📋 Key Features
Customizable Display
Choose table position (Top Right, Bottom Center, etc.)
Choose table size (Auto, Large, Tiny, etc.)
Custom text and background colors
Metrics Shown
D: % Distance from stop (difference between close and low/high)
DH: % Distance from midpoint of the candle
Earnings Countdown: Number of bars until next earnings event
Conditional Styling
If earnings are within 3 bars, text color turns red as a warning.
Execution Conditions
Runs only on daily timeframe
Updates on last bar only (no historical clutter)
Output
Displays all selected metrics in one line, separated by “×”
e.g. → D: -2.1% × 5 × DH: 1.4%
🧩 Overall Function
Creates a clean, customizable “info box” showing trade distances and upcoming earnings countdown for quick decision-making directly on your TradingView chart.
Nqaba Goldminer StrategyThis indicator plots the New York session key timing levels used in institutional intraday models.
It automatically marks the 03:00 AM, 10:00 AM, and 2:00 PM (14:00) New York times each day:
Vertical lines show exactly when those time windows open — allowing traders to identify major global liquidity shifts between London, New York, and U.S. session overlaps.
Horizontal lines mark the opening price of the 5-minute candle that begins at each of those key times, providing precision reference levels for potential reversals, continuation setups, and intraday bias shifts.
Users can customize each line’s color, style (solid/dashed/dotted), width, and horizontal-line length.
A history toggle lets you display all past occurrences or just today’s key levels for a cleaner chart.
These reference levels form the foundation for strategies such as:
London Breakout to New York Reversal models
Opening Range / Session Open bias confirmation
Institutional volume transfer windows (London → NY → Asia)
The tool provides a simple visual structure for traders to frame intraday decision-making around recurring institutional time events.
Percentile Rank Oscillator (Price + VWMA)A statistical oscillator designed to identify potential market turning points using percentile-based price analytics and volume-weighted confirmation.
What is PRO?
Percentile Rank Oscillator measures how extreme current price behavior is relative to its own recent history. It calculates a rolling percentile rank of price midpoints and VWMA deviation (volume-weighted price drift). When price reaches historically rare levels – high or low percentiles – it may signal exhaustion and potential reversal conditions.
How it works
Takes midpoint of each candle ((H+L)/2)
Ranks the current value vs previous N bars using rolling percentile rank
Maps percentile to a normalized oscillator scale (-1..+1 or 0–100)
Optionally evaluates VWMA deviation percentile for volume-confirmed signals
Highlights extreme conditions and confluence zones
Why percentile rank?
Median-based percentiles ignore outliers and read the market statistically – not by fixed thresholds. Instead of guessing “overbought/oversold” values, the indicator adapts to current volatility and structure.
Key features
Rolling percentile rank of price action
Optional VWMA-based percentile confirmation
Adaptive, noise-robust structure
User-selectable thresholds (default 95/5)
Confluence highlighting for price + VWMA extremes
Optional smoothing (RMA)
Visual extreme zone fills for rapid signal recognition
How to use
High percentile values –> statistically extreme upward deviation (potential top)
Low percentile values –> statistically extreme downward deviation (potential bottom)
Price + VWMA confluence strengthens reversal context
Best used as part of a broader trading framework (market structure, order flow, etc.)
Tip: Look for percentile spikes at key HTF levels, after extended moves, or where liquidity sweeps occur. Strong moves into rare percentile territory may precede mean reversion.
Suggested settings
Default length: 100 bars
Thresholds: 95 / 5
Smoothing: 1–3 (optional)
Important note
This tool does not predict direction or guarantee outcomes. It provides statistical context for price extremes to help traders frame probability and timing. Always combine with sound risk management and other tools.
Multi-Mode Seasonality Map [BackQuant]Multi-Mode Seasonality Map
A fast, visual way to expose repeatable calendar patterns in returns, volatility, volume, and range across multiple granularities (Day of Week, Day of Month, Hour of Day, Week of Month). Built for idea generation, regime context, and execution timing.
What is “seasonality” in markets?
Seasonality refers to statistically repeatable patterns tied to the calendar or clock, rather than to price levels. Examples include specific weekdays tending to be stronger, certain hours showing higher realized volatility, or month-end flow boosting volumes. This tool measures those effects directly on your charted symbol.
Why seasonality matters
It’s orthogonal alpha: timing edges independent of price structure that can complement trend, mean reversion, or flow-based setups.
It frames expectations: when a session typically runs hot or cold, you size and pace risk accordingly.
It improves execution: entering during historically favorable windows, avoiding historically noisy windows.
It clarifies context: separating normal “calendar noise” from true anomaly helps avoid overreacting to routine moves.
How traders use seasonality in practice
Timing entries/exits : If Tuesday morning is historically weak for this asset, a mean-reversion buyer may wait for that drift to complete before entering.
Sizing & stops : If 13:00–15:00 shows elevated volatility, widen stops or reduce size to maintain constant risk.
Session playbooks : Build repeatable routines around the hours/days that consistently drive PnL.
Portfolio rotation : Compare seasonal edges across assets to schedule focus and deploy attention where the calendar favors you.
Why Day-of-Week (DOW) can be especially helpful
Flows cluster by weekday (ETF creations/redemptions, options hedging cadence, futures roll patterns, macro data releases), so DOW often encodes a stable micro-structure signal.
Desk behavior and liquidity provision differ by weekday, impacting realized range and slippage.
DOW is simple to operationalize: easy rules like “fade Monday afternoon chop” or “press Thursday trend extension” can be tested and enforced.
What this indicator does
Multi-mode heatmaps : Switch between Day of Week, Day of Month, Hour of Day, Week of Month .
Metric selection : Analyze Returns , Volatility ((high-low)/open), Volume (vs 20-bar average), or Range (vs 20-bar average).
Confidence intervals : Per cell, compute mean, standard deviation, and a z-based CI at your chosen confidence level.
Sample guards : Enforce a minimum sample size so thin data doesn’t mislead.
Readable map : Color palettes, value labels, sample size, and an optional legend for fast interpretation.
Scoreboard : Optional table highlights best/worst DOW and today’s seasonality with CI and a simple “edge” tag.
How it’s calculated (under the hood)
Per bar, compute the chosen metric (return, vol, volume %, or range %) over your lookback window.
Bucket that metric into the active calendar bin (e.g., Tuesday, the 15th, 10:00 hour, or Week-2 of month).
For each bin, accumulate sum , sum of squares , and count , then at render compute mean , std dev , and confidence interval .
Color scale normalizes to the observed min/max of eligible bins (those meeting the minimum sample size).
How to read the heatmap
Color : Greener/warmer typically implies higher mean value for the chosen metric; cooler implies lower.
Value label : The center number is the bin’s mean (e.g., average % return for Tuesdays).
Confidence bracket : Optional “ ” shows the CI for the mean, helping you gauge stability.
n = sample size : More samples = more reliability. Treat small-n bins with skepticism.
Suggested workflows
Pick the lens : Start with Analysis Type = Returns , Heatmap View = Day of Week , lookback ≈ 252 trading days . Note the best/worst weekdays and their CI width.
Sanity-check volatility : Switch to Volatility to see which bins carry the most realized range. Use that to plan stop width and trade pacing.
Check liquidity proxy : Flip to Volume , identify thin vs thick windows. Execute risk in thicker windows to reduce slippage.
Drill to intraday : Use Hour of Day to reveal opening bursts, lunchtime lulls, and closing ramps. Combine with your main strategy to schedule entries.
Calendar nuance : Inspect Week of Month and Day of Month for end-of-month, options-cycle, or data-release effects.
Codify rules : Translate stable edges into rules like “no fresh risk during bottom-quartile hours” or “scale entries during top-quartile hours.”
Parameter guidance
Analysis Period (Days) : 252 for a one-year view. Shorten (100–150) to emphasize the current regime; lengthen (500+) for long-memory effects.
Heatmap View : Start with DOW for robustness, then refine with Hour-of-Day for your execution window.
Confidence Level : 95% is standard; use 90% if you want wider coverage with fewer false “insufficient data” bins.
Min Sample Size : 10–20 helps filter noise. For Hour-of-Day on higher timeframes, consider lowering if your dataset is small.
Color Scheme : Choose a palette with good mid-tone contrast (e.g., Red-Green or Viridis) for quick thresholding.
Interpreting common patterns
Return-positive but low-vol bins : Favorable drift windows for passive adds or tight-stop trend continuation.
Return-flat but high-vol bins : Opportunity for mean reversion or breakout scalping, but manage risk accordingly.
High-volume bins : Better expected execution quality; schedule size here if slippage matters.
Wide CI : Edge is unstable or sample is thin; treat as exploratory until more data accumulates.
Best practices
Revalidate after regime shifts (new macro cycle, liquidity regime change, major exchange microstructure updates).
Use multiple lenses: DOW to find the day, then Hour-of-Day to refine the entry window.
Combine with your core setup signals; treat seasonality as a filter or weight, not a standalone trigger.
Test across assets/timeframes—edges are instrument-specific and may not transfer 1:1.
Limitations & notes
History-dependent: short histories or sparse intraday data reduce reliability.
Not causal: a hot Tuesday doesn’t guarantee future Tuesday strength; treat as probabilistic bias.
Aggregation bias: changing session hours or symbol migrations can distort older samples.
CI is z-approximate: good for fast triage, not a substitute for full hypothesis testing.
Quick setup
Use Returns + Day of Week + 252d to get a clean yearly map of weekday edge.
Flip to Hour of Day on intraday charts to schedule precise entries/exits.
Keep Show Values and Confidence Intervals on while you calibrate; hide later for a clean visual.
The Multi-Mode Seasonality Map helps you convert the calendar from an afterthought into a quantitative edge, surfacing when an asset tends to move, expand, or stay quiet—so you can plan, size, and execute with intent.
Mirpapa_Lib_DivergenceLibrary "Mirpapa_Lib_Divergence"
다이버전스 감지 및 시각화 라이브러리 (범용 설계)
newPivot(bar, priceVal, indVal)
피벗 포인트 생성
Parameters:
bar (int) : 바 인덱스
priceVal (float) : 가격
indVal (float) : 지표값
Returns: PivotPoint
newDivSettings(pivotLen, maxStore, maxShow)
다이버전스 설정 생성
Parameters:
pivotLen (int) : 피벗 좌우 캔들
maxStore (int) : 저장 개수
maxShow (int) : 표시 라인 개수
Returns: DivergenceSettings
emptyDivResult()
빈 다이버전스 결과
Returns: 감지 안 된 DivergenceResult
checkPivotHigh(length, source)
고점 피벗 감지
Parameters:
length (int) : 좌우 비교 캔들 수
source (float) : 비교할 데이터 (지표값)
Returns: 피벗 값 또는 na
checkPivotLow(length, source)
저점 피벗 감지
Parameters:
length (int) : 좌우 비교 캔들 수
source (float) : 비교할 데이터 (지표값)
Returns: 피벗 값 또는 na
addPivotToArray(pivotArray, pivot, maxSize)
피벗을 배열에 추가 (FIFO 방식)
Parameters:
pivotArray (array) : 피벗 배열
pivot (PivotPoint) : 추가할 피벗
maxSize (int) : 최대 크기
checkBullishDivergence(pivotArray)
상승 다이버전스 체크 (Bullish)
Parameters:
pivotArray (array) : 저점 피벗 배열
Returns: DivergenceResult
checkBearishDivergence(pivotArray)
하락 다이버전스 체크 (Bearish)
Parameters:
pivotArray (array) : 고점 피벗 배열
Returns: DivergenceResult
createDivLine(result, lineColor, isOverlay)
다이버전스 라인 생성
Parameters:
result (DivergenceResult) : DivergenceResult
lineColor (color) : 라인 색상
isOverlay (bool) : true면 가격 기준, false면 지표 기준
Returns:
cleanupLines(lineArray, labelArray, maxLines)
오래된 라인/라벨 정리
Parameters:
lineArray (array) : 라인 배열
labelArray (array) : 라벨 배열
maxLines (int) : 최대 유지 개수
addLineAndCleanup(lineArray, labelArray, newLine, newLabel, maxLines)
라인/라벨 추가 및 자동 정리
Parameters:
lineArray (array) : 라인 배열
labelArray (array) : 라벨 배열
newLine (line) : 새 라인
newLabel (label) : 새 라벨
maxLines (int) : 최대 개수
PivotPoint
피벗 데이터 저장
Fields:
barIndex (series int) : 바 인덱스
price (series float) : 종가
indicatorValue (series float) : 지표값
DivergenceSettings
다이버전스 설정
Fields:
pivotLength (series int) : 피벗 좌우 캔들 수
maxPivotsStore (series int) : 저장할 최대 피벗 개수
maxLinesShow (series int) : 표시할 최대 라인 개수
DivergenceResult
다이버전스 감지 결과
Fields:
detected (series bool) : 다이버전스 감지 여부
isBullish (series bool) : true면 상승, false면 하락
bar1 (series int) : 첫 번째 피벗 바 인덱스
value1_price (series float) : 첫 번째 가격
value1_ind (series float) : 첫 번째 지표값
bar2 (series int) : 두 번째 피벗 바 인덱스
value2_price (series float) : 두 번째 가격
value2_ind (series float) : 두 번째 지표값
Market SessionsMarket Sessions (Asian, London, NY, Pacific)
Summary
This indicator plots the main global market sessions (Asian, European, American, Pacific) as boxes on your chart, complete with dynamic high/low tracking.
It's an essential tool for intraday traders to track session-based volatility patterns and visualize key support/resistance levels (like the Asian Range) that often define price action for the rest of the day.
Who it’s for
Intraday traders, scalpers, and day traders who need to visualize market hours and session-based ranges. If your strategy depends on the London open, the New York close, or the Asian range, this script will map it out for you.
What it shows
Customizable Session Boxes: Four fully configurable boxes for the Asian, European (London), American (New York), and Pacific (Sydney) sessions.
Session High & Low: The script tracks and boxes the highest high and lowest low of each session, dynamically updating as the session progresses.
Session Labels: Clear labels (e.g., "AS", "EU") mark each session, anchored to the start time.
Key Features
Powerful Timezone Control: This is the core feature.
Use Exchange Timezone (Default): Simply enter session times (e.g., 8:00 for London) relative to the exchange's timezone (e.g., "NASDAQ" or "BINANCE").
Use UTC Offset: Uncheck the box and enter a UTC offset (e.g., +3 or -5). Now, all session times you enter are relative to that specific UTC offset. This gives you full control regardless of the chart you're on.
Fully Customizable: Toggle any session on/off.
Style Control: Change the fill color, border color, transparency, border width, and line style (Solid, Dashed, Dotted) for each session individually.
Smart Labels: Labels stay anchored to the start of the session (no "sliding") and float just above the session high.
Why this helps
Track Volatility & Market Behavior: Visually identify the "personality" of each session. Some sessions might consistently produce powerful pumps or dumps, while others are prone to sideways "chop" or accumulation. This indicator helps you see these repeating patterns.
Find Key Support/Resistance Levels: The High and Low of a session (e.g., the Asian Range) often become critical support and resistance levels for the next session (e.g., London). This script makes it easy to spot these "session-to-session" S/R flips and reactions.
Aid Statistical Analysis: The script provides the core visual data for your statistical research. You can easily track how often the London session breaks the Asian high, or which session is most likely to reverse the trend, helping you build a robust trading plan.
Context is King: Instantly see which market is active, which are overlapping (like the high-volume London-NY overlap), and which have closed.
Quick setup
Go to Timezone Settings.
Decide how you want to enter times:
Easy (Default): Leave Use Exchange Timezone checked. Enter session times based on the chart's native exchange (e.g., for BTC/USDT on Binance, use UTC+0 times).
Manual (Pro): Uncheck Use Exchange Timezone. Enter your UTC Offset (e.g., +2 for Berlin). Now, enter all session times as they appear on the clock in Berlin.
Go to each session tab (Asian, European...) to enable/disable it and set the correct start/end hours and minutes.
Style the colors to match your chart theme.
Disclaimer
For educational/informational purposes only; not financial advice. Trading involves risk—manage it responsibly.
Mirpapa_Lib_MACDLibrary "Mirpapa_Lib_MACD"
MACD 계산 및 크로스 체크를 위한 라이브러리
calc_smma(src, len)
SMMA (Smoothed Moving Average) 계산
Parameters:
src (float) : 소스 데이터
len (simple int) : 길이
Returns: SMMA 값
calc_zlema(src, length)
ZLEMA (Zero Lag EMA) 계산
Parameters:
src (float) : 소스 데이터
length (simple int) : 길이
Returns: ZLEMA 값
checkMacdCross(lengthMA, lengthSignal, src, enabled)
MACD 크로스오버 체크
Parameters:
lengthMA (simple int) : MACD 길이
lengthSignal (int) : 시그널 길이
src (float) : 소스 (기본값: hlc3)
enabled (bool) : 계산 활성화 여부 (기본값: true)
Returns:
NFCI National Financial Conditions IndexChicago Fed National Financial Conditions Index (NFCI)
This indicator plots the Chicago Fed’s National Financial Conditions Index (NFCI).
The NFCI updates weekly, and its latest value is displayed across all chart intervals.
The NFCI measures how tight or loose overall U.S. financial conditions are. It combines over 100 weekly indicators from the money, bond, and equity markets—along with credit and leverage data—into a single composite index.
The NFCI has three key subcomponents, each of which can be independently selected within the indicator:
Risk: Captures volatility, credit spreads, and overall market stress.
Credit: Tracks how easy or difficult it is to borrow across households and businesses.
Leverage: Reflects the level of debt and balance-sheet strength in the financial system.
When the NFCI rises, financial conditions are tightening — liquidity is contracting, borrowing costs are climbing, and investors tend to reduce risk.
When the NFCI falls, conditions are loosening — liquidity expands, credit flows more freely, and markets generally become more risk-seeking.
Traders often use the NFCI as a macro backdrop for risk appetite: rising values signal growing stress and defensive positioning, while falling values indicate improving liquidity and a more supportive market environment.
Rolling Correlation vs Another Symbol (SPY Default)This indicator visualizes the rolling correlation between the current chart symbol and another selected asset, helping traders understand how closely the two move together over time.
It calculates the Pearson correlation coefficient over a user-defined period (default 22 bars) and plots it as a color-coded line:
• Green line → positive correlation (move in the same direction)
• Red line → negative correlation (move in opposite directions)
• A gray dashed line marks the zero level (no correlation).
The background highlights periods of strong relationship:
• Light green when correlation > +0.7 (strong positive)
• Light red when correlation < –0.7 (strong negative)
Use this tool to quickly spot diversification opportunities, confirm hedges, or understand how assets interact during different market regimes.






















