Uptrick: Dynamic Z-Score DivergenceIntroduction
Uptrick: Dynamic Z-Score Divergence is an oscillator that combines multiple momentum sources within a Z-Score framework, allowing for the detection of statistically significant mean-reversion setups, directional shifts, and divergence signals. It integrates a multi-source normalized oscillator, a slope-based signal engine, structured divergence logic, a slope-adaptive EMA with dynamic bands, and a modular bar coloring system. This script is designed to help traders identify statistically stretched conditions, evolving trend dynamics, and classical divergence behavior using a unified statistical approach.
Overview
At its core, this script calculates the Z-Score of three momentum sources—RSI, Stochastic RSI, and MACD—using a user-defined lookback period. These are averaged and smoothed to form the main oscillator line. This normalized oscillator reflects how far short-term momentum deviates from its mean, highlighting statistically extreme areas.
Signals are triggered when the oscillator reverses slope within defined inner zones, indicating a shift in direction while the signal remains in a statistically stretched state. These mean-reversion flips (referred to as TP signals) help identify turning points when price momentum begins to revert from extended zones.
In addition, the script includes a divergence detection engine that compares oscillator pivot points with price pivot points. It confirms regular bullish and bearish divergence by validating spacing between pivots and visualizes both the oscillator-side and chart-side divergences clearly.
A dynamic trend overlay system is included using a Slope Adaptive EMA (SA-EMA). This trend line becomes more responsive when Z-Score deviation increases, allowing the trend line to adapt to market conditions. It is paired with ATR-based bands that are slope-sensitive and selectively visible—offering context for dynamic support and resistance.
The script includes configurable bar coloring logic, allowing users to color candles based on oscillator slope, last confirmed divergence, or the most recent signal of any type. A full alert system is also built-in for key signals.
Originality
The script is based on the well-known concept of Z-Score valuation, which is a standard statistical method for identifying how far a signal deviates from its mean. This foundation—normalizing momentum values such as RSI or MACD to measure relative strength or weakness—is not unique to this script and is widely used in quantitative analysis.
What makes this implementation original is how it expands the Z-Score foundation into a fully featured, signal-producing system. First, it introduces a multi-source composite oscillator by combining three momentum inputs—RSI, Stochastic RSI, and MACD—into a unified Z-Score stream. Second, it builds on that stream with a directional slope logic that identifies turning points inside statistical zones.
The most distinctive additions are the layered features placed on top of this normalized oscillator:
A structured divergence detection engine that compares oscillator pivots with price pivots to validate regular bullish and bearish divergence using precise spacing and timing filters.
A fully integrated slope-adaptive EMA overlay, where the smoothing dynamically adjusts based on real-time Z-Score movement of RSI, allowing the trend line to become more reactive during high-momentum environments and slower during consolidation.
ATR-based dynamic bands that adapt to slope direction and offer real-time visual zones for support and resistance within trend structures.
These features are not typically found in standard Z-Score indicators and collectively provide a unique approach that bridges statistical normalization, structure detection, and adaptive trend modeling within one script.
Features
Z-Score-based oscillator combining RSI, StochRSI, and MACD
Configurable smoothing for stable composite signal output
Buy/Sell TP signals based on slope flips in defined zones
Background highlighting for extreme outer bands
Inner and outer zones with fill logic for statistical context
Pivot-based divergence detection (regular bullish/bearish)
Divergence markers on oscillator and price chart
Slope-Adaptive EMA (SA-EMA) with real-time adaptivity based on RSI Z-Score
ATR-based upper and lower bands around the SA-EMA, visibility tied to slope direction
Configurable bar coloring (oscillator slope, divergence, or most recent signal)
Alerts for TP signals and confirmed divergences
Optional fixed Y-axis scaling for consistent oscillator view
The full setup mode can be seen below:
Input Parameters
General Settings
Full Setup: Enables rendering of the full visual system (lines, bands, signals)
Z-Score Lookback: Lookback period for normalization (mean and standard deviation)
Main Line Smoothing: EMA length applied to the averaged Z-Score
Slope Detection Index: Used to calculate directional flips for signal logic
Enable Background Highlighting: Enables visual region coloring in
overbought/oversold areas
Force Visible Y-Axis Scale: Forces max/min bounds for a consistent oscillator range
Divergence Settings
Enable Divergence Detection: Toggles divergence logic
Pivot Lookback Left / Right: Defines the structure of oscillator pivot points
Minimum / Maximum Bars Between Pivots: Controls the allowed spacing range for divergence validation
Bar Coloring Settings
Bar Coloring Mode:
➜ Line Color: Colors bars based on oscillator slope
➜ Latest Confirmed Signal: Colors bars based on the most recent confirmed divergence
➜ Any Latest Signal: Colors based on the most recent signal (TP or divergence)
SA-EMA Settings
RSI Length: RSI period used to determine adaptivity
Z-Score Length: Lookback for normalizing RSI in adaptive logic
Base EMA Length: Base length for smoothing before adaptivity
Adaptivity Intensity: Scales the smoothing responsiveness based on RSI deviation
Slope Index: Determines slope direction for coloring and band logic
Band ATR Length / Band Multiplier: Controls the width and responsiveness of the trend-following bands
Alerts
The script includes the following alert conditions:
Buy Signal (TP reversal detected in oversold zone)
Sell Signal (TP reversal detected in overbought zone)
Confirmed Bullish Divergence (oscillator HL, price LL)
Confirmed Bearish Divergence (oscillator LH, price HH)
These alerts allow integration into automation systems or signal monitoring setups.
Summary
Uptrick: Dynamic Z-Score Divergence is a statistically grounded trading indicator that merges normalized multi-momentum analysis with real-time slope logic, divergence detection, and adaptive trend overlays. It helps traders identify mean-reversion conditions, divergence structures, and evolving trend zones using a modular system of statistical and structural tools. Its alert system, layered visuals, and flexible input design make it suitable for discretionary traders seeking to combine quantitative momentum logic with structural pattern recognition.
Disclaimer
This script is for educational and informational purposes only. No indicator can guarantee future performance, and trading involves risk. Always use risk management and test strategies in a simulated environment before deploying with live capital.
Statistics
Static K-means Clustering | InvestorUnknownStatic K-Means Clustering is a machine-learning-driven market regime classifier designed for traders who want a data-driven structure instead of subjective indicators or manually drawn zones.
This script performs offline (static) K-means training on your chosen historical window. Using four engineered features:
RSI (Momentum)
CCI (Price deviation / Mean reversion)
CMF (Money flow / Strength)
MACD Histogram (Trend acceleration)
It groups past market conditions into K distinct clusters (regimes). After training, every new bar is assigned to the nearest cluster via Euclidean distance in 4-dimensional standardized feature space.
This allows you to create models like:
Regime-based long/short filters
Volatility phase detectors
Trend vs. chop separation
Mean-reversion vs. breakout classification
Volume-enhanced money-flow regime shifts
Full machine-learning trading systems based solely on regimes
Note:
This script is not a universal ML strategy out of the box.
The user must engineer the feature set to match their trading style and target market.
K-means is a tool, not a ready made system, this script provides the framework.
Core Idea
K-means clustering takes raw, unlabeled market observations and attempts to discover structure by grouping similar bars together.
// STEP 1 — DATA POINTS ON A COORDINATE PLANE
// We start with raw, unlabeled data scattered in 2D space (x/y).
// At this point, nothing is grouped—these are just observations.
// K-means will try to discover structure by grouping nearby points.
//
// y ↑
// |
// 12 | •
// | •
// 10 | •
// | •
// 8 | • •
// |
// 6 | •
// |
// 4 | •
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
//
//
// STEP 2 — RANDOMLY PLACE INITIAL CENTROIDS
// The algorithm begins by placing K centroids at random positions.
// These centroids act as the temporary “representatives” of clusters.
// Their starting positions heavily influence the first assignment step.
//
// y ↑
// |
// 12 | •
// | •
// 10 | • C2 ×
// | •
// 8 | • •
// |
// 6 | C1 × •
// |
// 4 | •
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
//
//
// STEP 3 — ASSIGN POINTS TO NEAREST CENTROID
// Each point is compared to all centroids.
// Using simple Euclidean distance, each point joins the cluster
// of the centroid it is closest to.
// This creates a temporary grouping of the data.
//
// (Coloring concept shown using labels)
//
// - Points closer to C1 → Cluster 1
// - Points closer to C2 → Cluster 2
//
// y ↑
// |
// 12 | 2
// | 1
// 10 | 1 C2 ×
// | 2
// 8 | 1 2
// |
// 6 | C1 × 2
// |
// 4 | 1
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
// (1 = assigned to Cluster 1, 2 = assigned to Cluster 2)
// At this stage, clusters are formed purely by distance.
Your chosen historical window becomes the static training dataset , and after fitting, the centroids never change again.
This makes the model:
Predictable
Repeatable
Consistent across backtests
Fast for live use (no recalculation of centroids every bar)
Static Training Window
You select a period with:
Training Start
Training End
Only bars inside this range are used to fit the K-means model. This window defines:
the market regime examples
the statistical distributions (means/std) for each feature
how the centroids will be positioned post-trainin
Bars before training = fully transparent
Training bars = gray
Post-training bars = full colored regimes
Feature Engineering (4D Input Vector)
Every bar during training becomes a 4-dimensional point:
This combination balances: momentum, volatility, mean-reversion, trend acceleration giving the algorithm a richer "market fingerprint" per bar.
Standardization
To prevent any feature from dominating due to scale differences (e.g., CMF near zero vs CCI ±200), all features are standardized:
standardize(value, mean, std) =>
(value - mean) / std
Centroid Initialization
Centroids start at diverse coordinates using various curves:
linear
sinusoidal
sign-preserving quadratic
tanh compression
init_centroids() =>
// Spread centroids across using different shapes per feature
for c = 0 to k_clusters - 1
frac = k_clusters == 1 ? 0.0 : c / (k_clusters - 1.0) // 0 → 1
v = frac * 2 - 1 // -1 → +1
array.set(cent_rsi, c, v) // linear
array.set(cent_cci, c, math.sin(v)) // sinusoidal
array.set(cent_cmf, c, v * v * (v < 0 ? -1 : 1)) // quadratic sign-preserving
array.set(cent_mac, c, tanh(v)) // compressed
This makes initial cluster spread “random” even though true randomness is hardly achieved in pinescript.
K-Means Iterative Refinement
The algorithm repeats these steps:
(A) Assignment Step, Each bar is assigned to the nearest centroid via Euclidean distance in 4D:
distance = sqrt(dx² + dy² + dz² + dw²)
(B) Update Step, Centroids update to the mean of points assigned to them. This repeats iterations times (configurable).
LIVE REGIME CLASSIFICATION
After training, each new bar is:
Standardized using the training mean/std
Compared to all centroids
Assigned to the nearest cluster
Bar color updates based on cluster
No re-training occurs. This ensures:
No lookahead bias
Clean historical testing
Stable regimes over time
CLUSTER BEHAVIOR & TRADING LOGIC
Clusters (0, 1, 2, 3…) hold no inherent meaning. The user defines what each cluster does.
Example of custom actions:
Cluster 0 → Cash
Cluster 1 → Long
Cluster 2 → Short
Cluster 3+ → Cash (noise regime)
This flexibility means:
One trader might have cluster 0 as consolidation.
Another might repurpose it as a breakout-loading zone.
A third might ignore 3 clusters entirely.
Example on ETHUSD
Important Note:
Any change of parameters or chart timeframe or ticker can cause the “order” of clusters to change
The script does NOT assume any cluster equals any actionable bias, user decides.
PERFORMANCE METRICS & ROC TABLE
The indicator computes average 1-bar ROC for each cluster in:
Training set
Test (live) set
This helps measure:
Cluster profitability consistency
Regime forward predictability
Whether a regime is noise, trend, or reversion-biased
EQUITY SIMULATION & FEES
Designed for close-to-close realistic backtesting.
Position = cluster of previous bar
Fees applied only on regime switches. Meaning:
Staying long → no fee
Switching long→short → fee applied
Switching any→cash → fee applied
Fee input is percentage, but script already converts internally.
Disclaimers
⚠️ This indicator uses machine-learning but does not predict the future. It classifies similarity to past regimes, nothing more.
⚠️ Backtest results are not indicative of future performance.
⚠️ Clusters have no inherent “bullish” or “bearish” meaning. You must interpret them based on your testing and your own feature engineering.
Labden Predictive Kernel SFPPredictive kernel sfp indicator that uses a fuckton of math instead of typical signals to print buy and sell patterns.
MTF Scalper - alemicihanMulti-Timeframe Scalper Strategy: Aligning the Big Picture for Quick Gains
This article presents a robust futures trading strategy designed for high-frequency scalping in the crypto market. It’s built on the principle of minimizing risk by ensuring that short-term entries are always aligned with the dominant, higher-timeframe trend.
The Core Concept: Alignment is Key
A Balanced Trend Follower approach, now refined for rapid scalping, uses a Multi-Timeframe (MTF) confirmation system to filter out market noise and increase the probability of a successful trade.
The strategy operates on a Low Timeframe (LTF) chart (e.g., 3m, 5m, or 15m) but only executes trades if the direction is validated by three Higher Timeframes (HTF).
ComponentPurposeFunctionHTF (D, 4h, 1h) EMA => Trend Confirmation =>Checks if the current price is above/below all three Exponential Moving Averages (EMA 20). This provides a strong directional bias.
LTF (5m) Stochastic RSI => Momentum Entry => Generates the actual buy/sell signal by spotting a swift crossover, indicating fresh momentum in the direction of the confirmed HTF trend.
How The Signal Is Generated
Trend Alignment: The system first confirms the trend. If the price is trading above the Daily, 4-Hour, and 1-Hour EMAs, the market is deemed to be in a Strong LONG Trend. Only LONG signals are permitted.
Momentum Trigger: Once the trend is confirmed, a Long Signal is generated only when the Stochastic K-Line crosses above the D-Line, indicating a momentum shift (a pullback ending) towards the main trend direction.
Short Signal: The inverse logic applies to the Short Trend confirmation and entry signal.
Mandatory Risk Management: ATR-Based Exit
Given the high leverage nature of futures and scalping, static Stop-Loss (SL) and Take-Profit (TP) levels are inefficient. This strategy uses the Average True Range (ATR) indicator to dynamically set profit and loss targets based on current market volatility.
Stop Loss (SL): Set dynamically at 1.5 x ATR below (for long) or above (for short) the entry price. This gives the trade enough room to breathe without risking excessive capital.
Take Profit (TP): Set dynamically at 3.0 x ATR, establishing a robust Risk-to-Reward Ratio of 1:2.
Final Thoughts on Testing
This sophisticated approach combines the reliability of MTF analysis with the speed of momentum indicators. However, data analysis is key. Backtesting these parameters (EMA, ATR Multipliers, RSI/Stochastic lengths) on your chosen asset (like BTC/USDT or ETH/USDT) and timeframe is crucial to achieving optimal performance.
FVG – (auto close + age) GR V1.0FVG – Fair Value Gaps (auto close + age counter)
Short Description
Automatically detects Fair Value Gaps (FVGs) on the current timeframe, keeps them open until price fully fills the gap or a maximum bar age is reached, and shows how many candles have passed since each FVG was created.
Full Description
This indicator automatically finds and visualizes Fair Value Gaps (FVGs) using the classic 3-candle ICT logic on any timeframe.
It works on whatever timeframe you apply it to (M1, M5, H1, H4, etc.) and adapts to the current chart.
FVG detection logic
The script uses a 3-candle pattern:
Bullish FVG
Condition:
low > high
Gap zone:
Lower boundary: high
Upper boundary: low
Bearish FVG
Condition:
high < low
Gap zone:
Lower boundary: high
Upper boundary: low
Each detected FVG is drawn as a colored box (green for bullish, red for bearish in this version, but you can adjust colors in the inputs).
Auto-close rules
An FVG remains on the chart until one of the following happens:
Full fill / mitigation
A bullish FVG closes when any candle’s low goes down to or below the lower boundary of the gap.
A bearish FVG closes when any candle’s high goes up to or above the upper boundary of the gap.
Maximum bar age reached
Each FVG has a maximum lifetime measured in candles.
When the number of candles since its creation reaches the configured maximum (default: 200 bars), the FVG is automatically removed even if it has not been fully filled.
This keeps the chart cleaner and prevents very old gaps from cluttering the view.
Age counter (labels inside the boxes)
Inside every FVG box there is a small label that:
Shows how many bars have passed since the FVG was created.
Moves together with the right edge of the box and stays vertically centered in the gap.
This makes it easy to distinguish fresh gaps from older ones and prioritize which zones you want to pay attention to.
Inputs
FVG color – Main fill color for all FVG boxes.
Show bullish FVGs – Turn bullish gaps on/off.
Show bearish FVGs – Turn bearish gaps on/off.
Max bar age – Maximum number of candles an FVG is allowed to stay on the chart before it is removed.
Usage
Works on any symbol and any timeframe.
Can be combined with your own ICT / SMC concepts, order blocks, session ranges, market structure, etc.
You can also choose to only display bullish or only bearish FVGs depending on your directional bias.
Disclaimer
This script is for educational and informational purposes only and is not financial advice. Always do your own research and use proper risk management when trading.
Volatility Signal-to-Noise Ratio🙏🏻 this is VSNR: the most effective and simple volatility regime detector & automatic volatility threshold scaler that somehow no1 ever talks about.
This is simply an inverse of the coefficient of variation of absolute returns, but properly constructed taking into account temporal information, and made online via recursive math with algocomplexity O(1) both in expanding and moving windows modes.
How do the available alternatives differ (while some’re just worse)?
Mainstream quant stat tests like Durbin-Watson, Dickey-Fuller etc: default implementations are ALL not time aware. They measure different kinds of regime, which is less (if at all) relevant for actual trading context. Mix of different math, high algocomplexity.
The closest one is MMI by financialhacker, but his approach is also not time aware, and has a higher algocomplexity anyways. Best alternative to mine, but pls modify it to use a time-weighted median.
Fractal dimension & its derivatives by John Ehlers: again not time aware, very low info gain, relies on bar sizes (high and lows), which don’t always exist unlike changes between datapoints. But it’s a geometric tool in essence, so this is fundamental. Let it watch your back if you already use it.
Hurst exponent: much higher algocomplexity, mix of parametric and non-parametric math inside. An invention, not a math entity. Again, not time aware. Also measures different kinds of regime.
How to set it up:
Given my other tools, I choose length so that it will match the amount of data that your trading method or study uses multiplied by ~ 4-5. E.g if you use some kind of bands to trade volatility and you calculate them over moving window 64, put VSNR on 256.
However it depends mathematically on many things, so for your methods you may instead need multipliers of 1 or ~ 16.
Additionally if you wanna use all data to estimate SNR, put 0 into length input.
How to use for regime detection:
First we define:
MR bias: mean reversion bias meaning volatility shorts would work better, fading levels would work better
Momo bias: momentum bias meaning volatility longs would work better, trading breakouts of levels would work better.
The study plots 3 horizontal thresholds for VSNR, just check its location:
Above upper level: significant Momo bias
Above 1 : Momo bias
Below 1 : MR bias
Below lower level: significant MR bias
Take a look at the screenshots, 2 completely different volatility regimes are spotted by VSNR, while an ADF does not show different regime:
^^ CBOT:ZN1!
^^ INDEX:BTCUSD
How to use as automatic volatility threshold scaler
Copy the code from the script, and use VSNR as a multiplier for your volatility threshold.
E.g you use a regression channel and fade/push upper and lower thresholds which are RMSEs multiples. Inside the code, multiply RMSE by VSNR, now you’re adaptive.
^^ The same logic as when MM bots widen spreads with vola goes wild.
How it works:
Returns follow Laplace distro -> logically abs returns follow exponential distro , cuz laplace = double exponential.
Exponential distro has a natural coefficient of variation = 1 -> signal to noise ratio defined as mean/stdev = 1 as well. The same can be said for Student t distro with parameter v = 4. So 1 is our main threshold.
We can add additional thresholds by discovering SNRs of Student t with v = 3 and v = 5 (+- 1 from baseline v = 4). These have lighter & heavier tails each favoring mean reversion or momentum more. I computed the SNR values you see in the code with mpmath python module, with precision 256 decimals, so you can trust it I put it on my momma.
Then I use exponential smoothing with properly defined alphas (one matches cumulative WMA and another minimizes error with WMA in moving window mode) to estimate SNR of abs returns.
…
Lightweight huh?
∞
Pair Cointegration & Static Beta Analyzer (v6)Pair Cointegration & Static Beta Analyzer (v6)
This indicator evaluates whether two instruments exhibit statistical properties consistent with cointegration and tradable mean reversion.
It uses long-term beta estimation, spread standardization, AR(1) dynamics, drift stability, tail distribution analysis, and a multi-factor scoring model.
1. Static Beta and Spread Construction
A long-horizon static beta is estimated using covariance and variance of log-returns.
This beta does not update on every bar and is used throughout the entire model.
Beta = Cov(r1, r2) / Var(r2)
Spread = PriceA - Beta * PriceB
This “frozen” beta provides structural stability and avoids rolling noise in spread construction.
2. Correlation Check
Log-price correlation ensures the instruments move together over time.
Correlation ≥ 0.85 is required before deeper cointegration diagnostics are considered meaningful.
3. Z-Score Normalization and Distribution Behavior
The spread is standardized:
Z = (Spread - MA(Spread)) / Std(Spread)
The following statistical properties are examined:
Z-Mean: Should be close to zero in a stationary process
Z-Variance: Measures amplitude of deviations
Tail Probability: Frequency of |Z| being larger than a threshold (e.g. 2)
These metrics reveal whether the spread behaves like a mean-reverting equilibrium.
4. Mean Drift Stability
A rolling mean of the spread is examined.
If the rolling mean drifts excessively, the spread may not represent a stable long-term equilibrium.
A normalized drift ratio is used:
Mean Drift Ratio = Range( RollingMean(Spread) ) / Std(Spread)
Low drift indicates stable long-run equilibrium behavior.
5. AR(1) Dynamics and Half-Life
An AR(1) model approximates mean reversion:
Spread(t) = Phi * Spread(t-1) + error
Mean reversion requires:
0 < Phi < 1
Half-life of reversion:
Half-life = -ln(2) / ln(Phi)
Valid half-life for 10-minute bars typically falls between 3 and 80 bars.
6. Composite Scoring Model (0–100)
A multi-factor weighted scoring system is applied:
Component Score
Correlation 0–20
Z-Mean 0–15
Z-Variance 0–10
Tail Probability 0–10
Mean Drift 0–15
AR(1) Phi 0–15
Half-Life 0–15
Score interpretation:
70–100: Strong Cointegration Quality
40–70: Moderate
0–40: Weak
A pair is classified as cointegrated when:
Total Score ≥ Threshold (default = 70)
7. Main Cointegration Panel
Displays:
Static beta
Log-price correlation
Z-Mean, Z-Variance, Tail Probability
Drift Ratio
AR(1) Phi and Half-life
Composite score
Overall cointegration assessment
8. Beta Hedge Position Sizing (Average-Price Based)
To provide a more stable hedge ratio, hedge sizing is computed using average prices, not instantaneous prices:
AvgPriceA = SMA(PriceA, N)
AvgPriceB = SMA(PriceB, N)
Required B per 1 A = Beta * (AvgPriceA / AvgPriceB)
Using averaged prices results in a smoother, more reliable hedge ratio, reducing noise from bar-to-bar volatility.
The panel displays:
Required B security for 1 A security (average)
This represents the beta-neutral quantity of B required to hedge one unit of A.
Overview of Classical Stationarity & Cointegration Methods
The principal econometric tools commonly used in assessing stationarity and cointegration include:
Augmented Dickey–Fuller (ADF) Test
Phillips–Perron (PP) Test
KPSS Test
Engle–Granger Cointegration Test
Phillips–Ouliaris Cointegration Test
Johansen Cointegration Test
Since these procedures rely on regression residuals, matrix operations, and distribution-based critical values that are not supported in TradingView Pine Script, a practical multi-criteria scoring approach is employed instead. This framework leverages metrics that are fully computable in Pine and offers an operational proxy for evaluating cointegration-like behavior under platform constraints.
References
Engle & Granger (1987), Co-integration and Error Correction
Poterba & Summers (1988), Mean Reversion in Stock Prices
Vidyamurthy (2004), Pairs Trading
Explanation structured with assistance from OpenAI’s ChatGPT
Regards.
Z-Score Regime DetectorThe Z-Score Regime Detector is a statistical market regime indicator that helps identify bullish and bearish market conditions based on normalized momentum of three core metrics:
- Price (Close)
- Volume
- Market Capitalization (via CRYPTOCAP:TOTAL)
Each metric is standardized using the Z-score over a user-defined period, allowing comparison of relative extremes across time. This removes raw value biases and reveals underlying momentum structure.
📊 How it Works
- Z-Score: Measures how far a current value deviates from its average in terms of standard deviations.
- A Bullish Regime is identified when both price and market cap Z-scores are above the volume Z-score.
- A Bearish Regime occurs when price and market cap Z-scores fall below volume Z-score.
Bias Signal:
- Bullish Bias = Price Z-score > Market Cap Z-score
- Bearish Bias = Market Cap Z-score > Price Z-score
This provides a statistically consistent framework to assess whether the market is flowing with strength or stress.
✅ Why This Might Be Effective
- Normalizing the data via Z-scores allows comparison of diverse metrics on a common scale.
- Using market cap offers broader insight than price alone, especially for crypto.
- Volume as a reference threshold helps identify accumulation/distribution regimes.
- Simple regime logic makes it suitable for trend confirmation, filtering, or position biasing in systems.
⚠️ Disclaimer
This script is for educational purposes only and should not be considered financial advice. Always perform your own research and risk management. Past performance is not indicative of future results. Use at your own discretion.
P/E, EPS, Price & Price-to-Sales DisplayPrice to earning ratio,
EPS,
Price ANd
Price-to-Sales Display
ATR multiple from High & LowA simple numerical indicator measuring ATR multiple from recent 252 days high and low.
ATR multiples from high (and low) are used as a base in many systematic trading and trend following systems. As an example many systems buy after a 2.5–4 ATR multiple pullback in a strong stock if the regime allows it. This would then be paired with an entry tactic, for example buy as it recaptures the a pivot within the upper range, a MA or breaks out again after this mid term pullback/shakeout.
This indicator uses a function which captures the recent high and low no matter if we have 252 bars or not, which is not how standard high/low works in Tradingview. This means it also works with recent IPO:s.
I prefer to overlay the indicator in one of the lower panes, for example the volume pane and then right click on the indicator and select Pin to scale > No scale (fullscreen).
HPAS mean reversion strategy testerTakes Krown HPAS values hardcoded and simulates longs and short with configurable standard deviation multiplier TP/SL. Best used on lower timeframes
BTC Macro Heatmap (Fed Cuts & Hikes)🔴 1. Red line – Fed Funds Rate (policy trend)
This line tells you what stage of the monetary cycle we’re in.
Rising red line = the Fed is hiking → liquidity is tightening → money leaves risk assets like BTC.
Flat = pause → markets start pricing in the next move (often sideways BTC).
Falling = easing / cutting → liquidity returns → bullish environment builds.
The rate of change matters more than the level. When the slope turns down, capital starts seeking yield again — BTC benefits first because it’s the most volatile asset.
💚 2. Dim green zones – detected cuts
These are data-based easing events pulled directly from FRED.
They show when the actual effective rate began moving down, not necessarily the exact meeting day.
Think of them as the Fed’s “foot off the brake” — that’s when risk markets begin responding.
🟩 3. Bright green lines – official FOMC cuts
These are the real policy shifts — the Fed formally changed direction.
After these appear, BTC historically transitions from accumulation → markup phase.
Look at 2020: the bright green lines came right before BTC’s full reversal.
You’re seeing the same thing now with the 2025 lines — early-stage liquidity return.
🟠 4. Orange line – DXY (US Dollar Index)
DXY is your “risk-off” gauge.
When DXY rises, global investors flock to dollars → BTC usually weakens.
When DXY peaks and starts dropping, it means risk appetite is coming back → BTC rallies.
BTC and DXY are inversely correlated about 70–80% of the time.
Watch for DXY lower highs after rate cuts — that’s your macro confirmation of a BTC-friendly environment.
🟦 5. Aqua line – BTC (normalized)
You’re not looking for the price itself here, but its shape relative to DXY and the Fed line.
When BTC curls up as the red line flattens and DXY rolls over → that’s historically the start of a major bull phase.
BTC tends to bottom before the first cut and explode once DXY decisively breaks down.
🧠 Putting it together
Here’s the rhythm this chart shows over and over:
Fed hikes (red line rising) → BTC weakens, DXY climbs.
Fed pauses (red line flat) → BTC stops falling, DXY tops.
Fed cuts (dim + bright green) → DXY turns down → BTC begins long recovery → bull cycle starts.
Bar Count Per SessionCount K bars based on sessions, supporting at most 3 sessions
- Customize the session's timezone and period
- Set the steps between each number
- Use with the built-in `Trading Session` is a great convenience
Intraday Close Price VariationShows in the graph the intraday variation, being useful when using the replay feature.
RLSR logreg_support_libLibrary "logreg_support_lib"
sigmoid(z)
Parameters:
z (float)
prng01(seed1, seed2)
Parameters:
seed1 (float)
seed2 (float)
normalize(value, minval, maxval)
Parameters:
value (float)
minval (float)
maxval (float)
calcpercentilefast(arr, percentile)
Parameters:
arr (array)
percentile (float)
calcpercentile_series_sampled(s, length, percentile, stride)
Parameters:
s (float)
length (int)
percentile (float)
stride (int)
calcRangeWithLog(value, minval, maxval, uselog)
Parameters:
value (float)
minval (float)
maxval (float)
uselog (bool)
calcMomentumAdvanced(src, length, momType)
Parameters:
src (float)
length (simple int)
momType (string)
normalizeMomentumByType(rawMom, momType, momMin, momMax, momNorm)
Parameters:
rawMom (float)
momType (string)
momMin (float)
momMax (float)
momNorm (float)
normalizeMomentumByTypeExt(rawMom, momType, momMin, momMax, momNorm, bouncingdecay)
Parameters:
rawMom (float)
momType (string)
momMin (float)
momMax (float)
momNorm (float)
bouncingdecay (float)
calcrollingstddev(src, length)
Parameters:
src (float)
length (int)
addlog(buffer, level, msg)
Parameters:
buffer (string)
level (string)
msg (string)
calcfeaturecorrelation(x1, x2)
Parameters:
x1 (array)
x2 (array)
calcnoiseratio(src, lookback)
Parameters:
src (float)
lookback (int)
calccompatibilityscore(x1, x2)
Parameters:
x1 (array)
x2 (array)
getfuturereturn(offset, returnlookback)
Parameters:
offset (int)
returnlookback (int)
calculatema(source, length, matype)
Parameters:
source (float)
length (simple int)
matype (string)
adaptive_trigger_for_source(src, enabled, freeze, lookback, threshold, volahistory)
Parameters:
src (float)
enabled (bool)
freeze (bool)
lookback (int)
threshold (float)
volahistory (array)
checkadaptivetrigger5(s1, enabled1, freeze1, hist1, s2, enabled2, freeze2, hist2, s3, enabled3, freeze3, hist3, s4, enabled4, freeze4, hist4, s5, enabled5, freeze5, hist5, lookback, threshold)
Parameters:
s1 (float)
enabled1 (bool)
freeze1 (bool)
hist1 (array)
s2 (float)
enabled2 (bool)
freeze2 (bool)
hist2 (array)
s3 (float)
enabled3 (bool)
freeze3 (bool)
hist3 (array)
s4 (float)
enabled4 (bool)
freeze4 (bool)
hist4 (array)
s5 (float)
enabled5 (bool)
freeze5 (bool)
hist5 (array)
lookback (int)
threshold (float)
ring_start_index(rb_write_idx, rb_count, rb_cap)
Parameters:
rb_write_idx (int)
rb_count (int)
rb_cap (int)
reversalLibrary "reversals"
psar(af_start, af_increment, af_max)
Calculates Parabolic Stop And Reverse (SAR)
Parameters:
af_start (simple float) : Initial acceleration factor (Wilder's original: 0.02)
af_increment (simple float) : Acceleration factor increment per new extreme (Wilder's original: 0.02)
af_max (simple float) : Maximum acceleration factor (Wilder's original: 0.20)
Returns: SAR value (stop level for current trend)
fractals()
Detects Williams Fractal patterns (5-bar pattern)
Returns: Tuple with fractal values (na if no fractal)
swings(lookback, source_high, source_low)
Detects swing highs and swing lows using lookback period
Parameters:
lookback (simple int) : Number of bars on each side to confirm swing point
source_high (float) : Price series for swing high detection (typically high)
source_low (float) : Price series for swing low detection (typically low)
Returns: Tuple with swing point values (na if no swing)
pivot(tf)
Calculates classic/standard/floor pivot points
Parameters:
tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
Returns: Tuple with pivot levels
pivotcam(tf)
Calculates Camarilla pivot points with 8 levels for short-term trading
Parameters:
tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
Returns: Tuple with pivot levels
pivotdem(tf)
Calculates d-mark pivot points with conditional open/close logic
Parameters:
tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
Returns: Tuple with pivot levels (only 3 levels)
pivotext(tf)
Calculates extended traditional pivot points with R4-R5 and S4-S5 levels
Parameters:
tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
Returns: Tuple with pivot levels
pivotfib(tf)
Calculates Fibonacci pivot points using Fibonacci ratios
Parameters:
tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
Returns: Tuple with pivot levels
pivotwood(tf)
Calculates Woodie's pivot points with weighted closing price
Parameters:
tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
Returns: Tuple with pivot levels
Weekday Close vs Open — Last N (per weekday)# Weekday Close vs Open - Last N Occurrences
This indicator distills every weekday's historical open-to-close behavior into a compact table so you can see how "typical" the current session is before the day even closes. It runs independently of your chart timeframe by pulling daily OHLCV data under the hood, tracking the last **N** completed occurrences for each weekday, and refreshing only when a daily bar closes. On daily charts you can also shade every past bar that matches today's weekday (excluding the in-progress session) to reinforce the pattern visually while the table remains non-repainting.
## What It Shows
- **Win/Loss/Tie counts** - how many of the last `N` occurrences closed above the open (wins), below (losses), or inside the tie threshold you define as "flat".
- **Win % heatmap** - the win column is color-coded (deep green > deep red) so you immediately recognize strong or weak weekdays.
- **Advanced metrics (optional)** - average daily volume plus the average percentage excursion above/below the open (`AvgUp%`, `AvgDn%`) for that weekday.
- **Totals row** - aggregates every weekday into one row to estimate overall hit rate and average stats across the entire data set.
- **Weekday shading (optional)** - on daily charts you can tint every bar that matches today's weekday (all Mondays, all Fridays, etc.) for instant pattern recognition.
## How It Works
1. The script requests daily OHLCV data (non-repainting) regardless of the chart timeframe.
2. When a new daily bar confirms, it packs that day's data into one of seven arrays (one per weekday). Each day contributes five floats (O/H/L/C/V) so trimming and statistics stay in lockstep.
3. A helper function (`f_dayMetrics`) scans daily history to compute average volume, average excursion above/below the open, and win/loss/tie counts for the requested weekday.
4. The table populates on the last bar of the chart session, respecting your advanced/totals toggles and keeping text at `size.normal`.
## Reading the Table
- **Win/Loss/Tie columns**: raw counts taken from your chosen `N`.
- **Win %***: excludes ties from the denominator so it reflects only decisive closes.
- **AvgUp% / AvgDn%**: typical intraday extension (high vs open, open vs low) in percent.
- **Avg Vol**: arithmetic mean of daily volume for that weekday.
- **TOTAL row**: provides a global win rate plus volume/up/down averages weighted by how many samples each weekday contributed.
## Practical Uses
- Spot weekdays that historically trend higher or lower before entering a trade.
- Compare current price action against the typical intraday range (`AvgUp%` vs today's move).
- Filter mean-reversion vs breakout setups based on the most reliable weekday patterns.
- Quickly gauge whether today is behaving "in character" by referencing the highlighted row or the optional whole-chart weekday shading.
> **Tip:** Use smaller `N` values (e.g., 10-20) for adaptive, recent behavior and larger values (50+) to capture longer-term seasonality. Tighten the tie threshold if you want almost every candle to register as win/loss, or widen it to focus only on meaningful moves.
Forward Returns – (Next Month Start)This indicator calculates 1-month, 3-month, 6-month, and 12-month forward returns starting from the first trading day of the month following a defined price event.
A price event occurs when the selected asset drops below a user-defined threshold over a chosen timeframe (Day, Week, or Month).
For monthly conditions, the script evaluates the entire performance of the previous calendar month and triggers the event only at the first trading session of the next month, ensuring accurate forward-return alignment with historical monthly cycles.
The forward returns for each detected event are displayed in a paginated performance table, allowing users to navigate through large datasets using a page selector. Each page includes:
Entry Date
Forward returns (1M, 3M, 6M, 12M)
Average forward return
Win rate (percentage of positive outcomes)
This tool is useful for studying historical performance after major drawdowns, identifying seasonal patterns, and building evidence-based risk-management or timing models.
SVE Daily ATR + SDTR Context BandsSVE Daily ATR + SDTR Context Bands is a free companion overlay from The Volatility Engine™ ecosystem.
It plots daily ATR-based expansion levels and a Standardized Deviation Threshold Range (SDTR) to give traders a clean, quantitative view of where intraday price sits relative to typical daily movement and volatility extremes.
This module is designed as an SVE-compatible context layer—using discrete, RTH-aligned daily zones, expected-move bands, and a standardized volatility shell—so traders can build situational awareness even without the full SPX Volatility Engine™ (SVE).
It does not generate trade signals.
Its sole purpose is to provide a clear volatility framework you can combine with your own structure, Fibonacci, or signal logic (including SVE, if you use it).
🔍 What It Shows
* Daily ATR Bands (expHigh / expLow)
- Expected high/low based on smoothed daily ATR
- Updates at the RTH open
* Daily SDTR Bands (expHighSDTR / expLowSDTR)
- Standard deviation threshold range for volatility extremes
- Helps identify overextended conditions
Discrete RTH-aligned Zones
- Bands reset cleanly at each RTH session
No continuous carry-over from prior days
Daily ATR & SDTR stats label
Quick-reference box showing current ATR and SDTR values
🎯 Purpose
This tool helps traders:
- Gauge intraday context relative to expected daily movement
- Assess volatility state (quiet, normal, expanded, extreme)
- Identify likely exhaustion or expansion zones
- Frame intraday price action inside daily volatility rails
- Support decision-making with objective context rather than emotion
It complements any strategy and works on any intraday timeframe.
⚙️ Inputs
- ATR Lookback (default: 20 days)
- RTH Session Times
- SDTR Lookback
- Show/Hide Daily Stats Label
🧩 Part of the SVE Ecosystem
This module is part of the broader SPX Volatility Engine™ framework.
The full SVE system includes:
- Composite signal scoring
- Volatility compression logic
- Histogram slope and momentum analysis
- Internals (VIX / VVIX / TICK)
- Structural zone awareness
- Real-time bias selection
- High-clarity decision support
⚠️ Disclaimer
This tool is provided for educational and informational purposes only.
No performance claims are made or implied.
Not investment advice.
Static Beta for Pair and Quant Trading A beta coefficient shows the volatility of an individual stock compared to the systematic risk of the entire market. Beta represents the slope of the line through a regression of data points. In finance, each point represents an individual stock's returns against the market.
Beta effectively describes the activity of a security's returns as it responds to swings in the market. It is used in the capital asset pricing model (CAPM), which describes the relationship between systematic risk and expected return for assets. CAPM is used to price risky securities and to estimate the expected returns of assets, considering the risk of those assets and the cost of capital.
Calculating Beta
A security's beta is calculated by dividing the product of the covariance of the security's returns and the market's returns by the variance of the market's returns over a specified period. The calculation helps investors understand whether a stock moves in the same direction as the rest of the market. It also provides insights into how volatile—or how risky—a stock is relative to the rest of the market.
For beta to provide useful insight, the market used as a benchmark should be related to the stock. For example, a bond ETF's beta with the S&P 500 as the benchmark would not be helpful to an investor because bonds and stocks are too dissimilar.
Beta Values
Beta equal to 1: A stock with a beta of 1.0 means its price activity correlates with the market. Adding a stock to a portfolio with a beta of 1.0 doesn’t add any risk to the portfolio, but it doesn’t increase the likelihood that the portfolio will provide an excess return.
Beta less than 1: A beta value less than 1.0 means the security is less volatile than the market. Including this stock in a portfolio makes it less risky than the same portfolio without the stock. Utility stocks often have low betas because they move more slowly than market averages.
Beta greater than 1: A beta greater than 1.0 indicates that the security's price is theoretically more volatile than the market. If a stock's beta is 1.2, it is assumed to be 20% more volatile than the market. Technology stocks tend to have higher betas than the market benchmark. Adding the stock to a portfolio will increase the portfolio’s risk, but may also increase its return.
Negative beta: A beta of -1.0 means that the stock is inversely correlated to the market benchmark on a 1:1 basis. Put options and inverse ETFs are designed to have negative betas. There are also a few industry groups, like gold miners, where a negative beta is common.
LET'S START
Now I'll give my own definition.
Beta:
If we assume market caps are equal ,
it is an indicator that shows how much of the second instrument we should buy if we buy one of the first, taking into account the price volatility of two instruments.
But if the market caps are not equal:
For example, the ETF for A is $300.
The ETF for B is $600.
If static beta predicted by this script is 0.5:
300 * 1 * a = 600 * 0.5 * b
Then we should use 1 b for 1 a.
(Long a and short b or vice versa )
So, we can try pair trading for a/b or a-b.
However, these values are generally close to each other, such as 0.8 and 0.93. However, the closer we can adjust our lot purchases to bring the double beta to a value closer to 1, the higher the hedge ratio will be.
Large commercials use dynamic betas, which are updated periodically, in addition to static betas
However, scaling this is very difficult for individual investors with limited investment tools.
But a static beta of 5,000 bars is still much better than not considering any beta at all.
Note: The presence of a beta value for two instruments does not necessarily mean they can be included in pair trading.
It is also important (%99) to consider historically very high correlations and cointegration relationships, as well as the compatibility of security structures.
Note 2 : This script is designed for low timeframes.
Do not use betas from different timeframes.
Beta dynamics are different for each timeframe.
Note 3 : I created this script with the help of ChatGPT.
Source for beta definition ( ) :
www.investopedia.com
Regards.
Breakouts & Pullbacks [Trendoscope®]🎲 Breakouts & Pullbacks - All-Time High Breakout Analyzer
Probability-Based Post-Breakout Behavior Statistics | Real-Time Pullback & Runup Tracker
A professional-grade Pine Script v6 indicator designed specifically for analyzing the historical and real-time behavior of price after strong All-Time High (ATH) breakouts. It automatically detects significant ATH breakouts (with configurable minimum gap), measures the depth and duration of pullbacks, the speed of recovery, and the subsequent run-up strength — then turns all this data into easy-to-read statistical probabilities and percentile ranks.
Perfect for swing traders, breakout traders, and anyone who wants objective, data-driven insight into questions like:
“How deep do pullbacks usually get after a strong ATH breakout?”
“How many bars does it typically take to recover the breakout level?”
“What is the median run-up after recovery?”
“Where is the current pullback or run-up relative to historical ones?”
🎲 Core Concept & Methodology
Indicator is more suitable for indices or index ETFs that generally trade in all-time highs however subjected to regular pullbacks, recovery and runups.
For every qualified ATH breakout, the script identifies 4 distinct phases:
Breakout Point – The exact bar where price closes above the previous ATH after at least Minimum Gap bars.
Pullback Phase – From breakout candle high → lowest low before price recovers back above the breakout level.
Recovery Phase – From the pullback low → the bar where price first trades back above the original breakout price.
Post-Recovery Run-up Phase – From the recovery point → current price (or highest high achieved so far).
Each completed cycle is stored permanently and used to build a growing statistical database unique to the loaded chart and timeframe.
🎲 Visual Elements
Yellow polyline triangle connecting Previous ATH / Pullback point(start), New ATH Breakout point (end), Recovery point (lowest pullback price), and extends to recent ATH price.
Small green label at the pullback low showing detailed tooltip on hover with all measured values
Clean, color-coded statistics table in the top-right corner (visible only on the last bar)
Powerful Statistics Table – The Heart of the Indicator
The table constantly compares the current situation against all past qualified breakouts and shows details about pullbacks, and runups that help us calculate the probability of next pullback, recovery or runup.
🎲 Settings & Inputs
Minimum Gap
The minimum number of bars that must pass between breaking a new ATH and the previous one.
Higher values = stricter filter → only the strongest, cleanest breakouts are counted.
Lower values = more data points (useful on lower timeframes or very trending instruments).
Recommendation:
Daily charts: 30–50
4H charts: 40–80
1H charts: 100–200
🎲 How to Use It in Practice
This indicator helps investors to understand when to be bullish, bearish or cautious and anticipate regular pullbacks, recovery of markets using quantitative methods.
The indicator does not generate buy/sell signals. However, helps traders set expectations and anticipate market movements based on past behavior.
Pivot Fib 4H — EAStrategy uses the pivot standard to open position, it has well define entry and exit point with SL, it also has a proper money management plan, maximum 4 trades a day, each trade risk 0.5% of the account, I have it EA version of it also.






















