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
Statistics
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.
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).
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.
Vortex Indicator (Smoothed Version)The original tradingview vortex indicator but with smoothed as default
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.
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.
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.
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.
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
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
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.
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.
ADR% babaThis indicator calculates the Average Day Range (ADR) as a percentage using the TC2000 methodology, measuring the average relative expansion between daily highs and lows to quantify market volatility in a price-level independent manner.
Nas Indicator It helps with finding directional bias based off of percentages and grounds me better in my execution.
Lot Size & Risk Calculator All Pairs NEWLot Size & Risk Calculator All Pairs NEW
Description
Professional risk and position size calculator for traders working with various financial instruments.
Main difference from standard indicators:
Standard risk calculators only show basic Risk/Reward for the entire position. But in real trading, we often close positions partially at different take-profit levels, and the final Risk/Reward changes significantly with this approach! This indicator calculates weighted Risk/Reward taking into account position distribution across multiple take-profit levels.
Main features:
- Support for 4 instrument types: Forex, XAUUSD (gold), BTCUSD (bitcoin), US100 (NASDAQ index)
- Automatic position size calculation based on risk and stop-loss distance
- Multiple take-profit levels with customizable closing percentages
- Weighted Risk/Reward calculation considering position distribution
- Ability to adjust position distribution between take-profits to optimize final profit
- Display of total percentage growth of deposit from all take-profit levels
- 2 visualization options: colored fill between levels or lines
- Informative results panel in table format
Settings by groups:
Core Settings
- Currency: select instrument type (Forex, XAUUSD, BTCUSD, US100)
- Account Balance: trading account size in dollars
- Risk %: risk percentage from deposit (0.1-100%)
- Use Custom Contract Sizes: manual contract size configuration
Point Value Settings
- Use automatic point value calculation: automatic point value calculation
- Manual point value: manual point value input (for non-standard contracts)
Levels
- Entry Price: entry price (confirmation required on first use)
- Stop Price: stop-loss price
- Take-Profit Prices: take-profit prices (up to 3 levels)
- TP Close %: percentage of position closed at each take-profit level
Dashboard
- Show Targets Profit: display profit from take-profit levels
- Label Size: text size in the table
- Dashboard Position: table position on the chart
How to use:
Step 1: Initial setup (when first adding)
1. Enter entry price (Entry Price) - confirmation window will appear (click on desired bar)
2. Then enter stop-loss price (Stop Price) (click on desired bar)
3. Add first take-profit (TP1) (click on desired bar)
4. Second and third take-profits are added through checkboxes (click on the settings gear icon to open them)
Step 2: Instrument selection and risk configuration
1. In "Core" group, select your instrument type
2. Set account balance and risk percentage
Step 3: Position distribution configuration
1. Set TP Close % for each take-profit level (e.g.: TP1 - 33%, TP2 - 33%, TP3 - 34%)
2. Experiment with distribution! By changing closing percentages, you can:
- Increase/decrease final Risk/Reward
- Optimize risk/profit ratio
- Find the most comfortable position distribution for you
Step 4: Results analysis
1. Results table will show:
- Calculated position size (lots/contracts)
- Risk in monetary terms
- Risk/Reward for each take-profit level
- Weighted R:R considering position distribution
- Total potential profit from all take-profits
- Percentage growth of deposit - total profit percentage from all take-profit levels
Key features:
Position distribution adjustment
You can easily find optimal position distribution between take-profits:
- Aggressive approach: higher percentage on distant take-profit (higher profit potential)
- Conservative approach: higher percentage on near take-profit (faster profit taking)
- Balanced: even distribution for risk reduction
Weighted Risk/Reward
The indicator calculates not just simple R:R for the entire position, but weighted value that considers:
- Position distribution between take-profits
- Different distances to each take-profit level
- Closing percentage at each level
Results visualization
- Colored fill shows risk and profit zones
- Labels at levels display specific profit/loss values
- Results table contains all key metrics
Creation story
This indicator was created based on the original calculator by @Algoryze As a trader, I lacked the ability to see real Risk/Reward when partially closing positions and a convenient tool for selecting optimal position distribution between take-profit levels. I improved the indicator by adding:
- Weighted Risk/Reward calculation
- Ability to adjust closing percentage at each take-profit
- Display of total percentage growth of deposit
- Improved interface and visualization
I hope this tool will be useful to other traders who use strategies with partial position closing!
Important notes:
1. When first adding the indicator, be sure to enter prices in order: Entry → Stop → TP1
2. TP2 and TP3 are added through input fields (no confirmation required)
3. Closing percentages are automatically normalized if the sum is not 100%
4. Experiment with position distribution to find optimal risk/profit ratio
5. For different instruments, add separate copies of the indicator in different tabs
Support
For questions and suggestions, leave comments in the indicator publication on TradingView.
---
Important: All calculations are provided for informational purposes only. Trading involves risks, trade responsibly. The indicator helps with calculations but does not guarantee profit.
Linear Regression R-SquaredCalculates the least squares linear regression R-squared values for the specified data period. Values range from zero to one.
LARGER PRICE LINE Adjustable (UPDATED)LARGER PRICE LINE
I made this so I could SEE THE PRICE LINE BETTER and try to reduce some eye strain!!
Hope it helps... enjoy! comment for improvements or suggestions
Improved Adjustable Size and Color for the Price Line and Price Box
Adjustment for Price Line: Size and Color plus Solid Line, Dashed or Dotted Line
Adjustments include: Price Box Text Size and Color (Small, Normal, Large, Huge!)
Adjustable Right Side Offset for Price Box
VWMA Cross Buy SignalCore Components & Logic
1. The Entry Engine (VWMA + Filters)
The strategy triggers a long signal when a Volume Weighted Moving Average (VWMA) crossover occurs.
Unlike a standard Simple Moving Average, the VWMA gives more weight to bars with higher volume. This ensures the indicator responds faster to "Smart Money" moves and slower to low-volume noise.
It uses a secondary Trend Filter (defaulting to the 200 EMA). By only buying when the price is above this line, the indicator forces you to stay on the right side of the primary market trend.
It requires volume to be higher than its recent average (e.g., 1.1× or 10% higher). This prevents entries on weak, low-conviction price moves.
2. The Dynamic Exit System
You have two distinct ways to manage your risk and targets, toggleable in the settings:
ATR Based (Volatility Adjusted): It calculates the Average True Range (ATR) to determine how volatile the stock is. By setting your Stop Loss at 2.0×ATR, you avoid getting "shaken out" by normal daily price fluctuations. The Take Profit is set at 4.4×ATR to capture large trend extensions.
Fixed % (Static): A more rigid approach where you set a hard percentage target (e.g., 10% gain / 5% loss).
3. The Performance Analytics Table
The grey minimalist table in the bottom-right corner uses cumulative percentage-based math to show:
Realized RRR: The actual Reward-to-Risk ratio based on your closed trades.
Break-Even Win Rate: The minimum win rate you need to stay profitable with your current RRR. It uses the formula:
BE WR=1+RRR1
Current Win Rate: Highlighted in Green if you are beating the Break-Even rate, or Red if the strategy is currently losing money on that specific stock.
Max Drawdown %: The most important metric for risk. It shows the largest peak-to-trough decline in your equity curve, letting you know how much losing streak can hurt your equity.
Strategic Use Case
This indicator is optimized for Stock Screening. When you flip through your watchlist, the table updates instantly.
If you see a stock with a high Win Rate and a Max Drawdown under 10%, you have found a ticker where the VWMA crossover logic is highly compatible with that stock's specific volatility. If the Win Rate cell is Red, you know the strategy is "un-tuned" for that asset and needs adjustment.
Median Anchor Oscillator [ALPHA]ALPHA – Median Anchor Oscillator
A clean, outlier-resistant z-score oscillator built around a rolling median (not mean) and Median Absolute Deviation (MAD) instead of standard deviation.
Key features:
- Green/red histogram shows deviation strength from the median anchor
- Dashed lines at ± threshold (default 2.5 – adjustable)
- Optional purple fill for extreme zones
- Auto-scales perfectly (no price squish on BTC or high-value assets)
Ideal for mean-reversion traders spotting overextension or "gravity" pullbacks.
SHORT = breaching top dashed line (red)
LONG = breaching bottom dashed line (green)
Use with a MACD or RSI for those divergence signal confirmations.
This is ALPHA – early version, still tuning.
Companion overlay suite (medians, pivot, signals, RSI overlay) coming in future, possible standalone update(s).
Feedback / suggestions very welcome!
Tags: z-score, median, oscillator, mean-reversion, BTC, crypto, deviation
Crosses Open Daily (shock points OD)It is an indicator that works to alert you when an asset, during the day, crosses or approaches the daily open again.
Teemo Volume Delta & Market HUDTeemo Volume Delta & Market HUD
Description:
Teemo Volume Delta goes beyond simple volume indicators to provide expert-level analysis of Buy and Sell pressure within the market. It visualizes supply/demand imbalances inside candles and provides an immediate grasp of market control via a real-time HUD.
With the v1.2.0 update, we have removed unnecessary overlays (like EMAs) to focus on Pure Delta Analysis and a flexible Smart Accumulation System, making the tool lighter and more powerful.
🚀 Key Features
1. Dual Calculation Modes Offers two calculation methods tailored to your trading environment and goals:
Estimation: Rapidly estimates buy/sell volume based on candle shape (OHLC) and price range. It features fast loading times and works instantly on all assets.
Intraday: Analyzes lower timeframe data (e.g., 1-minute bars) to calculate the precise delta of the current timeframe. (Loading time may vary depending on TradingView data limits.)
2. Smart Accumulation System Supports strategic analysis beyond simple summation with two distinct modes:
Time Based: Resets the Cumulative Delta to 0 at specific intervals (e.g., every 4 hours, Daily). This is optimized for session-based analysis or day trading.
Infinite: Continuously accumulates data without resetting, ideal for analyzing long-term Divergences between price and delta.
3. Intuitive HUD (Heads-Up Display) Displays critical market data on the chart for instant decision-making:
Delta Panel: Shows real-time Buy/Sell volume and Net Delta for the current candle.
Market HUD: Provides a comprehensive view of Trend Strength (ADX), Momentum (RSI), and the Cumulative Buy/Sell status for the current period.
4. Teemo Design System (v1.2) Provides optimized color themes for visual comfort during long trading sessions:
Teemo Neon: High-contrast Mint/Purple theme optimized for dark backgrounds.
Classic Soft: A calming Soft Green/Red theme designed to reduce eye strain (Recommended for all backgrounds).
⚙️ Settings Guide
Calculation Mode: Choose between Estimation (Speed) or Intraday (Precision).
Accumulation Mode: Choose Time Based (Periodic Reset) or Infinite (Continuous).
Reset Period: Set the reset interval for Time Based mode (e.g., 1D = Daily Reset).
Color Preset: Select between Teemo Neon or Classic Soft themes.
💡 Trading Tips
Delta Divergence: If the price makes a higher high but the Cumulative Delta (HUD) makes a lower high, it signals weakening buying pressure and a potential reversal.
Candle Coloring: A solid Mint (or Green) candle body indicates a price rise accompanied by strong actual buying volume, offering higher reliability than standard candles.
HUD Confluence: Consider trend-following entries when the ADX is above 25 and the Delta is heavily skewed in one direction.
This indicator is for informational purposes only and does not constitute financial advice. The Estimation mode provides approximations based on algorithms, and the Intraday mode's accuracy depends on the quality of the lower timeframe data provided by the exchange.
Developed by Teemo Trading Systems
------------------------------------------------------------------------
Teemo Volume Delta & Market HUD
설명 본문:
Teemo Volume Delta는 단순한 거래량 지표를 넘어, 시장 내부의 매수(Buy)와 매도(Sell) 압력을 정밀하게 분석하는 전문가용 도구입니다. 캔들 내부의 수급 불균형을 시각화하고, 실시간 HUD를 통해 시장의 주도권이 누구에게 있는지 즉각적으로 파악할 수 있도록 돕습니다.
v1.2.0 업데이트를 통해 불필요한 보조지표(EMA)를 제거하고, 순수한 델타 분석과 유연한 누적(Accumulation) 시스템에 집중하여 더욱 가볍고 강력해졌습니다.
🚀 주요 기능 (Key Features)
1. 듀얼 계산 모드 (Dual Calculation Modes) 사용자의 환경과 목적에 맞춰 두 가지 계산 방식을 제공합니다.
Estimation (추정 모드): 캔들의 형태(OHLC)와 가격 변동폭을 기반으로 매수/매도 볼륨을 빠르게 추정합니다. 로딩 속도가 빠르며 모든 자산에 즉시 적용 가능합니다.
Intraday (정밀 분석 모드): 하위 타임프레임(예: 1분봉)의 데이터를 분석하여 상위 타임프레임의 델타를 정밀하게 계산합니다. (TradingView 데이터 제한에 따라 로딩 시간이 소요될 수 있습니다.)
2. 스마트 누적 시스템 (Smart Accumulation) 단순 누적을 넘어, 전략적 분석을 위한 두 가지 모드를 지원합니다.
Time Based: 지정한 주기(예: 4시간, 1일)마다 누적 델타를 **0으로 초기화(Reset)**합니다. 세션별 수급 분석이나 데이 트레이딩에 최적화되어 있습니다.
Infinite: 초기화 없이 데이터를 계속 누적하여, 장기적인 가격과 델타의 **다이버전스(Divergence)**를 분석하는 데 유용합니다.
3. 직관적인 HUD (Heads-Up Display) 차트 우측과 좌측에 핵심 정보를 요약하여 보여줍니다.
Delta Panel: 현재 캔들의 매수/매도 거래량과 순매수(Net Delta) 상태를 실시간으로 표시합니다.
Market HUD: ADX(추세 강도), RSI(모멘텀), 그리고 현재 구간의 누적 매수/매도 현황을 한눈에 볼 수 있습니다.
4. Teemo Design System (v1.2) 장시간 차트를 보는 트레이더를 위해 시인성이 뛰어난 컬러 테마를 제공합니다.
Teemo Neon: 어두운 배경에 최적화된 고대비 민트/퍼플 테마.
Classic Soft: 눈의 피로를 줄여주는 차분한 그린/레드 테마 (밝은/어두운 배경 모두 추천).
⚙️ 설정 가이드 (Settings)
Calculation Mode: Estimation(속도 중심) 또는 Intraday(정확도 중심) 중 선택.
Accumulation Mode: Time Based(주기별 리셋) 또는 Infinite(무한 누적) 선택.
Reset Period: Time Based 모드 사용 시 리셋할 주기 설정 (예: 1D = 매일 리셋).
Color Preset: Teemo Neon 또는 Classic Soft 테마 선택.
💡 활용 팁 (Trading Tips)
델타 다이버전스: 가격은 신고가를 갱신하지만 누적 델타(Cum Delta)는 낮아진다면, 매수세가 약화되고 있다는 강력한 반전 신호입니다.
캔들 컬러링: 캔들의 몸통 색상이 짙은 민트색(또는 그린)이라면 강력한 매수세가 동반된 상승을 의미하며, 신뢰도가 높습니다.
HUD 활용: ADX가 25 이상이면서 델타가 한쪽 방향으로 쏠릴 때 추세 매매를 고려하세요.
이 지표는 정보 제공의 목적으로만 사용되며, 재정적 조언이 아닙니다. Estimation 모드는 근사치를 제공하며, Intraday 모드는 거래소에서 제공하는 하위 데이터의 품질에 따라 정확도가 달라질 수 있습니다.






















