Anchored LRL using ZigZag AnchorAnchored Linear Regression Channel - ZigZag Pivot
The Anchored Linear Regression Channel (LRL) dynamically anchors to the most recent ZigZag pivot point, providing traders with a regression-based channel that resets with each significant price swing.
HOW IT WORKS:
This indicator combines ZigZag pivot detection with linear regression analysis. When price reverses by a specified ATR multiple, a new pivot is identified. After a minimum number of bars, the linear regression channel anchors to this pivot and projects forward to the current bar, recalculating with each new bar.
KEY FEATURES:
- Dynamic anchoring to ZigZag highs and lows
- Customizable ATR-based reversal detection
- Two standard deviation channel bands (inner and outer)
- Adjustable minimum bars before anchor reset (ideal for scalping on lower timeframes)
- Separate controls for ZigZag smoothing vs. anchor reset timing
- Color-coded regression line (up/down trend)
- Optional line extension to the right
- Fully customizable colors and line widths
- Visual label marking the anchor pivot point
INPUTS:
- ATR Reversal: Multiplier for ATR-based pivot detection (default: 2.0)
- MA Length: EMA smoothing for ZigZag calculation (default: 5)
- ATR Length: Period for ATR calculation (default: 5)
- Min Bars After Pivot: Bars required before anchor resets (default: 3, reduce to 1-2 for faster scalping)
- Channel Widths: Inner (0.70) and Outer (1.00) standard deviation multiples
- Line Colors: Customizable colors for uptrend/downtrend and channel lines
- Label Colors: Customizable background and text colors
HOW TO USE:
1. Apply the indicator to your chart
2. Adjust "Min Bars After Pivot" based on your timeframe:
- 1-minute charts: Use 1-2 bars for quick scalping entries
- 5-minute+ charts: Use 3-5 bars for more confirmation
3. Watch for the regression line color to indicate trend direction
4. Use channel bands as potential support/resistance zones
5. The label shows which pivot (high/low) the channel is anchored to
BEST PRACTICES:
- Lower timeframes (1-5 min): Use lower "Min Bars After Pivot" (1-3) for faster reaction
- Higher timeframes: Use higher values (5+) for more confirmed pivots
- Combine with price action and volume for confirmation
- Adjust ATR Reversal based on instrument volatility
NOTES:
- This indicator repaints as it recalculates with each new bar
- Channel resets when a new ZigZag pivot is confirmed
- Not suitable for backtesting strategies due to dynamic nature
- Works best on liquid instruments with clear price swings
DISCLAIMER:
This indicator is for educational and informational purposes only. It does not provide trading signals or guarantees of profitability. Past performance is not indicative of future results. Always perform your own analysis and risk management.
Statistics
Multi-Symbol RSI Portfolio Simulator [Honestcowboy]The Multi-Symbol RSI Portfolio Simulator was build to test a theory, does the RSI indicator work in FOREX assets. Does it have predictive power. In this example the security function is used to fetch data for 40 different Forex pairs and it executes a very simple trading strategy. Sell when RSI hits 80, flatten if back below. Buy when RSI hits 20, flatten if back above. All executed on bar closes so no intra bar stuff.
🟦 🟦 🟦 Very Important Disclaimer
This is a very crude indicator which does not calculate trading costs and assumes perfect execution of trades with zero slippage. Forex markets carry high risk and most CFD brokers ask high spreads and trading costs so this approach will most likely only work on the H4 or above Daily charts. We are observing market behaviour here, it's a study of price action not an executable ready strategy. Do your own cost analysis, simulation if you want to take this idea further.
🟦 What is the point?
I build this indicator to prove that RSI indeed causes price action reactions especially on the intraday level in forex. Just like any study or paper not accounting for trading costs, this is just hypothetical and a starting point.
🟦 CALCULATION
On each bar close it will check RSI value for each pair in the list. If one of the pairs meets the condition for a long or short it will open that trade on next bar open and hold it till close. Add the profits/losses to the equity line. And if condition still true on next bar do it again, this is a very crude simple form of testing. Tradingview strategy tester is superior but does not allow for multi-pair trading.
Short Condition: RSI above 80
Short Exit: RSI below 70
Long Condition: RSI below 20
Long Exit: RSI above 30
The indicator also has 2 modes: Mean reversion and Trend mode. On default it uses Mean Reversion which is explained above. Trend mode does the exact opposite, so long above 80 short below 20.
I've also included a table with a heatmap showing all the trading pairs the indicator uses, it's current RSI value and color based on how close indicator is to shorting or longing it from green to red with gray being middle so no direction.
🟦 USE CASES
You can tweak the setting for different RSI values. Different RSI lengths and also freely change any trading pair inside the list to make your own test. I'm including some screenshots of tests here below:
The Charlie Method - EnhancedThe Charlie Method is a precision-engineered 15-minute confirmation tool built for disciplined traders who wait for price to come to them.
It identifies only true bullish and bearish engulfing candles, visually marking them at the moment of confirmation and delivering immediate alerts.
No repainting. No noise. No distractions.
This method is best applied at key levels, liquidity zones, and session extremes, where confirmation matters most.
Trade less. Confirm more. Execute with intent.
SPY Options Targets -IV Expected MoveWhat this indicator is?
This tool turns option implied volatility into two things:
1) Expected move levels on the SPY chart for a chosen time horizon
2) Estimated option premium targets if SPY reaches those levels
It is built to answer three trading questions:
1) How far can SPY reasonably move in my holding window
2) What SPY levels should I use for profit targets or invalidation
3) If SPY hits those levels, what option price is a realistic target
What the bands mean on the SPY chart
The bands are expected move levels on the underlying, recalculated each bar from the selected option’s implied volatility.
One sigma band
The teal band is the expected one standard deviation move over the next Horizon minutes. In practice, this is a normal move zone for that holding window.
Two sigma band
The orange band is the expected two standard deviation move over the next Horizon minutes. In practice, this is a large move zone for that holding window.
How to interpret value
If price is near the middle of the bands, the market is behaving normally for that window.
If price approaches the one sigma band, the move is extended for that window.
If price approaches the two sigma band, the move is unusually large for that window and you should expect either strong continuation or sharp mean reversion depending on market context.
What the table means and how to use it
IV
Implied volatility solved from the selected option price. Higher IV widens the bands and increases option targets.
DTE
Days to expiry of the selected option. Near expiry options can change faster and IV can shift quickly.
H move 1 sigma
The projected one sigma SPY move in dollars for the selected Horizon minutes. This is the key number for planning.
Opt at plus 1 sigma and minus 1 sigma
If SPY reaches the one sigma upper band or the one sigma lower band, the indicator estimates what your selected option should be worth at that moment, assuming implied volatility does not change.
Opt at plus 2 sigma and minus 2 sigma
Same idea for the two sigma bands.
Now opt px
Current option price for reference.
.................................................................................................................
How to trade using it?
Step 1 Pick the right option input
Choose the same expiry you plan to trade and pick a liquid contract, ideally at the money or near the money. This makes the IV reading more representative of the current tape.
Step 2 Set the horizon to your holding time
If you typically hold 15 to 30 minutes, set Horizon minutes to 15 or 30.
If you typically hold 60 to 120 minutes, set it accordingly.
This matters because the bands represent expected move for that exact window.
Step 3 Use the bands to define trade planning
For a long bias
Entry is your setup. The bands are used for targets and risk.
Target 1 is the one sigma upper band.
Target 2 is the two sigma upper band if momentum supports continuation.
Invalidation can be defined as losing the mid zone and failing to reclaim, or a clear level based stop. The indicator does not choose your stop. It gives your realistic upside distance.
For a short bias
Target 1 is the one sigma lower band.
Target 2 is the two sigma lower band if momentum supports continuation.
Invalidation can be defined similarly using your structure.
Step 4 Use the option targets as profit taking levels
Once you enter an option trade, ignore random premium swings and anchor to the table.
Common approach
Take partial profit when the option approaches the plus or minus one sigma target value.
Hold a smaller runner for the plus or minus two sigma target value.
If SPY hits the one sigma band but the option is far below the table target, it usually means implied volatility is dropping. Reduce expectations or exit earlier.
If SPY hits the one sigma band and the option is above the table target, it usually means implied volatility expanded. Consider taking profits sooner because this extra premium can mean revert.
Step 5 Use it to choose strikes
Before entering, check whether your desired option profit requires SPY to travel to the two sigma band within your horizon.
If yes, that is a lower probability trade for that window.
If your plan is achievable around the one sigma band, it is typically more realistic.
..................................................................................................................
Practical examples
Scalp example
Horizon 30 minutes.
If H move 1 sigma is about 1 dollar, then expecting a 3 dollar SPY move in 30 minutes is a two to three sigma expectation and should be treated as a low probability scalp unless a news event is active.
Intraday example
Horizon 120 minutes.
If H move 1 sigma is about 2 dollars, a 2 dollar move is a reasonable target and a 4 dollar move is the stretch target.
Important limitations
Implied volatility changes
The option target prices assume IV stays constant. In real markets IV can change during the move, especially on 0DTE, around news, or during sharp selloffs. Treat option targets as a baseline estimate.
Not a standalone signal
This indicator does not generate buy or sell signals. Combine it with your entry model, structure, or momentum confirmation.
Liquidity matters
Very wide bid ask spreads can distort the inferred IV. Use liquid contracts.
Suggested defaults for SPY
Use a liquid near the money option for the current expiry.
Horizon 30 for scalps, 60 for intraday, 120 for swings.
Keep expiry time at 16:00 New York.
Disclaimer
This script is for educational and informational purposes only and is not financial advice. Options involve risk and may not be suitable for all traders.
Dealer Control Index (DCI) Oscillator BreakoutsOverview
The Dealer Control Index (DCI) is a structural oscillator designed to measure market stability based on the relationship between price and key institutional "hedging levels" (Gamma Flip). Unlike momentum-based oscillators like RSI, the DCI focuses on Dealer Gamma Exposure—the point where market makers shift from supporting price (Long Gamma) to accelerating moves (Short Gamma).
How to Use
This indicator requires a Manual Anchor (Flip Level) to function with high precision. Users should identify the current institutional Gamma Flip level for their specific ticker and input it into the script settings.
Positive Score (+25 to +100): Price is above the Flip Level. Dealers are in a "Long Gamma" position, typically resulting in lower volatility and "dip-buying" behavior.
Neutral Zone (-75 to +25): The "Transition Zone." Price is fluctuating near the hedge-rebalancing point. Expect "choppy" price action.
The Gamma Trap (-75 to -100): Price has snapped significantly below the Flip Level. Dealers are now "Short Gamma" and may be forced to sell into further price drops to hedge their books, potentially creating a "Waterfall" effect.
Key Features
Volatility Normalized: Uses ATR-based normalization to ensure the -100 to +100 scale is consistent across different asset classes (e.g., comparing SPY to NVDA).
Sigmoid Smoothing: Employs a sigmoid curve to filter out "market noise" and provide a clear visual of when the regime shift is actually occurring.
Visual Regimes: Color-coded zones (Green/Red) provide instant feedback on the current dealer hedging bias.
StO Price Action - Panel US Economy DataShort Summary
- Displays selected us economic data as a time series graph
- Economic indicator name shown in the upper-right corner
- Designed as a lightweight fundamental context overlay
Full Description
Overview
- Plots economic macro data as a continuous graph
- Combines visual trend context with clear textual identification
Supported Economic Data
- CPI – Consumer Price Index
- CIR – Core Inflation Rate (YoY)
- IRYY – Inflation Rate (YoY)
- IJC – Initial Jobless Claims
- JC4W – Jobless Claims (4-Week Average)
- NFP – Nonfarm Payrolls
- UR – Unemployment Rate
Graph Behavior
- Selected economic series is rendered as a line graph
- Graph color is user-configurable
Label Display
- Full descriptive name of the selected indicator
- Fixed position in the upper-right corner
Usage
- Helps identify macro trends alongside price action
- Useful for bias alignment on higher timeframes
- Works well with Trend-following Systems or higher-timeframe structure analysis
Notes
- Economic data is informational and non-predictive
- Not a signal or timing tool
- Best used as contextual background not standalone input
Absorption Pro V4This indicator detects absorption-style reversal setups and scores them with a multi-factor model.
It builds key levels from ZigZag/Fibonacci and round numbers across multiple timeframes, then flags potential absorption candles using volume and a delta-proxy filter plus strict candle-structure rules. Signals are validated with trend context (MA/SMMA/EMA/ATR), VWAP positioning, and optional momentum/volatility filters (RSI, Stoch, CCI, MACD, ADX, Volume Profile). Only score-threshold crosses can trigger long/short markers and alerts (defaults tuned for NQ).
Duggan Capital ValueScript with lines for previous Vwaps.
GOD VIEW $$$$$$$$$$ WE ARE SHAKING VOL WHEN YOU SLEEP
Trailing Stoploss % BasedA minimalistic trend-following indicator that plots a single trailing line based on a user-defined percentage using price highs and lows.
The line:
Trails price in trends
Moves only in the direction of the trend
Flattens when price is not making new highs or lows
Acts as support in uptrends and resistance in downtrends
Useful on all instruments and all timeframes for clean trend tracking and trailing stop management.
Cash-and-Carry Yield (APR)This indicator calculates and visualizes the annualized rate of return for Cash-and-Carry arbitrage strategies by comparing a specific Futures contract against its underlying Spot price. By automatically projecting the current price spread (basis) based on the exact time remaining until expiration, it allows traders to instantly assess the potential "risk-free" yield available in the market.
The script is engineered to support both continuous 24/7 crypto markets and traditional CME futures. It features a smart "Gap Handling" setting that allows users to choose between a strict view that respects market closes (showing "Market Closed" during weekends) or a filled view that carries over the last known price for a seamless chart experience.
Visually, the indicator displays the annualized yield as a histogram; green columns indicate a Contango market (positive yield), while red columns signal Backwardation. A Simple Moving Average (SMA) is overlaid to help identify the broader yield trend amidst volatility. An integrated dashboard table in the corner provides a real-time summary of the Spot Price, Future Price, absolute spread, and the precise number of days left until expiration. Please ensure the Futures Ticker and the corresponding Expiration Date are correctly entered in the settings for accurate time-weighted calculations.
Volume Profile: Date-Range ObservationI have refined the strategy developed by kv4coins , incorporating an additional option for the observation date range. Previously, when seeking a fixed date range—particularly to track data from the onset of an event-driven trigger up to the present—it was somewhat cumbersome. To address this, I added a new date selection feature to accommodate the need for observing specific time periods.
USDC/USDT PremiumUSDC/USDT Premium Index
Overview
This indicator tracks the premium or discount of USD Coin (USDC) relative to Tether (USDT) using data from Binance. It serves as a barometer for sentiment within the stablecoin market. A premium on USDC often suggests a flight to quality or higher demand for a stablecoin perceived as more transparent and regulated.
Key Features
•
Premium Calculation: The premium is calculated as (USDC/USDT Price - 1) * 100 to represent the deviation from parity in basis points. For example, a value of 0.1 means USDC is trading at a 0.1% premium to USDT (i.e., a price of 1.001).
•
Dynamic Coloring: The indicator's line color changes based on its position relative to a moving average (MA):
•
Green: The premium is currently above its moving average, suggesting bullish momentum for USDC.
•
Red: The premium is below its moving average, indicating bearish momentum.
•
Zero Line: A zero line is plotted to clearly distinguish between a premium (above zero) and a discount (below zero).
•
Customizable MA: You can adjust the moving average period and type (SMA, EMA, etc.) to fine-tune the indicator's sensitivity.
How to Use
1.
Gauge Stablecoin Sentiment: A rising premium (green line) can indicate that traders are favoring USDC over USDT, which might happen during times of market uncertainty or concerns about USDT's reserves.
2.
Identify Shifts in Momentum: Look for the color to flip from red to green as a sign that the USDC premium is gaining strength. A flip from green to red may signal a weakening trend.
3.
Spot Extremes: Extreme deviations from the zero line can signal market stress or significant capital flows between the two major stablecoins.
Interpretation
•
Green Line (Premium > MA): Suggests that the short-term trend for the USDC premium is positive and strengthening.
•
Red Line (Premium < MA): Suggests that the short-term trend is negative, with USDC's value declining relative to its recent average against USDT.
•
Above Zero Line: USDC is trading at a premium to USDT.
•
Below Zero Line: USDC is trading at a discount to USDT.
This tool provides a nuanced view of the stablecoin ecosystem, helping traders understand capital flows and risk appetite. It is most effective when used to complement a broader market analysis strategy.
Volume Variance SuppressionVolume Variance Suppression Indicator
This indicator measures the variance of traded volume over a rolling window to detect periods of participation compression.
When volume variance falls below a defined threshold, it signals:
Reduced initiative order flow
Dominance of passive liquidity
Market balance / consolidation rather than trend
These suppression phases often precede volatility expansion, failed auctions, or impulsive moves, as liquidity builds and positioning becomes crowded.
The indicator is not directional and should be used as a market state filter, not a standalone signal. It helps distinguish balance vs expansion regimes and improves trade selection by aligning strategies with the current microstructural environment.
Performance Table: Standard DCA | Last 6-12-24-48MThis indicator visualizes Standard Dollar-Cost Averaging (DCA) performance across multiple time horizons (6M, 12M, 24M, 48M).
It summarizes invested capital, current portfolio value, net profit, and return percentage in a compact table, allowing quick comparison of short- and long-term DCA outcomes.
Designed for long-term investors, it helps evaluate how consistent periodic investments perform over time without relying on market timing.
The indicator is asset-agnostic and works on any symbol supported by TradingView.
Key use cases:
Long-term portfolio tracking
DCA strategy validation
Performance comparison across periods
Educational and analytical purposes
This tool focuses on clarity and realism, avoiding over-optimization and short-term noise.
--
I hope this table helps investors better understand long-term DCA performance.
Feedback and suggestions for improvement are always welcome.
MLMatrixLibOverview
MLMatrixLib is a comprehensive Pine Script v6 library implementing machine learning algorithms using native matrix operations. This library provides traders and developers with a toolkit of statistical and ML methods for building quantitative trading systems, performing data analysis, and creating adaptive indicators.
How It Works
The library leverages Pine Script's native matrix type to perform efficient linear algebra operations. Each algorithm is implemented from first principles, using matrix decomposition, iterative optimization, and statistical estimation techniques. All functions are designed for numerical stability with careful handling of edge cases.
---
Library Contents (34 Sections)
Section 1: Utility Functions & Matrix Operations
Core building blocks including:
• identity(n) - Creates n×n identity matrix
• diagonal(values) - Creates diagonal matrix from array
• ones(rows, cols) / zeros(rows, cols) - Matrix constructors
• frobeniusNorm(m) / l1Norm(m) - Matrix norm calculations
• hadamard(m1, m2) - Element-wise multiplication
• columnMeans(m) / rowMeans(m) - Statistical aggregations
• standardize(m) - Z-score normalization (zero mean, unit variance)
• minMaxNormalize(m) - Scale values to range
• fitStandardScaler(m) / fitMinMaxScaler(m) - Reusable scaler parameters
• addBiasColumn(m) - Prepend column of ones for regression
• arrayMedian(arr) / arrayPercentile(arr, p) - Array statistics
Section 2: Activation Functions
Numerically stable implementations:
• sigmoid(x) / sigmoidMatrix(m) - Logistic function with overflow protection
• tanhActivation(x) / tanhMatrix(m) - Hyperbolic tangent
• relu(x) / reluMatrix(m) - Rectified Linear Unit
• leakyRelu(x, alpha) - Leaky ReLU with configurable slope
• elu(x, alpha) - Exponential Linear Unit
• Derivatives for backpropagation: sigmoidDerivative, tanhDerivative, reluDerivative
Section 3: Linear Regression (OLS)
Ordinary Least Squares implementation using the normal equation (X'X)⁻¹X'y:
• fitLinearRegression(X, y) - Fits model, returns coefficients, R², standard error
• fitSimpleLinearRegression(x, y) - Single-variable regression
• predictLinear(model, X) - Generate predictions
• predictionInterval(model, X, confidence) - Confidence intervals using t-distribution
• Model type stores: coefficients, R-squared, residuals, standard error
Section 4: Weighted Linear Regression
Generalized least squares with observation weights:
• fitWeightedLinearRegression(X, y, weights) - Solves (X'WX)⁻¹X'Wy
• Useful for downweighting outliers or emphasizing recent data
Section 5: Polynomial Regression
Fits polynomials of arbitrary degree:
• fitPolynomialRegression(x, y, degree) - Constructs Vandermonde matrix
• predictPolynomial(model, x) - Evaluate polynomial at points
Section 6: Ridge Regression (L2 Regularization)
Adds penalty term λ||β||² to prevent overfitting:
• fitRidgeRegression(X, y, lambda) - Solves (X'X + λI)⁻¹X'y
• Lambda parameter controls regularization strength
Section 7: LASSO Regression (L1 Regularization)
Coordinate descent algorithm for sparse solutions:
• fitLassoRegression(X, y, lambda, maxIter, tolerance) - Iterative soft-thresholding
• Produces sparse coefficients by driving some to exactly zero
• softThreshold(x, lambda) - Core shrinkage operator
Section 8: Elastic Net (L1 + L2 Regularization)
Combines LASSO and Ridge penalties:
• fitElasticNet(X, y, lambda, alpha, maxIter, tolerance)
• Alpha balances L1 vs L2: alpha=1 is LASSO, alpha=0 is Ridge
Section 9: Huber Robust Regression
Iteratively Reweighted Least Squares (IRLS) for outlier resistance:
• fitHuberRegression(X, y, delta, maxIter, tolerance)
• Delta parameter defines transition between L1 and L2 loss
• Downweights observations with large residuals
Section 10: Quantile Regression
Estimates conditional quantiles using linear programming approximation:
• fitQuantileRegression(X, y, tau, maxIter, tolerance)
• Tau specifies quantile (0.5 = median, 0.25 = lower quartile, etc.)
Section 11: Logistic Regression (Binary Classification)
Gradient descent optimization of cross-entropy loss:
• fitLogisticRegression(X, y, learningRate, maxIter, tolerance)
• predictProbability(model, X) - Returns probabilities
• predictClass(model, X, threshold) - Returns binary predictions
Section 12: Linear SVM (Support Vector Machine)
Sub-gradient descent with hinge loss:
• fitLinearSVM(X, y, C, learningRate, maxIter)
• C parameter controls regularization (higher = harder margin)
• predictSVM(model, X) - Returns class predictions
Section 13: Recursive Least Squares (RLS)
Online learning with exponential forgetting:
• createRLSState(nFeatures, lambda, delta) - Initialize state
• updateRLS(state, x, y) - Update with new observation
• Lambda is forgetting factor (0.95-0.99 typical)
• Useful for adaptive indicators that update incrementally
Section 14: Covariance and Correlation
Matrix statistics:
• covarianceMatrix(m) - Sample covariance
• correlationMatrix(m) - Pearson correlations
• pearsonCorrelation(x, y) - Single correlation coefficient
• spearmanCorrelation(x, y) - Rank-based correlation
Section 15: Principal Component Analysis (PCA)
Dimensionality reduction via eigendecomposition:
• fitPCA(X, nComponents) - Power iteration method
• transformPCA(X, model) - Project data onto principal components
• Returns components, explained variance, and mean
Section 16: K-Means Clustering
Lloyd's algorithm with k-means++ initialization:
• fitKMeans(X, k, maxIter, tolerance) - Cluster data points
• predictCluster(model, X) - Assign new points to clusters
• withinClusterVariance(model) - Measure cluster compactness
Section 17: Gaussian Mixture Model (GMM)
Expectation-Maximization algorithm:
• fitGMM(X, k, maxIter, tolerance) - Soft clustering with probabilities
• predictProbaGMM(model, X) - Returns membership probabilities
• Models data as mixture of Gaussian distributions
Section 18: Kalman Filter
Linear state estimation:
• createKalman1D(processNoise, measurementNoise, ...) - 1D filter
• createKalman2D(processNoise, measurementNoise) - Position + velocity tracking
• kalmanStep(state, measurement) - Predict-update cycle
• Optimal filtering for noisy measurements
Section 19: K-Nearest Neighbors (KNN)
Instance-based learning:
• fitKNN(X, y) - Store training data
• predictKNN(model, X, k) - Classify by majority vote
• predictKNNRegression(model, X, k) - Average of k neighbors
• predictKNNWeighted(model, X, k) - Distance-weighted voting
Section 20: Neural Network (Feedforward)
Multi-layer perceptron:
• createNeuralNetwork(architecture) - Define layer sizes
• trainNeuralNetwork(nn, X, y, learningRate, epochs) - Backpropagation
• predictNN(nn, X) - Forward pass
• Supports configurable hidden layers
Section 21: Naive Bayes Classifier
Gaussian Naive Bayes:
• fitNaiveBayes(X, y) - Estimate class-conditional distributions
• predictNaiveBayes(model, X) - Maximum a posteriori classification
• Assumes feature independence given class
Section 22: Anomaly Detection
Statistical outlier detection:
• fitAnomalyDetector(X, contamination) - Mahalanobis distance-based
• detectAnomalies(model, X) - Returns anomaly scores
• isAnomaly(model, X, threshold) - Binary classification
Section 23: Dynamic Time Warping (DTW)
Time series similarity:
• dtw(series1, series2) - Compute DTW distance
• Handles sequences of different lengths
• Useful for pattern matching
Section 24: Markov Chain / Regime Detection
Discrete state transitions:
• fitMarkovChain(states, nStates) - Estimate transition matrix
• predictNextState(transitionMatrix, currentState) - Most likely next state
• stationaryDistribution(transitionMatrix) - Long-run probabilities
Section 25: Hidden Markov Model (Simple)
Baum-Welch algorithm:
• fitHMM(observations, nStates, maxIter) - EM training
• viterbi(model, observations) - Most likely state sequence
• Useful for regime detection
Section 26: Exponential Smoothing & Holt-Winters
Time series smoothing:
• exponentialSmooth(data, alpha) - Simple exponential smoothing
• holtWinters(data, alpha, beta, gamma, seasonLength) - Triple smoothing
• Captures trend and seasonality
Section 27: Entropy and Information Theory
Information measures:
• entropy(probabilities) - Shannon entropy in bits
• conditionalEntropy(jointProbs, marginalProbs) - H(X|Y)
• mutualInformation(probsX, probsY, jointProbs) - I(X;Y)
• kldivergence(p, q) - Kullback-Leibler divergence
Section 28: Hurst Exponent
Long-range dependence measure:
• hurstExponent(data) - R/S analysis
• H < 0.5: mean-reverting, H = 0.5: random walk, H > 0.5: trending
Section 29: Change Detection (CUSUM)
Cumulative sum control chart:
• cusumChangeDetection(data, threshold, drift) - Detect regime changes
• cusumOnline(value, prevCusumPos, prevCusumNeg, target, drift) - Streaming version
Section 30: Autocorrelation
Serial dependence analysis:
• autocorrelation(data, maxLag) - ACF for all lags
• partialAutocorrelation(data, maxLag) - PACF via Durbin-Levinson
• Useful for time series model identification
Section 31: Ensemble Methods
Model combination:
• baggingPredict(models, X) - Average predictions
• votingClassify(models, X) - Majority vote
• Improves robustness through aggregation
Section 32: Model Evaluation Metrics
Performance assessment:
• mse(actual, predicted) / rmse / mae / mape - Regression metrics
• accuracy(actual, predicted) - Classification accuracy
• precision / recall / f1Score - Binary classification metrics
• confusionMatrix(actual, predicted, nClasses) - Multi-class evaluation
• rSquared(actual, predicted) / adjustedRSquared - Goodness of fit
Section 33: Cross-Validation
Model validation:
• trainTestSplit(X, y, trainRatio) - Random split
• Foundation for walk-forward validation
Section 34: Trading Convenience Functions
Trading-specific utilities:
• priceMatrix(length) - OHLC data as matrix
• logReturns(length) - Log return series
• rollingSlope(src, length) - Linear trend strength
• kalmanFilter(src, processNoise, measurementNoise) - Filtered price
• kalmanFilter2D(src, ...) - Price with velocity estimate
• adaptiveMA(src, sensitivity) - Kalman-based adaptive moving average
• volAdjMomentum(src, length) - Volatility-normalized momentum
• detectSRLevels(length, nLevels) - K-means based S/R detection
• buildFeatures(src, lengths) - Multi-timeframe feature construction
• technicalFeatures(length) - Standard indicator feature set (RSI, MACD, BB, ATR, etc.)
• lagFeatures(src, lags) - Time-lagged features
• sharpeRatio(returns) - Risk-adjusted return measure
• sortinoRatio(returns) - Downside risk-adjusted return
• maxDrawdown(equity) - Maximum peak-to-trough decline
• calmarRatio(returns, equity) - Return/drawdown ratio
• kellyCriterion(winRate, avgWin, avgLoss) - Optimal position sizing
• fractionalKelly(...) - Conservative Kelly sizing
• rollingBeta(assetReturns, benchmarkReturns) - Market exposure
• fractalDimension(data) - Market complexity measure
---
Usage Example
```
import YourUsername/MLMatrixLib/1 as ml
// Create feature matrix
matrix X = ml.priceMatrix(50)
X := ml.standardize(X)
// Fit linear regression
ml.LinearRegressionModel model = ml.fitLinearRegression(X, y)
float prediction = ml.predictLinear(model, X_new)
// Kalman filter for smoothing
float smoothedPrice = ml.kalmanFilter(close, 0.01, 1.0)
// Detect support/resistance levels
array levels = ml.detectSRLevels(100, 3)
// K-means clustering for regime detection
ml.KMeansModel km = ml.fitKMeans(features, 3)
int cluster = ml.predictCluster(km, newFeature)
```
---
Technical Notes
• All matrix operations use Pine Script's native matrix type
• Numerical stability ensured through:
- Clamping exponential arguments to prevent overflow
- Division by zero protection with epsilon thresholds
- Iterative algorithms with convergence tolerance
• Designed for bar-by-bar execution in Pine Script's event-driven model
• Compatible with Pine Script v6
---
Disclaimer
This library provides mathematical tools for quantitative analysis. It does not constitute financial advice. Past performance of any algorithm does not guarantee future results. Users are responsible for validating models on their specific use cases and understanding the limitations of each method.
Vortex Indicator (Smoothed Version)The original tradingview vortex indicator but with smoothed as default
Broadening Formation Reclaim Stats v1.0Description: Broadening Formation Reclaim Stats v1.0
Overview
The Broadening Formation Reclaim Stats is a technical analysis tool designed to track and quantify "reclaim" price action within expanding market structures (Broadening Formations). It focuses on scenarios in which price breaches a prior Swing High or Swing Low and subsequently rotates back into the range, often signaling a potential reversal toward the opposite side of the formation.
This indicator is built for traders who study price action rotations, "The Strat" (Rev 2-2 / Failed 2-Down/Up), and liquidity sweeps.
How It Works
The script utilizes a state-machine logic to track price movements relative to high and low pivots:
1. Structure Identification: It identifies recent Pivot Highs and Lows (Auto-Swing mode) or allows users to input specific price levels (Manual mode).
2. The Breach: It identifies when price breaks above the established high or below the established low, "locking" the structure for a potential reclaim.
3. The Reclaim: A signal is generated when price moves back inside the range using specific price action triggers:
Rev 2-2: A reversal pattern where price reverses the direction of the previous candle.
Failed 2-Down/Up: Price makes a new wick extreme but closes back within the previous candle's range and below its opening price.
4. Targets: The script considers a reclaim "Successful" if price reaches the opposite side of the broadening formation (the opposing pivot).
Key Features
Backtesting Dashboard: A real-time table displaying the total number of reclaims, global success rates, and a breakdown of Bullish vs. Bearish performance.
Flexible Lookbacks: Statistics can be calculated based on the entire chart history, "Today Only" (for day traders), or a specific number of bars.
Dual Mode Detection: Choose between **Auto Swing** detection (based on a user-defined pivot length) or **Manual** mode for specific levels.
Optimized Visuals: Uses the Pine Script Plot Engine for core levels to ensure price-scale stability and "Box Objects" for clear pivot visualization.
Settings
Swing Length: Adjust the sensitivity of the pivot detection.
BF Mode: Toggle between automatic pivot tracking or manual price entry.
Statistics Start Mode: Filter the data displayed in the table to focus on recent price action or historical performance.
UI Customization: Fully adjustable table position, size, and transparency.
Disclaimer
This indicator is for educational and research purposes only. It tracks historical price action patterns and does not constitute financial advice. Past performance (success rates) as displayed in the dashboard is not an indicator of future results.
Magic Hour Range + Window Levels (0/50/75/100 + Extensions)This indicator plots one or more “Magic Hour” ranges (by ET hour) by drawing the hour’s high/low box, then extending an aligned post-hour analysis window for a set number of hours. Inside that window it overlays key reversion targets—0% (High), 50% (Mid), 100% (Low), optional 25%/75%—plus optional extension levels beyond the range (±25/50/75/100% and extras). All levels are clipped to the analysis window for a clean, session-by-session view of range, targets, and extensions.
ATR Volatility RegimeATR Volatility Regime
A volatility classification indicator that uses ATR (Average True Range) percentile ranking to identify LOW , NORMAL , HIGH , or EXTREME volatility conditions.
Displayed as a separate pane oscillator (0–100 scale) with colored zones.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 WHY THIS INDICATOR?
Most volatility indicators show raw ATR — a number without context. Is ATR = 50 high or low? Depends on the asset and recent history.
This indicator answers: "Is current volatility high or low for THIS asset, right now?"
What it adds over standard ATR:
Percentile context — Compares current ATR to its own history
Regime classification — Actionable labels instead of raw numbers
Visual zones — Instant read without interpretation
Optional MTF — Lock to a fixed timeframe while viewing another
Auto-adapts — Works on any asset without manual threshold tuning
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📐 CORE CONCEPTS
ATR (Average True Range)
Measures volatility in price units — how much an asset typically moves per bar. Directionless (magnitude only, not direction).
Calculation:
True Range = the greatest of:
High − Low (current bar's range)
|High − Previous Close| (gap up captured)
|Low − Previous Close| (gap down captured)
ATR = Moving average of True Range over N bars (default: 14)
Percentile Rank (Pctl)
Answers: "What percentage of historical values is the current value greater than?"
Pctl = 0% → Lowest ATR in lookback period (extreme compression)
Pctl = 50% → Median ATR (typical volatility)
Pctl = 100% → Highest ATR in lookback period (extreme expansion)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 WHAT IT DOES
Classifies current volatility into four regimes:
LOW (< 25th percentile) — Compression, breakout likely brewing
NORMAL (25th–50th percentile) — Typical market conditions
HIGH (50th–75th percentile) — Elevated volatility, use caution
EXTREME (> 75th percentile) — Rare expansion, tighten stops or stay flat
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 DISPLAY COMPONENTS
Oscillator Line (0–100)
ATR percentile rank over time. Color matches regime:
Blue = LOW
Gray = NORMAL
Orange = HIGH
Red = EXTREME
Zone Backgrounds
Colored bands at threshold levels for instant visual reference.
Status Label
VOL — Current regime
ATR — Raw ATR value (for stop sizing)
Pctl — Percentile rank (0–100%)
TF — Active timeframe (chart or fixed)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📈 HOW TO USE
LOW Volatility (Pctl < 25%):
Market compressed — "calm before the storm"
Watch for breakout setups
Pctl = 0% often precedes significant moves
NORMAL Volatility (Pctl 25–50%):
Typical conditions
Standard position sizing and stops
HIGH Volatility (Pctl 50–75%):
Elevated movement — reduce size
Widen stops to avoid noise
EXTREME Volatility (Pctl > 75%):
Rare, intense conditions
Avoid new entries or tighten risk
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙️ SETTINGS
ATR Settings:
ATR Length (default: 14) — Period for ATR calculation
Percentile Lookback (default: 100) — Bars for percentile ranking
Timeframe:
Use Fixed Timeframe (default: off) — Lock calculation to specific TF
Fixed Timeframe (default: D) — TF to use when fixed mode enabled
Thresholds:
Low Threshold (default: 25)
High Threshold (default: 50)
Extreme Threshold (default: 75)
Display:
Show Zone Background — Toggle colored fills
Show Status Label — Toggle info label
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 SUGGESTED LOOKBACK BY ASSET
Crypto — 100 bars (fast regime shifts)
Stocks — 252 bars (one trading year)
Forex — 100–150 bars
Commodities — 150–200 bars (seasonal patterns)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔔 ALERTS
Vol → EXTREME
Vol → HIGH
Vol → LOW
Vol exits HIGH
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 PRACTICAL APPLICATIONS
Stop-Loss Sizing:
Use raw ATR for stops. Example: Stop = Entry − (1.5 × ATR)
Position Sizing:
Reduce size when percentile is HIGH or EXTREME.
Entry Filtering:
LOW regime = prepare for breakout
EXTREME regime = avoid new entries
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📝 NOTES
Works on any timeframe — adapts to chart or locks to fixed TF
ATR is non-directional — magnitude only
Percentile auto-adapts to each asset's volatility profile
Not a standalone signal — combine with trend/regime filters
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🏷️ TAGS
volatility, ATR, average-true-range, percentile, regime, risk-management, position-sizing, swing-trading, MTF
Quant Stats: Alpha, Beta, R2Quant Stats Indicator for TradingView: Alpha, Beta, and R-Squared
Overview
The Quant Stats Indicator is a professional-grade Pine Script tool designed for quantitative traders and hedge fund managers who need real-time analysis of stock or ETF performance against a benchmark using three fundamental CAPM metrics: Beta, R-Squared, and Alpha.
This indicator calculates three critical measurements that answer every quant trader's core questions: How volatile is this asset relative to my benchmark? How much of its performance is independent of the benchmark? And how much excess return am I achieving after adjusting for risk?
The Three Metrics Explained
Beta (β) measures systematic risk and volatility relative to your chosen benchmark. A Beta of 1.0 means the asset moves in lockstep with the benchmark. A Beta above 1.0 indicates higher volatility—if the market rises 10%, a Beta-1.5 asset should rise 15%. Conversely, a Beta below 1.0 indicates lower volatility, making it a defensive position. This metric helps you understand how much market exposure you're truly taking.
R-Squared (R²) quantifies what percentage of an asset's price movement can be explained by benchmark movements. An R² of 0.95 means 95% of the asset's moves are driven by the benchmark, leaving only 5% unexplained. Conversely, an R² of 0.2 means 80% of the asset's movement is independent of the benchmark. This distinction is crucial: high R² is desirable for passive index tracking but indicates weak alpha potential; low R² reveals genuine independent returns, exactly what active managers seek.
Alpha (α) reveals Jensen's Alpha—the excess risk-adjusted return after accounting for the return you "should" earn given your Beta exposure. A positive Alpha of 15% means you're outperforming the market by 15 percentage points after adjusting for systematic risk. This is the holy grail of stock picking: pure skill-driven excess return, not luck from market exposure.
How to Use It
Configure four key inputs: your benchmark ticker (default SPY, but use QQQ for tech-focused analysis or sector-specific ETFs), the lookback period in days, and the risk-free rate reflecting current Treasury yields. The lookback period is critical. Use 20 days for tactical trading to capture short-term sentiment and beta spikes; use 63 days for swing trading and quarterly rebalancing; use 252 days for structural asset allocation decisions.
The indicator plots Beta as a blue line, R-Squared as a red shaded background area, and Alpha as a green line in a sub-panel. Reference gridlines appear at Beta = 1.0 (market-equivalent volatility) and Alpha = 0.0 (breakeven performance), making interpretation intuitive.
Practical Applications
For swing traders monitoring a 63-day window, seek positions with low Beta (below 0.8) and positive Alpha—these are defensive winners. Avoid high Beta (above 1.2) with low R² unless you specifically want high-volatility speculation. Long/short hedge funds should use a 20-day lookback to detect regime changes: sudden Beta spikes often precede correlation breakdowns, while R² collapses signal rising idiosyncratic risk requiring immediate rebalancing.
For ETF portfolio construction, high R² (above 0.95) indicates index-tracking that doesn't justify active management fees. Low R² (below 0.3) combined with positive Alpha reveals genuine active management skill. The sweet spot is moderate Beta (0.5–0.8) with low R² and positive Alpha—a true diversifier that reduces portfolio volatility while generating independent returns.
Critical Interpretation Rules
A common mistake is assuming high R² is always desirable. It isn't. Passive index funds naturally have high R²; active managers should target low R² with high Alpha. Similarly, don't assume Alpha above 10% is sustainable—short-term Alpha (20–100 days) is inherently volatile and often represents temporary mispricings rather than repeatable skill. Always pair Beta analysis with R² interpretation; Beta alone ignores idiosyncratic risk, liquidity constraints, and tail risk.
Configuration Recommendations
Conservative investors should use SPY as benchmark with a 252-day lookback, targeting Alpha above 3% and Beta below 0.8. Growth-oriented portfolios might use QQQ with a 63-day lookback, targeting 8–12% Alpha and tolerating Beta up to 1.3. Hedge funds pursuing market-neutral strategies should use SPY with a 20-day lookback, set the risk-free rate to 2% (anticipating rate cuts), and target 15%+ Alpha while maintaining Beta below 0.3.
Important Limitations
The indicator is backward-looking; historical statistical relationships may not persist. Shorter lookback periods are noisier but more responsive; longer periods smooth noise but lag regime changes. Choosing the wrong benchmark completely invalidates analysis. Finally, the indicator doesn't account for tail risk or extreme market events where correlations spike unpredictably and Beta becomes unreliable.
Use this tool to separate signal from noise and identify true alpha generators. Apply it consistently, validate results against official fund factsheets, and monitor for 2–4 weeks before making significant portfolio decisions.
HAP Trend CageHAP Trend Cage – Visual Band & Stochastic Entry System
HAP Trend Cage is a pure visual overlay indicator designed to show when price is trapped inside dynamic bands — and when momentum timing aligns for a potential entry.
This is not Bollinger Bands.
These bands are built to contain price behavior, not volatility expansion.
🔹 What it shows:
Dynamic price bands plotted directly on the chart
Clear visual zones where price is compressed or held
Stochastic (14, 3, 3) used purely for entry timing
Exact candle awareness — you see where and when the signal happens
🔹 How to use:
Follow the bands visually — price inside the cage = structure intact
Wait for Stochastic alignment inside or near band boundaries
Designed for confirmation, not prediction
No clutter, no repainting, no over-signaling
🔹 Why it’s different:
Focuses on market structure first
Momentum is used only as a timing tool
Built for traders who trust price behavior over indicators
This indicator does not tell you to buy or sell.
It shows you where the market is constrained — and lets you decide when to act
Monthly Seasonality AnalyzerThis indicator analyzes historical performance/seasonality of a chosen month, from date of inception to present. Users can choose any calendar month via dropdown menu.
For each historical month selected, it will calculate the monthly percentage gain/loss, range(volatility), and average gain/loss percentage, average range percentage across all recorded years. Positive returns are colored green and negative returns are red. Also, calculates if the selected month was bullish(open>close) or bearish.
When current chart month matches the selected month, it shows the in-progress range as well.
Data is collected from 1930 to present. Results are shown in vertical and horizontal tables. If the vertical table exceeds a 36 years, the script automatically switches to horizontal table to display all the data, with option to change table position.
Overall this tool is valuable for seasonality research, such as Santa Rally, May Go Away and swing trading/ position trading to capture the monthly PO3 range.
Most seasonality indicators show all 12 months at once or use daily bars. This one zooms in deeply on one month only, providing detailed per-year breakdowns, accurate completed-month stats, and a practical live range display.
The script uses arrays to store years, gains, and ranges. Uses table.new(), table.cell(), table.merge_cells() for easily readable result display. Code handles the current in-progress month separately (shows live range without including it in historical averages).
**Script will not run on any timeframe other than monthly and displays error otherwise. Script is best used on spot and not futures.
BERNA (Boundary-Encoded Resonance Network Architecture)BERNA — Boundary-Encoded Resonance Network Architecture
BERNA is a research-grade indicator that estimates the remaining structural capacity of the current market regime.
Unlike trend, volatility, or momentum tools, BERNA does not measure price direction — it measures how much of the regime’s internal capacity has already been consumed.
This script implements the BERNA model published on Zenodo (Bülent Duman, 2026).
It is intentionally minimal and uses only OHLC data.
What BERNA measures
BERNA outputs a structural capacity state:
τ = Σ / Θ (normalized structural stress)
Λ = Θ − Σ (remaining structural capacity)
Interpretation:
High Λ / low τ → the regime has structural endurance
Rising τ → capacity is being consumed
τ → 1 (Λ → 0) → rupture proximity (capacity exhaustion)
This makes BERNA a forward-looking structural capacity variable, not a price oscillator.
What is inside this script
This implementation contains the following components:
Efficiency proxy (DERYA-like, but not the full public DERYA)
BERNA uses a simple microstructure efficiency proxy computed as:
E = |close − open| / (high − low)
This is conceptually “DERYA-like” but it is not the full DERYA framework.
No external/public DERYA source code is embedded here.
Standard technical primitives used
This script uses only basic primitives commonly found in technical analysis:
Absolute value and range normalization
Thresholding (regime binning)
Power transform on range (rng^p)
There is no EMA, RSI, MACD, ATR, ADX, Fisher, Kaufman, or other indicator embedded.
All computations are internal and deterministic.
3-state structural regime binning (K = 3)
The efficiency proxy E is discretized into three regimes using user thresholds:
Low efficiency
Mid efficiency
High efficiency
Each regime has its own capacity Θ and stress multiplier β.
Structural stress accumulation (Σ) and rupture proximity
Stress increment is defined as:
dΣ = β · (1 − E) · (range^p)
Σ accumulates inside a regime and is capped by Θ.
In this prototype, Σ resets on regime change by construction (regime-gated accumulation).
The rupture proximity is expressed through τ and Λ.
How to use BERNA
BERNA is designed as a regime-health and fragility overlay, not a buy/sell trigger.
Typical uses:
Detect when an ongoing move is structurally late-stage (τ high, Λ low)
Avoid initiating trades when capacity is nearly exhausted
Compare structural resilience across assets and regimes
Use alongside price/trend/volume systems for context
Do not use BERNA alone as a trading signal.
BERNA tells you “how much structure is left”, not “where price will go.”
Visuals
Efficiency (E) shows the bar-level microstructure efficiency proxy
τ shows normalized structural stress (capacity consumption)
Λ shows remaining structural capacity
Dotted lines mark warning and critical rupture proximity levels
Important notes
BERNA is not RSI, MACD, ATR, ADX, Fisher, Kaufman, or a volatility model
BERNA does not predict price direction
BERNA does not issue entry/exit signals
BERNA is a structural capacity diagnostic
This script does not embed any external/public indicator code; all logic is implemented directly in Pine.
Risk and disclaimer
This script is provided for research and analytical purposes only.
It is not financial advice and must not be used as a standalone trading system.
Markets are uncertain.
All trading decisions and risks remain entirely the responsibility of the user.
BERNA: Boundary-Encoded Resonance Network Architecture
A Structural Failure Theory of Financial Regimes Based on Endogenous Capacity Depletion
Author: Duman, Bülent
Affiliation: Independent Researcher
Reference: zenodo.org






















