Trend Survival MatrixMost trend tools tell you which way the trend is going, but not how late you are in it. The Trend Survival Matrix answers that directly. It tracks the live trend across three timescales (short, medium, and long EMA regimes) and measures each one's age — the number of bars since it last flipped. Then, from every completed trend in the chart's history, it builds an empirical run-length distribution and estimates a conditional survival probability: the odds the current trend lasts at least 5, 10, or 20 more bars given how long it has already run. Crucially, those odds are conditioned on the volatility regime each historical run was born in (low / normal / high ATR-percentile buckets), so a long, calm trend isn't judged against runs that formed in chaotic conditions.
The panel reads left to right: direction, current age, the typical (median) run length for that regime, survival odds at each horizon, and a maturity state — FRESH, HEALTHY, MATURING, EXTENDED, or EXHAUSTION — driven by an overextension z-score (how many standard deviations the current age sits above the historical mean). On the chart, a ribbon between the primary EMA pair tints by direction and fades as survival decays, so a durable trend looks solid while a fragile, overextended one visibly thins out. Markers flag new trends, and a once-per-run label warns when survival drops below your threshold — useful for deciding whether to add, tighten stops, or prepare to fade.
Everything is empirical and inspectable — the survival figures come straight from the instrument's own history, not a black box or preset numbers. The engine is fully non-repainting (state advances only on confirmed bars, with no higher-timeframe requests), so the readings stay stable when you switch chart timeframes. Where there aren't enough historical samples to condition on, the panel honestly reports LOW DATA and a confidence flag rather than showing a made-up probability. Works on any symbol and timeframe; tune the EMA lengths, horizons, and volatility buckets to your market. 指标

指标

Market Regime EngineMarket Regime Engine
Market Regime Engine is a multi-layer market-state and historical research framework designed to identify what the market is doing, where it is in the broader market cycle, how mature the current regime is, and how similar historical environments have behaved afterward.
Rather than defining trend from a single indicator, the engine processes price, volume, volatility, momentum, and market structure through several independent layers and combines them into a standardized:
Regime Score: -100 → +100
The architecture is:
Price + Volume → Fast Engine → Structure Engine → Context Engine → Regime Score → Regime + Stage → Regime Age → Historical Cohort
The objective is to remain responsive to genuine changes in market behavior without allowing a single moving-average cross, high-volume candle, or isolated structural signal to completely change the market classification.
Fast Engine
The Fast Engine is the most responsive part of the model and receives substantial weight in the final score.
It analyzes:
20 SMA location — whether price is above or below its short-term trend mean.
20 SMA slope — whether the trend itself is rising, falling, or flattening.
Displacement — candle-body expansion normalized by ATR.
Relative Volume (RVOL) — determines whether directional movement is being accompanied by meaningful participation.
The combination of price relative to the 20 SMA, SMA slope, displacement, and volume provides the first indication that market behavior is changing.
ATR normalization allows these measurements to adapt across instruments and volatility regimes.
Structure Engine
The Structure Engine asks whether price structure confirms what the Fast Engine is detecting.
It tracks:
Swing highs
Swing lows
Higher highs
Higher lows
Lower highs
Lower lows
Break of Structure (BOS)
Change of Character (CHoCH)
A BOS identifies a meaningful break of established swing structure and receives one of the largest individual weights in the model.
A CHoCH identifies a potential change in the prevailing structural direction and is particularly useful when an established trend begins deteriorating.
This creates an important distinction between simply moving above or below the 20 SMA and actually changing market structure.
Context Engine
The Context Engine determines whether the surrounding environment supports the signals coming from price and structure.
It incorporates:
ATR — normalizes price movement and allows the engine to compare displacement and SMA distance across changing volatility environments.
ADX/DMI — measures trend strength and directional confirmation. ADX itself does not determine whether the market is bullish or bearish; it strengthens an already established directional condition.
Fair Value Gaps (FVG) — identify recent price imbalances that provide additional directional context.
Order Blocks — identify recent opposing candles preceding meaningful displacement.
FVG and Order Block information intentionally receive relatively small weights because they are treated as contextual evidence rather than primary directional signals.
Regime Score
All of these components feed into a single standardized score:
-100 ←──────── 0 ────────→ +100
Negative values represent increasing bearish alignment, while positive values represent increasing bullish alignment.
The full weighting framework is:
Component Maximum Weight
Price vs. 20 SMA ±15
20 SMA Slope ±15
Relative Volume ±10
Displacement ±10
Swing Structure ±10
Break of Structure ±20
CHoCH ±10
ADX/DMI ±5
FVG ±2.5
Order Block ±2.5
Maximum Score ±100
This hierarchy is intentional.
The engine places greater importance on price, the 20 SMA, volume, displacement and structural breaks, while FVGs and Order Blocks act as secondary confirmation.
Regime Classification
The Regime Score is translated into five market states:
Strong Bull — broad bullish alignment with strong directional confirmation.
Bull — bullish evidence dominates, but the environment is not strong enough to qualify as Strong Bull.
Range / Neutral — directional evidence is weak, balanced, or conflicting.
Bear — bearish evidence dominates.
Strong Bear — broad bearish alignment with strong downside confirmation.
A confirmation mechanism prevents every short-lived fluctuation from changing the official regime.
For example, price briefly crossing below a rising 20 SMA does not automatically terminate a Bull regime. Other components must deteriorate sufficiently for the aggregate score to confirm a meaningful transition.
This provides the responsiveness of a fast indicator without making the classification excessively sensitive to noise.
Regime vs. Market Stage
One of the most important features of the full engine is that Regime and Stage are separate calculations.
Regime = tactical market condition
Regime answers:
What is the market doing right now?
It is relatively fast and responsive.
Stage = structural market cycle
Stage answers:
Where is the market within the broader trend cycle?
The model uses four stages:
Stage 1 — Base / Accumulation
Typically characterized by flattening trend, weaker ADX, overlapping price structure, and stabilization following a bearish environment.
Stage 2 — Markup
Characterized by a rising 20 SMA, bullish structure, price above the trend mean, structural upside progression and strengthening trend conditions.
Stage 3 — Distribution
Represents deterioration following a bullish environment. The 20 SMA may flatten, bullish structure begins failing, lower highs may develop, and bearish CHoCH can signal that the previous advance is losing control.
Stage 4 — Markdown
Characterized by a falling 20 SMA, bearish structure, price below the trend mean and established downside progression.
Because Stage and Regime are independent, the model can recognize transitions such as:
Strong Bull / Stage 2 → Bull / Stage 2 → Range / Stage 2 → Range / Stage 3 → Bear / Stage 3 → Bear / Stage 4
This provides considerably more information than simply labeling every bar "uptrend" or "downtrend."
Regime Age
Once a confirmed regime begins, the engine counts how many bars that regime has survived.
This produces Regime Age.
For example:
Bull — Age 4
Bull — Age 8
Bull — Age 13
Bull — Age 21
The numbers 8, 13 and 21 do not determine the regime or Stage.
They are strictly research checkpoints.
A market does not become more bullish because it reaches Age 13, nor does it become bearish because it reaches Age 21.
Instead, regime age allows the model to investigate whether the statistical behavior of a market changes as a regime matures.
Historical Cohort Engine
The full Market Regime Engine extends beyond classification by maintaining a historical cohort research layer.
At the designated regime-age checkpoints:
8 bars
13 bars
21 bars
the engine studies subsequent market behavior over:
5 bars
10 bars
20 bars
The research layer can evaluate characteristics such as:
Continuation probability
Average forward return
Historical sample size
Direction-adjusted performance
The larger framework can also be extended to measure:
Median return
Maximum Favorable Excursion (MFE)
Maximum Adverse Excursion (MAE)
Regime survival rate
Regime failure rate
Probability of a new high or low
Probability of transitioning into another regime
This creates a distinction between classification and expectancy.
The Regime Engine tells you:
What environment are we in?
The Historical Cohort Engine asks:
What has historically happened after environments like this?
Importantly, historical cohort statistics do not feed back into the Regime Score. They remain an independent research layer.
Distance From the 20 SMA
The full engine also measures price's distance from its 20 SMA in ATR units:
(Price − 20 SMA) / ATR
This provides information that a simple Bull/Bear classification cannot.
For example, two markets might both have a +55 Bull Regime Score, but one could be:
0.30 ATR above its 20 SMA
while the other is:
2.20 ATR above its 20 SMA.
The directional environment may be similar, but the second market is substantially more extended.
SMA distance is therefore treated primarily as location information rather than additional directional points, helping avoid double-counting the same trend information.
Full Dashboard
The larger version exposes the internal workings of the engine rather than displaying only the final regime.
The dashboard reports:
Current Regime
Regime Score
Market Stage
Regime Age
Price vs. 20 SMA
SMA slope
RVOL
Displacement
BOS
CHoCH
ADX
FVG
Order Block context
ATR-normalized SMA distance
5-bar historical cohort results
10-bar historical cohort results
20-bar historical cohort results
This makes the indicator transparent: instead of simply being told that the market is Bullish, the user can see why the model reached that conclusion.
Example
Suppose the dashboard reports:
Regime: BULL
Score: +32.5
Stage: Stage 2 — Markup
Age: 9 bars
with:
Price above 20 SMA: +15
Rising SMA: +15
RVOL: 0
Displacement: 0
BOS: 0
CHoCH: 0
ADX: 0
Bullish FVG: +2.5
The result is:
+15 + 15 + 2.5 = +32.5
The correct interpretation is not simply "the market is going higher."
Instead, the engine is saying:
The market remains structurally bullish and in a Stage-2 environment, but immediate momentum, volume and structural-break confirmation are currently limited.
That distinction is the purpose of the model.
Philosophy of the Indicator
Market Regime Engine is built around the idea that:
Regime ≠ Trade Entry
A bullish regime does not mean every bar should be bought, just as a bearish regime does not mean every bar should be sold.
The engine is designed to establish environment and directional context.
Execution can then be handled separately using the trader's preferred methodology—price location, pullbacks, candlestick confirmation, support/resistance, volume profile, or other entry criteria.
The framework therefore separates three different questions:
Regime:
What is the market doing?
Stage:
Where are we in the broader cycle?
Historical Cohort:
What happened historically after comparable conditions?
Together, these create a market-state framework that attempts to remain fast enough to recognize meaningful change, structured enough to resist noise, and transparent enough to understand exactly why the market received its current classification.
For research and educational purposes only. Market Regime Engine does not predict future prices and is not financial advice. 指标

指标

Zeiierman Trend Pressure (Zeiierman)█ Overview
Zeiierman Trend Pressure (Zeiierman) is a multi-layer trend pressure and exhaustion oscillator designed to visualize short-term momentum, persistent trend structure, directional pressure, and exhaustion states within a normalized 0 to -100 range.
Instead of relying on a single oscillator calculation, the indicator separates market behavior into three distinct components:
• Z-Pulse = fast reactive pressure
• Z-Trend = slower macro-weighted trend pressure
• Pressure Core = broader directional pressure and regime structure
Z-Pulse reacts quickly to changes in local range position, while Z-Trend blends fast, structural, and macro range measurements with a strong weighting toward the longer-term trend. The Pressure Core then evaluates candle position, candle body, wick behavior, and recent impulse to provide an additional view of directional pressure.
The indicator also contains a persistent Pressure Exhaustion model. When both Z-Pulse and Z-Trend reach an extreme region, an exhaustion state can become active. Instead of disappearing immediately when either line moves slightly away from the extreme, the state uses confirmation and release logic to remain active until pressure has meaningfully weakened.
Pressure Core coloring identifies the broader directional environment:
• Core Bull = positive directional pressure
• Core Bear = negative directional pressure
• Core Neutral = mixed or insufficient directional pressure
Dots show active pressure states, while triangles identify the beginning of an upper or lower pressure event. Price boxes can also be projected directly onto the chart while an exhaustion state remains active.
█ How It Works
⚪ Z-Pulse
Z-Pulse is the indicator's fast component. It first measures where the current close sits inside the recent price range using a Williams-style normalized range calculation.
rangePosition = 100 * (close - highest) / (highest - lowest)
A stochastic transformation of this fast range reading is then blended back into the original value.
Z-Pulse Raw =
rangePosition * 0.72
+ stochasticPulse * 0.28
The result is smoothed with an EMA to create Z-Pulse. This gives the indicator a responsive line that can quickly detect changes in local market pressure while staying within the 0 to -100 oscillator range.
⚪ Z-Trend
Z-Trend is designed to represent the more persistent side of market pressure.
Three normalized range measurements are calculated using the Pulse Range, Trend Range, and Macro Trend lengths. These readings are combined using fixed internal weights, with the macro component receiving the largest influence.
Z-Trend Target =
Fast Range * 0.10
+ Trend Range * 0.18
+ Macro Range * 0.72
The engine then measures agreement between the three range layers and the efficiency of recent price movement.
When the market is moving efficiently and the range layers agree, Z-Trend becomes more resistant to short counter-trend movements. Persistent occupation of the upper or lower oscillator region also increases the Trend Persistence effect.
This makes Z-Trend slower and more stable than Z-Pulse, allowing it to represent the underlying directional structure instead of reacting to every short-term fluctuation.
⚪ Pressure Core
Pressure Core measures each candle's internal structure relative to a larger price range.
It combines five components:
• closing location inside the range
• average candle location
• candle-body direction
• upper versus lower wick pressure
• recent five-bar price impulse
pressure =
closeLocation * 0.42
+ meanLocation * 0.23
+ bodyBias * 0.13
+ wickBias * 0.12
+ impulse * 0.10
A reactive pressure model and a slower regime model are then combined using the Regime Weight setting.
Pressure Core =
Regime Pressure * Regime Weight
+ Reactive Pressure * (1 - Regime Weight)
This creates a third view of market pressure that is independent of the Z-Pulse / Z-Trend relationship.
⚪ Pressure Exhaustion
Pressure Exhaustion begins when both Z-Pulse and Z-Trend occupy the same extreme region.
upperPressure = Z-Pulse >= upperLevel
and Z-Trend >= upperLevel
lowerPressure = Z-Pulse <= lowerLevel
and Z-Trend <= lowerLevel
The state does not use a simple one-bar threshold cross. It includes entry confirmation and a separate release distance so temporary fluctuations do not immediately terminate a persistent pressure state.
This creates a hysteresis effect, where entry and release conditions are intentionally different.
At normal and higher sensitivity settings, both Z-Pulse and Z-Trend must move away from the extreme before the state is released. At the lowest sensitivity settings, the state is deliberately allowed to become much less stable.
█ How to Use
Zeiierman Trend Pressure can be used in three main ways: Trend Trading, Continuation Trading, and Reversal Trading.
Z-Pulse reacts faster to short-term changes in pressure, while Z-Trend shows the slower and more persistent trend direction. Pressure Core can then be used as an additional confirmation of the broader market bias.
⚪ Trend Trading
Use Z-Trend and Pressure Core to identify the main directional environment.
When Z-Trend is holding in the upper half of the oscillator and Pressure Core is Bull-colored, bullish pressure is dominant. This favors looking for long setups.
When Z-Trend is holding in the lower half , and Pressure Core is Bear-colored, bearish pressure is dominant. This favors looking for short setups.
⚪ Continuation Trading
For continuation setups, look for temporary pullbacks within an already established trend.
• Bullish Continuation Setup
During a bullish trend, Z-Trend and Pressure Core should remain bullish while Z-Pulse temporarily moves lower. This shows that short-term pressure has weakened, but the broader trend structure is still intact.
• Z-Trend remains bullish
• Pressure Core remains Bull-colored
• Z-Pulse drops lower during the price pullback
• Z-Pulse then turns higher again
• Price begins continuing in the direction of the broader bullish trend
• Bearish Continuation Setup
During a bearish trend, Z-Trend and Pressure Core should remain bearish while Z-Pulse temporarily moves higher. This shows that short-term pressure has strengthened against the trend, but the broader bearish structure is still intact.
• Z-Trend remains bearish
• Pressure Core remains Bear-colored
• Z-Pulse temporarily pushes higher during a price bounce
• Z-Pulse then turns lower again
• Price begins continuing in the direction of the broader bearish trend
The important distinction is that Z-Pulse is allowed to move against the trend temporarily. That is the pullback. As long as Z-Trend and Pressure Core remain aligned with the broader direction, the move can be treated as a potential continuation setup rather than a full trend reversal.
⚪ Reversal Trading
The pressure boxes highlight areas where the market has remained under extreme directional pressure for a period of time.
The box itself shows the price range formed while the pressure state is active. The triangle at the end of the box marks the Pressure Release, which is the important confirmation for a potential reversal.
• Bullish Reversal
A blue box forms when Z-Pulse and Z-Trend remain under strong downside pressure.
While the box is active, bearish pressure is still present, so the box alone is not a buy signal.
When the blue triangle appears, the Lower Pressure state has been released. This shows that downside pressure is weakening and can mark a potential bullish reversal area.
• Blue Box = downside pressure is active
• Blue Triangle = downside pressure has released
• Bearish Reversal
A red box forms when Z-Pulse and Z-Trend remain under strong upside pressure.
While the box is active, bullish pressure is still present, so the box alone is not a sell signal.
When the red triangle appears, the Upper Pressure state has been released. This shows that upside pressure is weakening and can mark a potential bearish reversal area.
• Red Box = upside pressure is active
• Red Triangle = upside pressure has released
The key idea is to wait for the pressure release rather than trying to predict the reversal while the box is still developing.
█ Settings
Pulse Range: Controls the primary range window used by Z-Pulse.
Pulse Stochastic: Controls the stochastic transformation applied to the fast range reading.
Pulse Smoothing: Controls EMA smoothing of Z-Pulse. Higher values create a smoother and slower response.
Trend Range: Controls the medium-term structural range used by Z-Trend.
Macro Trend: Controls the longest range component used by Z-Trend. This component has the largest internal weighting.
Trend Smoothing: Controls the final smoothing of Z-Trend.
Trend Persistence: Controls how strongly persistent occupation of an extreme region influences Z-Trend.
Exhaustion Zone: Controls the base location of the upper and lower pressure regions.
Sensitivity: Controls exhaustion selectivity, confirmation, release distance, and state persistence. Lower values are looser and more inconsistent, while higher values are stricter and more persistent.
Reactive Smoothing: Controls smoothing of the reactive component inside Pressure Core.
Regime Weight: Controls how much influence the slower Pressure Core regime receives relative to reactive pressure.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
指标

Cross-Asset Regime OscillatorA daily 0–100 gauge of US market risk appetite, built from five cross-asset
signals rather than price alone. It answers one question: is the broader
tape leaning risk-on or risk-off right now?
METHOD
Each signal is z-scored against its own trailing distribution on daily bars
("Lookback (bars)" input, default 252 ≈ one trading year, range 60–1000),
clamped to ±3 so no single blown-out signal dominates, averaged with equal
weight, then mapped linearly onto 0–100. The lookback always counts daily
bars, whatever the chart timeframe.
SIGNALS (all free-tier data, no premium feeds)
1. Credit — HYG/IEF: high yield vs. Treasuries. Higher = risk-on.
2. Equity volatility — VIX, inverted. Lower vol = risk-on.
3. Cyclical vs. defensive — XLI/XLU: industrials vs. utilities. Higher = risk-on.
4. Yield curve — US10Y minus US03MY (10-year minus 3-month). Steeper = risk-on.
5. US dollar — DXY, inverted. Weaker dollar = risk-on.
READING IT
0–20 RISK-OFF · 20–40 MILDLY OFF · 40–60 NEUTRAL · 60–80 MILDLY ON · 80–100 RISK-ON
The line is colored by band, with dotted guides at 20/40/60/80, and the
corner readout shows the current band and score. Enable "Show signal
breakdown" to see each signal's clamped z-score and the composite in the
corner table — useful for seeing WHICH channel is driving a move (e.g. credit
still positive while vol and cyclicals roll over). "Color chart bars by
regime" paints the price bars with the band color.
MISSING DATA
A signal that has not loaded, has fewer daily bars than the lookback, or is
flat over the lookback is skipped, and the composite averages the rest. The
readout warns when fewer than 3 of the 5 signals have data.
NON-REPAINTING
Every value is the clamped z-score of the last CONFIRMED daily bar, computed
inside the daily security context. The one-bar offset makes the request
confirmed-only, so the forming daily bar never leaks in and values never
change on refresh. Each day's value is aligned to the start of the daily
period, so the reading is identical on every supported chart timeframe.
During a live session the reading reflects the prior session's close.
SUPPORTED TIMEFRAMES
Daily and intraday charts. On any chart timeframe above daily (weekly,
monthly, multi-day) the script stops with a runtime error by design:
"Cross-Asset Regime Oscillator is a daily indicator. Use a 1D or lower
chart timeframe." It is a daily oscillator, and above-daily requests cannot
be pinned reliably to the same confirmed session.
LIMITATIONS
This is a deliberately simple, transparent construction: equal weights, one
lookback, five signals. It describes current conditions; it does not
forecast. Short lookbacks react fast and can whipsaw. Not investment advice. 指标

EMA + RSI + VWAP Targets🚀 EMA + RSI + VWAP Trading Indicator | Smart Buy & Sell Signals
Trade with confirmation, not guesswork. 📊
This indicator combines EMA trend direction, RSI momentum, and VWAP price positioning into one clean trading system designed to help identify potential BUY and SELL opportunities.
🔥 Key Features:
🟢 BUY & 🔴 SELL signals
📈 EMA trend filter
⚡ RSI momentum confirmation
🎯 VWAP market positioning
🎯 Automatic Target 1, Target 2 & Target 3
🛑 Configurable Stop Loss
🔔 BUY/SELL alerts
👀 Clean and easy-to-read chart
⚙️ Customizable settings for different markets and timeframes
💡 How it works:
BUY signals look for bullish conditions when price is above the EMA and VWAP with RSI confirmation.
SELL signals look for bearish conditions when price is below the EMA and VWAP with RSI confirmation.
🎯 Multiple targets help you plan potential trade exits, while the configurable Stop Loss helps define risk.
Perfect for traders looking for a simple, confirmation-based approach across crypto, forex, stocks, and other markets.
⚠️ Disclaimer: This indicator is an analytical tool, not financial advice. No indicator can guarantee profits. Always use proper risk management and test the settings on your market and timeframe before trading live.
⭐ Like, follow, and share if you find this indicator useful! 指标

指标

24-hour Volumeoppock Curve Multi-Filter is a trend and momentum-based indicator designed to identify potential high-probability Long and Short opportunities. It combines the Coppock Curve with multiple confirmation filters to determine market bias and provides visual Entry, Stop Loss, TP1, TP2 and TP3 levels.
Use the indicator alongside market structure, support/resistance and price action for confirmation. It is designed as a decision-support and risk-management tool, not a guaranteed signal generator. Always apply proper risk management.
If you want, I can also write you a much more professional TradingView publication description with sections like “How It Works,” “Buy Conditions,” “Sell Conditions,” “Risk Management,” and “Settings,” tailored specifically to your script.
指标

FCP | Market Pulse | Multi Symbol Volatility ScannerMarket Pulse ranks up to 40 symbols by how violent their current candle is relative to their own recent behaviour.
THE METRIC
For every symbol on a fixed scan timeframe:
ratio = (high − low) / ATR(14)
The ATR is read from the previous bar, so an explosive candle cannot inflate its own baseline and cancel itself out. Because the range is divided by that symbol's own ATR, the number is unitless — a 2.5 on EURUSD and a 2.5 on BTCUSDT mean the same thing. One threshold works for FX, indices, metals and crypto at once, which a pip- or percent-based filter cannot do.
A symbol is listed when its ratio reaches the trigger multiple. Anything below it is ignored, so the panel stays empty most of the time and only fills up when something is actually happening.
READING THE PANEL
SYMBOL — the live scan period, sorted by ratio, strongest first
PREVIOUS — the same list for the last closed period, so a chart opened mid-period still shows what just moved
xATR — how many times its own average range the candle has covered
CHG% — direction and size of the move, (close − open) / open
▲ ▼ — green for an up candle, red for a down candle
"quiet" means nothing crossed the threshold. That is the normal state.
Nothing is stored between periods. A symbol drops off by itself as soon as it cools down, and markets that are closed are excluded so a frozen quote is never reported as a live burst.
SETTINGS
Scan timeframe — every symbol is measured on this timeframe regardless of the chart. Keep the chart at the same timeframe or lower.
ATR length — default 14.
Trigger at N x ATR — 2.0 to 2.5 catches ordinary bursts, 5 catches only major shocks.
Symbols — 40 slots, each a checkbox plus a symbol picker. Untick a slot to drop it from the panel and the alert. Retarget any slot to your own data provider.
ALERTS
Create the alert with "Any alert() function call". One alert fires per closed scan bar and lists every symbol over the threshold, in the same order the panel shows them.
The Telegram JSON option formats the message as a ready-to-post sendMessage payload. Enter your own chat id, then point the alert webhook at the Telegram sendMessage API endpoint for your bot.
Webhooks require a paid TradingView plan with two-factor authentication enabled. Your bot token lives only in the webhook URL — it is never part of this script. Never share it or screenshot the alert dialog; if it leaks, revoke it in BotFather.
Turn the option off if you route alerts through your own relay server instead.
LIMITS
40 symbols is a hard ceiling — Pine allows no more than 40 data requests per script. 指标

On Balance VolumeOverview
This indicator is based on On Balance Volume (OBV) and is designed to analyze the relationship between price and volume, helping traders identify potential accumulation, distribution, trend confirmation, and changes in volume flow.
In addition to the traditional OBV, the indicator allows users to apply different moving-average types to smooth the OBV and, optionally, add Bollinger Bands around the smoothed OBV.
The indicator also uses dynamic colors, making it easier to visually identify the direction of both the OBV and its moving average.
1. On Balance Volume (OBV)
OBV accumulates or subtracts volume according to price movement:
If the current closing price is higher than the previous close, volume is added to OBV.
If the current closing price is lower than the previous close, volume is subtracted from OBV.
If there is no change in price, OBV remains unchanged.
Interpretation
Rising OBV:
May indicate increasing buying pressure, accumulation, or confirmation of an uptrend.
Falling OBV:
May indicate increasing selling pressure, distribution, or confirmation of a downtrend.
OBV should not be used in isolation. Combining it with price action, trend structure, support and resistance, and other technical factors may improve the quality of the analysis.
2. OBV Dynamic Colors
The main OBV line uses three colors:
🟢 Green
OBV is increasing compared with the previous period.
This indicates positive volume flow.
🔴 Red
OBV is decreasing compared with the previous period.
This indicates negative volume flow.
🟡 Yellow
OBV has not changed compared with the previous period.
3. Smoothing
The Type setting allows users to apply a moving average to the OBV.
Available options:
None
SMA
SMA + Bollinger Bands
EMA
SMMA (RMA)
WMA
VWMA
Smoothing can be used to reduce short-term fluctuations and make the underlying direction of OBV easier to identify.
4. Moving Average Type
None
No moving average is applied.
Only the original OBV is displayed.
Useful for:
Faster analysis;
Immediate identification of OBV changes;
Traders who prefer raw volume-flow information.
SMA — Simple Moving Average
Calculates the arithmetic average of OBV over the selected number of periods.
Characteristics:
Smoother than the raw OBV;
Slower to react to sudden changes;
Useful for identifying the broader direction of volume flow.
SMA + Bollinger Bands
Applies an SMA to OBV and adds Bollinger Bands.
This option displays:
A central moving average;
An upper Bollinger Band;
A lower Bollinger Band.
The bands help identify periods when OBV is moving relatively far from its recent average.
EMA — Exponential Moving Average
The EMA gives greater weight to recent OBV values.
Characteristics:
Responds faster to changes in OBV;
Useful for short- and medium-term analysis;
Generally more responsive than an equivalent SMA.
SMMA (RMA)
The SMMA/RMA is a smoother moving average designed to reduce short-term fluctuations.
It can be useful for traders who want a more stable view of the underlying OBV trend.
WMA — Weighted Moving Average
The WMA assigns greater weight to more recent values.
It generally responds faster to changes in OBV than an equivalent SMA.
VWMA — Volume Weighted Moving Average
The VWMA weights values according to volume.
Because OBV itself is already volume-based, this option may produce a different smoothing behavior compared with traditional moving averages and should be evaluated according to the trader's strategy.
5. Length
The Length parameter determines the number of periods used to calculate the moving average.
The default value is:
14 periods
Shorter Length
Examples: 5, 9, or 10.
The moving average becomes faster and more sensitive.
Potentially useful for:
Short-term trading;
Faster detection of changes in volume flow;
Scalping and intraday strategies, depending on the market.
However, shorter lengths can also generate more noise and false signals.
Longer Length
Examples: 20, 50, or 100.
The moving average becomes slower and smoother.
Potentially useful for:
Trend analysis;
Swing trading;
Identifying the dominant volume-flow direction.
The longer the length, the greater the delay in reacting to changes in OBV.
6. Moving Average Dynamic Colors
The OBV moving average also changes color dynamically.
🟢 Green
The moving average is rising.
🔴 Red
The moving average is falling.
🟡 Yellow
The moving average is unchanged.
This allows traders to quickly identify the direction of the smoothed OBV.
7. Bollinger Bands
Bollinger Bands are available only when:
Type = SMA + Bollinger Bands
The bands are calculated using the standard deviation of OBV.
The indicator displays:
Upper Bollinger Band
SMA / Middle Band
Lower Bollinger Band
The distance between the bands expands or contracts according to changes in OBV volatility.
8. BB StdDev
The BB StdDev parameter controls the distance of the Bollinger Bands from the moving average.
Default value:
2.0
Lower value
Example: 1.0–1.5.
The bands become narrower.
This increases sensitivity and causes OBV to reach the bands more frequently.
Higher value
Example: 2.5–3.0.
The bands become wider.
This reduces the frequency of band touches and can help highlight more extreme OBV movements.
9. How to Interpret the Indicator
The indicator can primarily be used for four types of analysis:
1. Trend Confirmation
During an uptrend:
Price rising + OBV rising
may indicate volume confirmation of the bullish trend.
During a downtrend:
Price falling + OBV falling
may indicate confirmation of selling pressure.
2. Bullish Divergence
A potential bullish divergence occurs when:
Price makes lower lows while OBV makes higher lows.
This may indicate weakening selling pressure and a possible loss of bearish momentum.
3. Bearish Divergence
A potential bearish divergence occurs when:
Price makes higher highs while OBV makes lower highs.
This may indicate weakening buying pressure.
Important: Divergences do not guarantee a reversal. They should be considered warning signals and ideally confirmed by price action or other technical factors.
10. Using Bollinger Bands on OBV
When Bollinger Bands are enabled, they can help identify unusual movements in volume flow.
OBV near or above the Upper Band
May indicate an unusually strong positive OBV movement relative to its recent average.
OBV near or below the Lower Band
May indicate an unusually strong negative OBV movement.
However, touching or crossing a Bollinger Band does not automatically mean buy or sell.
During strong trends, OBV may remain near one of the bands for extended periods.
11. Suggested Settings
There is no universally optimal configuration. The appropriate settings depend on the asset, timeframe, volatility, and trading strategy.
Short-Term Analysis
A possible starting configuration:
Type: EMA
Length: 9 or 14
This provides a faster response to changes in OBV.
Medium-Term Analysis
A possible starting configuration:
Type: SMA
Length: 20
This provides a balance between responsiveness and smoothing.
Longer-Term Trend Analysis
A possible starting configuration:
Type: SMA
Length: 50
This provides greater smoothing and reduces sensitivity to short-term fluctuations.
Bollinger Band Analysis
A possible starting configuration:
Type: SMA + Bollinger Bands
Length: 20
BB StdDev: 2.0
These settings are reference points for testing and are not investment recommendations.
12. Practical Usage
One possible approach is to use the indicator together with price structure.
Potential Bullish Setup
Look for a combination such as:
Price showing a bullish market structure;
OBV rising;
OBV moving average turning green;
OBV confirming upward price movements;
A breakout or recovery of an important price level.
Potential Bearish Setup
Look for a combination such as:
Price showing a bearish market structure;
OBV falling;
OBV moving average turning red;
OBV confirming downward price movements;
A breakdown or rejection of an important price level.
The indicator is best used as a confirmation tool, rather than as the sole reason to enter a trade.
13. Recommended Starting Configuration
For traders who are new to the indicator, a simple starting configuration is:
Type: SMA
Length: 14
Then compare it with:
Type: EMA
Length: 14
Observe which configuration better represents the behavior of the asset and timeframe being analyzed.
For Bollinger Band analysis:
Type: SMA + Bollinger Bands
Length: 20
BB StdDev: 2.0
14. Important Notes
OBV is a cumulative indicator. Therefore, its absolute values can vary significantly depending on the available historical data and the asset being analyzed.
Signals should be interpreted in the context of:
Market trend;
Price structure;
Support and resistance;
Volume;
Volatility;
Timeframe;
Overall market conditions.
No parameter should be considered universally superior.
It is recommended to test different configurations using historical data, Bar Replay, and paper trading before applying any strategy to live trading.
This indicator is a technical analysis tool and does not constitute financial, investment, or trading advice. 指标

Macro Regime Dashboard█ OVERVIEW
Macro Regime Dashboard is a market-timing checklist for US equities. It evaluates five regime conditions on every daily bar: elevated volatility, a non-rising Fed policy rate, contracting margin debt, the presence of a leading sector, and earnings confirmation from bellwether stocks. It plots the count of conditions met as a stepline in a separate pane, renders a live checklist table, and marks the bars where all conditions and the enabled fail-safes align. The thesis: durable market bottoms tend to form when fear is high, the Fed is not tightening, leverage has been flushed, and a leading theme keeps delivering earnings through the panic.
█ HISTORY / BACKGROUND
The five-condition checklist and its fail-safes are the market-timing framework described by the YouTuber, Defiant Gatekeeper, who distilled it from his buy decisions around volatility spikes. The framework itself synthesizes established concepts: the VIX as a fear gauge, Federal Reserve policy as the dominant liquidity driver, margin debt as a measure of speculative leverage, sector leadership as the engine that attracts institutional capital, and earnings surprises as confirmation that the leading theme is insulated from the broader panic.
The fail-safes address the framework's known failure modes, which the author identifies from historical episodes: leading-sector fundamentals breaking down, systemic accounting fraud destroying trust in reported earnings, a credit freeze that policy easing cannot offset, and inflation high enough to remove the Fed's ability to support asset prices. Two of these are quantifiable and are implemented here as the high-yield credit spread and CPI fail-safes. The concept is his; this Pine implementation, the data-series selections, and the proxy choices are original to this script.
█ HOW IT WORKS
On each daily bar the script requests six external series and evaluates five boolean conditions plus two fail-safes.
Condition 1: Fear. The CBOE Volatility Index (CBOE:VIX) must exceed the threshold input (default 30).
Condition 2: Fed not on an upward trajectory. The effective federal funds rate (FRED:DFF) today must be at or below its value from the lookback number of trading days earlier, with a 0.01 tolerance. The table also flags when the 2-year Treasury yield (TVC:US02Y) sits below the funds rate, indicating that the bond market is pricing cuts; this flag is informational and does not gate the condition. Because the policy trajectory is partly qualitative (guidance, projections), an override input can force this condition to pass or fail.
Condition 3: Margin debt declining. The reference framework uses the monthly FINRA margin debt statistic, which TradingView does not carry. The script substitutes the Federal Reserve Z.1 series for margin accounts at brokers and dealers (FRED:BOGZ1FL663067003Q), requested at 3-month resolution. The condition passes when the latest quarterly value is below the prior quarterly value.
Condition 4: Leading sector. The script loops over eleven S&P sector ETFs plus a semiconductor ETF, computes each one's return over the lookback window, and subtracts the SPY return over the same window. The strongest relative-strength value must exceed the threshold input (default 3 percentage points over 63 days). The table names the current leader.
Condition 5: Bellwether earnings beats. For up to three user-selected bellwether symbols representing the leading theme, the script pulls reported and estimated earnings per share through the earnings request feed and marks a beat when actual is at or above estimate for the most recent report. The condition passes when a majority of the symbols with available data beat. When no earnings data exists for any bellwether, the condition passes neutrally rather than failing, so that missing history does not veto the count. An override input can force this condition either way.
Fail-safes. The ICE BofA US High Yield Option-Adjusted Spread (FRED:BAMLH0A0HYM2) must sit below its threshold (default 10 percent), and CPI year-over-year, computed from FRED:CPIAUCSL as the ratio of the monthly index to its value twelve months earlier, must sit below its threshold (default 2.5 percent). Each fail-safe passes when its data is unavailable. Two toggle inputs decide whether each fail-safe vetoes the composite signal or only displays as a warning. By default the credit fail-safe gates and the CPI fail-safe warns.
Composite. The buy state is true when all five conditions hold and every enabled gate is clear. The script plots the raw condition count (0 to 5) as a stepline, draws a dotted horizontal reference at 5, shades the pane background green while the buy state is active, and prints a green triangle on the first bar of each signal window. A table in the top right shows each condition's current value and pass state, both fail-safe readings, and a composite verdict row. Two alerts are provided: one on the first bar of a new buy signal, and one when the credit spread crosses above its threshold.
█ HOW TO USE
Apply the indicator to a broad US index such as SPX or SPY on the daily timeframe . All inputs and thresholds are calibrated to daily bars; the conditions describe the whole market, so the chart symbol only supplies the bar grid.
Read the stepline as regime pressure. A count of 3 or 4 during a selloff means the setup is forming; a touch of 5 with the background shading and a triangle means every condition and enabled gate aligned on that bar. A count of 5 without shading means a fail-safe is blocking, which is exactly the bull-trap situation the fail-safes exist to flag. The table gives the per-condition diagnosis at a glance.
Using the dashboard in tandem with the Stock Screener
The dashboard times entry and sizing. It does not select stocks. The reference framework pairs it with a fundamental selection layer keyed to the liquidity regime, and most of that layer maps directly onto TradingView's Stock Screener fields: revenue growth, EPS growth, forward price-to-earnings, and debt to EBITDA. The workflow:
Determine the liquidity quadrant. The dashboard's Fed condition covers the rate trajectory. Check the Fed balance sheet direction separately by charting FRED:WALCL: rising means expansion, falling means contraction.
Rate falling and balance sheet rising (maximum liquidity): screen for revenue growth above 50 percent and ignore valuation and leverage fields. Unprofitable hypergrowth is the target profile in this quadrant.
Mixed quadrants (one lever easing, one tightening): screen for revenue growth in the 10 to 20 percent range, a moderate forward price-to-earnings, and debt to EBITDA below roughly 3 to 5 depending on which lever is easing.
Rate rising and balance sheet falling (minimum liquidity): screen for forward price-to-earnings below 15, debt to EBITDA below 1.5, and positive earnings. Stability over growth.
When the dashboard signals, run the screener preset for the current quadrant, restricted to the leading sector the table names, to surface candidates.
The final validation step in the reference framework, a regression of price-to-earnings against expected EPS growth across roughly ten same-industry peers with an R-squared above 0.8, is not screenable and is performed outside TradingView in a spreadsheet.
█ SETTINGS
VIX threshold (default 30): level the volatility index must exceed for condition 1.
Fed rate lookback (default 63 trading days): comparison window for the funds-rate trajectory in condition 2.
Fed trajectory override (default Auto): forces condition 2 to pass or fail when guidance contradicts the rate proxy.
Sector RS lookback (default 63 days): return window for the relative-strength computation in condition 4.
RS outperformance vs SPY (default 3 percent): margin by which the leading sector must beat SPY.
Bellwether 1, 2, 3 (defaults are three large semiconductor names): symbols whose earnings reports confirm the leading theme. Change these whenever the leading theme rotates.
Earnings override (default Auto): forces condition 5 to pass or fail.
HY OAS max (default 10 percent): credit-spread ceiling for the credit fail-safe.
CPI YoY max (default 2.5 percent): inflation ceiling for the CPI fail-safe.
Credit fail-safe gates signal (default on): when on, an elevated credit spread vetoes the composite signal.
CPI fail-safe gates signal (default off): when on, elevated inflation vetoes the composite signal; when off it displays as a warning only.
█ WHAT MAKES IT ORIGINAL
The script consolidates a cross-asset macro checklist into a single gated, auditable pane: an equity volatility index, the policy rate, the Treasury 2-year, a quarterly flow-of-funds leverage series, sector ETF relative strength, per-symbol earnings surprise data, a credit spread, and a computed inflation rate. Each series exists elsewhere in isolation; the contribution here is the joint evaluation with explicit pass/fail logic, the separation of hard vetoes from soft warnings through the gate toggles, and two implementation choices that make the framework computable on TradingView at all: the Z.1 quarterly margin-account series as a proxy for the unavailable monthly FINRA margin debt statistic, and the earnings-beat condition built from the earnings request feed on user-configurable bellwethers, with missing data treated as neutral rather than as a veto.
█ NOTES / LIMITATIONS
Designed for the daily timeframe on a broad US index. Other resolutions misalign the lookbacks and the higher-timeframe requests; other symbol classes add no information because every condition is market-wide.
The margin-debt proxy is quarterly. Monthly FINRA data can show a deleveraging turn up to one quarter before the Z.1 series reflects it, so condition 3 is the slowest leg and produces a step-shaped response.
Monthly and quarterly requests update when those periods complete. Within a forming month or quarter the CPI and margin readings can change until the period closes.
Earnings history depth varies by symbol and generally thins in earlier years. On older bars condition 5 frequently passes neutrally for lack of data, and the override and bellwether inputs are static across the whole chart, so the plotted historical count is indicative rather than point-in-time. Treat the history as illustration, not as a backtest.
Economic series have distinct start dates, and all external requests ignore invalid symbols. Missing data renders as n/a in the table, fail-safes pass when their series is absent, and a sector whose ticker fails to resolve is silently skipped in the relative-strength scan.
The checklist table reflects the last bar only.
The Fed condition is a proxy for a qualitative judgment. During fast easing cycles the fixed lookback can briefly misread the trajectory, which is what the override input is for.
指标

指标

FCP | Market Sessions | High Low Box & Range StatsMarks the Sydney, Tokyo, London and New York sessions, tracks each
one's high and low, and carries those levels forward to the next
session open.
WHAT IT DRAWS
• A shaded box spanning each session's time window and price range.
• High and low lines that extend to the next session's open.
• Range extension lines projected from the session high and low at
configurable multiples of the session range (0.5x, 1x, 2x by
default), with optional multiplier labels.
• A stats table showing each active session's current range as a
percentage of its own average range over the last N sessions.
Rows for disabled sessions are hidden.
HOW IT WORKS
Session boundaries and session extremes are not read from the chart's
candles. They are computed from 5-minute data through a lower-timeframe
request, so the levels are identical whether you are on a 15-minute
chart or a 4-hour chart. The chart is only the canvas.
The session in progress updates on every tick rather than on bar close,
so the box and its high and low lines follow price in real time.
SETTINGS
Session timezone — sessions are defined in this timezone, so the
windows stay fixed regardless of the symbol's exchange timezone.
Accepts a UTC offset (GMT+0, GMT+3) or an IANA name (Europe/London).
Look-back — how many past sessions to keep drawn.
Each session has its own on/off switch, time window, colour and line
width, so you can define custom windows instead of the defaults.
Range extensions — three independent multipliers; set any of them to
0 to hide one. Line style, width and transparency are adjustable.
Range stats — the averaging window, panel corner and text size.
NOTES
Works on timeframes up to and including 1 day. On higher timeframes
nothing is drawn.
Session times are fixed to the selected timezone and do not shift with
daylight saving time. If your sessions are defined in a DST-observing
timezone, adjust the windows twice a year or enter an IANA timezone
name. 指标

Adaptive Range Opportunity Hunter [SMI] v1.3Adaptive Range Opportunity Hunter
This indicator was created as an experimental tool to help identify potential entry opportunities near the end of a trading session, with the intention of evaluating positions that may be held for at least the following trading day rather than relying on frequent same-day scalping.
The underlying idea is simple: instead of evaluating price using a fixed absolute threshold, the script measures where the current price is located inside its own recent local range.
By default, the indicator uses the highest and lowest prices of the previous 40 bars as a local price reference. This value was selected empirically after observing that, on many charts, approximately 40 bars often contain around one or two recent price cycles. It should therefore be understood as a practical local reference rather than a universal cycle length.
The main metric, Distance from Local Low %, represents the normalized position of the current close relative to the lowest price in that local range:
0% means price is at the local low.
3% means price is inside the lowest 3% of the local range.
50% represents approximately the middle of the range.
100% corresponds to the local high.
The complementary Distance from Local High % provides the symmetric measurement from the upper extreme. Both values are continuously displayed so users can experiment with their own thresholds.
The default research condition combines two elements:
SMI <= -40
Distance from Local Low <= 3%
This identifies situations where momentum is in an oversold SMI region while price is simultaneously located very close to the lower extreme of its recent local range.
The 3% threshold is not a predicted loss, stop-loss, or expected downside. It simply describes the price's normalized location within the recent high-low range.
The indicator also calculates a Standardized Benefit to Local High %. This represents the hypothetical percentage distance from the configured lower-range threshold to the current local high. It is intended to help compare simultaneous opportunities between different symbols. It is not an expected return or price target.
Intended use
My initial research use is to review signals near the end of the trading day and evaluate whether the resulting positions can be held into at least the following session. The goal is to explore a slower operational approach than habitual intraday scalping and reduce reliance on repeated same-day round trips.
The indicator exposes both the raw measurements and combined SMI conditions, allowing users to test different ideas such as:
Distance from Local Low below 1%, 2%, 3%, 5%, etc.
Local-range proximity without SMI confirmation.
Local-range proximity combined with SMI oversold conditions.
Symmetric conditions near the local high.
Alerts are included so users can monitor multiple symbols and be notified when a new condition appears.
Experimental status
This is a research indicator, not a trading system and not a recommendation to buy or sell. The default values of 40 bars, 3%, and SMI ±40 are intentionally kept as an initial reference rather than presented as universally optimal parameters.
Community feedback is especially welcome regarding different symbols, markets, timeframes and threshold values. One of the purposes of publishing the script is to evaluate whether the observed behavior remains useful outside the instruments and historical examples used during its development.
Credits
The Stochastic Momentum Index calculation is based on the original TradingView implementation by UCSgears. The original source also credits Surjith S M for part of the overbought/oversold visualization.
This adaptation adds the local rolling-range framework, normalized distance measurements, configurable opportunity conditions, standardized local-range comparison, alerts and dashboard. 指标

指标

Institutional Quant Correlation Grid Suite Slide 1: Title
Institutional Quant Correlation Grid Suite
Pine Script v6 Indicator
Purpose: A professional-grade quantitative analysis tool that evaluates a ticker's relationship to a benchmark (e.g., SPY) across multiple dimensions — correlation, volatility, momentum, and risk-adjusted performance — all presented in an intuitive visual dashboard.
Author: Quant Trading Team
Version: 6.0
Slide 2: Problem Statement & Solution
The Challenge:
Retail traders lack institutional-grade quant tools inside TradingView.
Evaluating a stock's true relationship to the market (or sector ETF) requires looking beyond simple price correlation.
Key metrics (Beta, Alpha, Z-scores, Relative Strength) are scattered across different indicators.
Our Solution:
An all-in-one indicator that computes, visualizes, and alerts on:
Multi-asset correlations (Price, RSI, ATR, Volume, Volume-Weighted)
Risk metrics (Beta, Annualized Alpha)
Mean-reversion signals (Spread Z-Score)
Relative strength momentum (RS Ratio)
Timeframe returns (1D, 1W, 1M)
Automated Buy/Hold/Sell conditions
Slide 3: Core Inputs – Quant Settings
Input Default Description
Lookback Window 30 bars Rolling window for all correlations & statistics. Adjustable 10–500.
Reference Symbol SPY Benchmark ETF. Dropdown includes 40+ sector/thematic ETFs (XLF, SMH, ARKG, GDX, JETS, etc.)
Correlation Metric Close Which data series to screen against the benchmark (Close, Open, High, Low, Volume, RSI, ATR).
Correlation Threshold 0.70 Minimum absolute correlation to be considered "aligned".
Z-Score Extremes Threshold 2.00 Level at which the spread is considered overextended (mean-reversion signal).
Slide 4: Oscillator & Indicator Parameters
The suite uses standard technical indicators for its multi-dimensional analysis:
Indicator Parameter Default
RSI Length 14
MACD Fast / Slow / Signal 12 / 26 / 9
Stochastic Length / Smooth 14 / 3
CCI Length 20
Williams %R Length 14
ATR Length 14
These are used to compute correlations across different market regimes (momentum, volatility, volume) — not just price.
Slide 5: Core Calculations – Correlation Suite
The indicator computes 6 distinct correlation metrics against the reference symbol over the lookback window:
Correlation Methodology
Price Corr Standard Pearson correlation of Close prices.
Selected Metric Corr Correlation of the user-chosen metric (e.g., RSI, Volume) against the benchmark's equivalent.
RSI Corr Correlation of RSI values.
ATR Corr Correlation of Average True Range (volatility alignment).
Volume Corr Correlation of raw volume (detects relative liquidity/interest).
VW-Corr Volume-Weighted correlation — weights daily returns by volume, giving more importance to high-volume days.
Slide 6: Core Calculations – Risk & Performance
Beta & Alpha (Annualized)
Beta = Covariance(asset, benchmark) / Variance(benchmark)
Alpha = (Mean_Asset_Return - Beta × Mean_Benchmark_Return) × 100 × 252
Interpretation: Beta > 1 = higher volatility than benchmark; Alpha > 0 = outperformance.
Relative Strength (RS) Momentum
RS Ratio = Close_Asset / Close_Benchmark
RS Momentum = (RS_Ratio / SMA(RS_Ratio, length) - 1) × 100
Positive = asset is strengthening relative to benchmark.
Spread Z-Score (Mean-Reversion)
Log Spread = ln(Close_Asset / Close_Benchmark)
Z = (Log_Spread - Mean(Log_Spread)) / StdDev(Log_Spread)
Extreme positive = asset is overextended vs benchmark (sell signal).
Slide 7: Grid 1 – Quant Heatcard (Visual Dashboard)
Position Options: 9 positions (Top/Bottom + Left/Center/Right)
Text Size: Tiny, Small, Normal
Top Row (6 cards):
Card Display Color Logic
Beta Value vs 1.0 Green if ≥ 1.0
Alpha (Ann.) Annualized % Green if positive, Red if negative
Price Corr Correlation Green if ≥ threshold
VW-Corr Volume-Weighted Corr Gold if ≥ threshold
RS Momentum % vs benchmark Green if positive, Red if negative
Spread Z-Score Z value Gold if ≥ Z-threshold (overextended)
Slide 8: Grid 1 – Quant Heatcard (Continued)
Bottom Row (6 cards):
Card Display Color Logic
Return 1D % change Green if positive, Red if negative
Return 1W % change (weekly close) Green if positive, Red if negative
Return 1M % change (monthly close) Green if positive, Red if negative
Quant Signal "ALPHA PASS" or "NEUTRAL" PASS if: corrClose ≥ threshold AND RS Momentum > 0 AND Beta > 0.8
Benchmark Symbol text (e.g., "SPY") Cyan highlight
Lookback e.g., "30 bars" Muted display
Slide 9: Grid 2 – Detailed Breakdown Table
Position Options: 9 positions (separate from Grid 1)
Text Size: Tiny, Small, Normal
Row Col 0 Col 1 Col 2 Col 3
Row 0: Correlations Price Corr RSI Corr ATR Corr Volume Corr
Row 1: Structure Beta Alpha Spread Z-Score RS Momentum
Row 2: Selected Metric Selected Metric Name Correlation of Selected Metric PASS/FAIL (≥ threshold) Lookback (e.g., "30B")
Color Coding:
Green = Strong/Positive
Red = Weak/Negative
Cyan = Informational
Gold = Extreme/Warning
Slide 10: Plots & Screener Exports
The indicator also plots directly on the chart pane (below price):
Plot Color Display
Price Correlation (%) Blue (linewidth 2) Main chart pane
VW-Correlation (%) Yellow (linewidth 1) Main chart pane
Threshold Upper/Lower Green/Red dashed lines ±70% bands
Beta Teal Data Window + Status Line
Alpha (%) Green Data Window + Status Line
RS Momentum (%) Purple Data Window + Status Line
Z-Score Orange Data Window + Status Line
Return 1D/1W/1M Purple/Orange/Red Data Window + Status Line
These enable screeners and multi-ticker comparisons using TradingView's Data Window.
Slide 11: Alert Conditions – Automated Signals
The indicator generates 3 distinct alert conditions for automated trading notifications:
Signal Condition
BUY / Accumulation corrClose ≥ threshold AND corrVW ≥ threshold AND RS Momentum > 0 AND Beta > 0.8 AND Z-Score < zThreshold
HOLD / Neutral corrClose ≥ threshold AND RS Momentum ≤ 0.5 AND Z-Score < zThreshold
SELL / Divergence RS Momentum < 0 OR corrClose < 0.20 OR Z-Score ≥ zThreshold
Alert Messages include: Ticker name and clear reasoning (e.g., "High correlation, positive RS momentum against benchmark, and stable Z-score.")
Slide 12: Use Cases & Applications
Scenario How the Indicator Helps
Sector Rotation Compare a stock to sector ETF (e.g., AAPL vs. XLK). High correlation + positive RS = sector leader.
Pair Trading Z-Score tells you when spread is overextended — mean-reversion entry/exit points.
Risk Management Beta tells you if stock is riskier than market; ATR correlation shows volatility alignment.
Factor Screening The "Quant Signal" (ALPHA PASS) quickly flags stocks with strong fundamentals vs benchmark.
Momentum Investing RS Momentum identifies stocks gaining relative strength.
Earnings / Event Analysis 1D/1W/1M returns show immediate impact vs benchmark.
Slide 13: Technical Implementation Highlights
Lookahead Handling: Uses barmerge.lookahead_off for reference security to avoid repainting.
Rolling Windows: All statistics use TradingView's ta.correlation, ta.sma, ta.stdev for consistency.
Volume-Weighted Correlation: Custom computation using volume-weighted returns for more robust correlation.
Dynamic Tables: Uses table.new with position constants, allowing users to place grids anywhere on screen.
Alerts: Built-in alertcondition() for automated strategy integration.
Compatibility: Requires Pine Script v6. Works on all timeframes (1min to monthly).
Slide 14: Customization Options Summary
Group Parameter Options
Core Quant Lookback, Reference Symbol, Correlation Metric, Thresholds 10-500, 40+ ETFs, 7 metrics, 0.05 steps
Grid 1 (Heatcard) Show/Hide, Position, Text Size 9 positions, 3 sizes
Grid 2 (Details) Show/Hide, Position, Text Size 9 positions, 3 sizes
Oscillators RSI, MACD, Stochastic, CCI, Williams, ATR lengths User-adjustable
Result: A fully configurable tool adaptable to any trading style — from day trading to long-term investing.
Slide 15: Demonstration – Example Output
Ticker: AAPL
Benchmark: SPY
Lookback: 30 bars
Metric Value Signal
Beta 1.12 High volatility
Alpha +2.3% Positive outperformance
Price Corr 0.85 Strong alignment
VW-Corr 0.81 Volume-confirmed correlation
RS Momentum +1.2% Gaining relative strength
Z-Score +0.45 Within normal range
Quant Signal ALPHA PASS Bullish
Alert: BUY condition triggered.
Slide 16: Summary & Value Proposition
What this indicator delivers:
✅ Institutional-grade quant dashboard in a single script
✅ Multi-dimensional analysis — not just price, but volatility, volume, momentum, and risk
✅ Visual clarity with two customizable data grids
✅ Actionable alerts for systematic trading
✅ Screener-ready outputs via Data Window
✅ Fully configurable to fit any strategy or timeframe
Ideal for: Swing traders, sector rotators, pair traders, risk managers, and quantitative researchers using TradingView.
FOR EDUCATIONAL PURPOSES ONLY
NOT A FINANCIAL ADVICE 指标

New Highs/Lows Market BreadthNew Highs/Lows Market Breadth
This indicator is intended as a daily market breadth and participation tool. It is most useful for confirming the internal strength or weakness behind U.S. equity market price trends, monitoring changes in breadth momentum, and identifying periods when participation is expanding or contracting.
New Highs/Lows Market Breadth measures the difference between the number of securities making new highs and new lows across several major U.S. indices and exchanges.
The core calculation is:
Net Breadth = New Highs − New Lows
Positive readings indicate that new highs are outnumbering new lows, while negative readings indicate that new lows are dominating. This provides a view of participation beneath the surface of the market and can help identify strengthening or deteriorating internal conditions that may not be obvious from price alone.
Market Universes
The indicator supports multiple breadth universes from a single dropdown:
Indices
Nasdaq Composite
Nasdaq 100
S&P 500
Exchanges
NYSE
AMEX
Nasdaq
NYSE + AMEX + Nasdaq combined
The combined exchange option sums the new-high and new-low counts from all three exchanges before calculating Net Breadth, providing a broader measure of U.S. exchange-level participation.
Lookback Periods
Breadth can be evaluated using:
1 Month
3 Months
6 Months
52 Weeks
These selections refer to the lookback used to define a new high or new low, not the chart timeframe. For example, the 1 Month setting measures securities making new one-month highs and lows during the applicable trading session.
Shorter lookbacks generally respond more quickly to changes in participation, while longer lookbacks provide a broader view of intermediate- and long-term market strength or weakness.
Breadth Display
By default, the indicator plots Net New Highs/Lows as a column histogram around the zero line.
The entire Highs/Lows histogram can be disabled independently. This allows the indicator pane to display only the moving average, background condition, or other enabled components.
An optional Display Highs and Lows Separately setting replaces the net histogram with separate positive columns for new highs and negative columns for new lows. This makes it easier to see whether changes in Net Breadth are being driven by expanding highs, expanding lows, or both.
Moving Average
An optional moving average can be applied directly to Net New Highs/Lows to smooth short-term fluctuations and make changes in breadth direction easier to identify.
Available moving average types include:
SMA
EMA
WMA
RMA
Length, line width, and color are customizable.
The moving average can also be colored according to its slope:
Rising MA = user-defined rising color
Falling MA = user-defined falling color
Flat MA = default MA color
Slope coloring focuses on whether breadth momentum is improving or deteriorating rather than simply whether breadth is above or below zero.
For example, Net Breadth can remain negative while its moving average begins rising. This indicates that internal conditions are improving even though new lows may still exceed new highs. Conversely, a falling moving average above zero can indicate weakening participation before Net Breadth becomes negative.
Background Breadth Streaks
An optional background highlight identifies sustained periods of positive or negative Net Breadth.
The number of consecutive bars required to activate the background is user-defined, with 3 bars as the default.
Once the selected threshold is reached:
Consecutive positive Net Breadth bars activate the positive background color.
Consecutive negative Net Breadth bars activate the negative background color.
The background remains active while the qualifying streak continues.
This feature is designed to distinguish persistent breadth conditions from isolated positive or negative readings.
Highs/Lows Table
An optional table displays the current number of securities making Highs and Lows for the selected market universe and lookback period.
This provides the underlying counts behind the Net Breadth calculation without requiring the Highs/Lows histogram to remain visible.
Confirmed Bars and Repainting
Repaint is disabled by default.
With Repaint disabled, the indicator displays only confirmed chart bars. This applies to the breadth plots, moving average, background conditions, and table updates.
Enabling Repaint allows the current unconfirmed chart bar to update as incoming data changes. Values displayed on an open bar can therefore change until that bar is confirmed.
Usage and Limitations
Use a standard 1-day chart for the intended calculation. The underlying TradingView New High/New Low market-statistics series used by this indicator are daily-session breadth data. The indicator requests those series using the chart's current timeframe, so 1D is the recommended and intended chart timeframe.
Intraday timeframes are not recommended. The source breadth series are based on daily market statistics rather than true intraday New High/New Low counts. Depending on the selected source and data availability, intraday charts may show unavailable, repeated, incomplete, or otherwise misleading values.
Weekly and monthly charts change the meaning of the display. Because the script requests the breadth source at the chart timeframe, using a weekly or monthly chart does not produce the same bar-by-bar series as a daily chart. Moving-average length and consecutive-background settings will also operate on weekly or monthly bars rather than trading days. Use 1D when you want the indicator to behave as designed.
Use a time-based chart rather than synthetic/non-time-based chart types. Standard candles, bars, or lines on a daily timeframe provide the clearest alignment with the daily breadth source data. Renko, Range, Kagi, Point & Figure, and similar synthetic chart types can distort the relationship between chart bars and daily breadth observations.
Repaint should normally remain disabled for confirmed analysis. Enabling it allows the current unconfirmed chart bar to change before closing. Historical bars remain confirmed, but the most recent open bar should not be treated as final.
Data availability is dependent on TradingView's underlying market-statistics symbols. Historical coverage may vary by index, exchange, and breadth lookback, and missing source data cannot be reconstructed by the indicator.
Credit: This indicator is based on the open-source Net New Highs/Lows script by Fred6724, with substantial modifications and additional functionality. 指标

Liquidity Sweep Buy/Sell [v6]# Liquidity Sweep Buy/Sell
## Overview
**Liquidity Sweep Buy/Sell ** is a price-action indicator designed to identify potential **liquidity sweeps** around important swing highs and swing lows.
The indicator looks for situations where price moves beyond a previous high or low, takes the available liquidity, and then closes back inside the previous level.
It can help traders identify potential **reversal areas, BUY/SELL opportunities, entries, and exits**.
> **Important:** This indicator is a technical analysis tool, not a guarantee of future price movement. Always use proper risk management and confirm signals with your own analysis.
---
## 🔹 What Is Liquidity?
In simple terms, **liquidity** is an area where many orders may be located.
Common liquidity areas include:
* Previous swing highs
* Previous swing lows
* Equal highs
* Equal lows
* Previous session highs/lows
* Important support and resistance levels
For example:
If price forms a previous high and later moves above that high, traders may interpret this move as a **liquidity sweep**.
If price then quickly closes back below the previous high, it can indicate that the breakout failed and that price may potentially reverse.
---
# 🟢 How the BUY Signal Works
The indicator searches for a previous swing low.
When price moves below that liquidity level and then closes back above it, the indicator can generate a **BUY signal**.
### Example:
**Previous Low → Price Sweeps Below → Price Closes Back Above → BUY**
This can indicate that sell-side liquidity below the previous low has been taken.
The indicator can then display:
**🟢 BUY**
and
**BUY ENTRY**
---
# 🔴 How the SELL Signal Works
The indicator searches for a previous swing high.
When price moves above that liquidity level and then closes back below it, the indicator can generate a **SELL signal**.
### Example:
**Previous High → Price Sweeps Above → Price Closes Back Below → SELL**
This can indicate that buy-side liquidity above the previous high has been taken.
The indicator can then display:
**🔴 SELL**
and
**SELL ENTRY**
---
# 📈 EMA Trend Filter
The indicator includes an optional **EMA Trend Filter**.
By default, it uses the **200 EMA**.
### Bullish Environment
When price is above the EMA, the indicator favors BUY signals.
### Bearish Environment
When price is below the EMA, the indicator favors SELL signals.
This filter can help reduce signals that go against the broader market direction.
You can disable the EMA filter from the settings if you want to use pure liquidity-sweep signals.
---
# 📊 Volume Filter
An optional **Volume Filter** is also available.
When enabled, the indicator compares current volume with the average volume.
This can help traders focus on liquidity sweeps that occur with relatively stronger market activity.
The volume filter is disabled by default.
---
# 🎯 How to Use the Indicator
## Step 1 — Add the Indicator
Open TradingView and add:
**Liquidity Sweep Buy/Sell **
to your chart.
---
## Step 2 — Identify the Market Trend
First look at the 200 EMA.
### Price Above EMA
Focus more on:
**🟢 BUY signals**
### Price Below EMA
Focus more on:
**🔴 SELL signals**
---
## Step 3 — Look for Liquidity
Watch the red and green liquidity levels.
### Red Level
Represents a previous swing high and potential **buy-side liquidity**.
### Green Level
Represents a previous swing low and potential **sell-side liquidity**.
---
## Step 4 — Wait for the Sweep
Do not enter simply because price touches a liquidity level.
Wait for price to **sweep the level and close back through it**.
This is the important part of the setup.
---
## Step 5 — Confirm the Signal
A stronger setup can occur when:
**Liquidity Sweep + Trend Direction + Strong Candle + Volume**
all support the same direction.
For example:
**Price above 200 EMA → price sweeps a previous low → candle closes back above the low → BUY signal**
This gives you a more structured setup instead of entering randomly.
---
# 🧠 How Beginners Can Learn It
If you are new to liquidity trading, learn these concepts in this order:
### 1. Market Structure
Learn:
* Higher High
* Higher Low
* Lower High
* Lower Low
### 2. Support & Resistance
Understand how previous highs and lows can become important areas.
### 3. Liquidity
Learn why traders watch:
* Previous highs
* Previous lows
* Equal highs
* Equal lows
### 4. Liquidity Sweeps
Understand the difference between:
**Breakout**
and
**Liquidity Sweep**
A sweep moves through a level but then returns back inside it.
### 5. Confirmation
Learn to wait for the candle close rather than entering immediately when price touches a level.
---
# 💡 Simple Strategy Example
### BUY Setup
1. Price is above the 200 EMA.
2. A previous swing low is visible.
3. Price moves below that low.
4. Price closes back above the low.
5. BUY signal appears.
6. Look for confirmation before entering.
7. Place your stop-loss according to your own risk-management rules.
8. Target a logical resistance/liquidity area.
### SELL Setup
1. Price is below the 200 EMA.
2. A previous swing high is visible.
3. Price moves above that high.
4. Price closes back below the high.
5. SELL signal appears.
6. Look for confirmation before entering.
7. Place your stop-loss according to your own risk-management rules.
8. Target a logical support/liquidity area.
---
# ⚙️ Recommended Settings
### Beginner
* Swing Length: **5**
* EMA Filter: **ON**
* EMA Length: **200**
* Volume Filter: **OFF**
### More Signals
Reduce the swing length.
For example:
**3–5**
This can make the indicator more sensitive.
### Stronger / Fewer Signals
Increase the swing length.
For example:
**7–10**
This focuses more on larger swing points.
---
# ⏱️ Timeframe
The indicator can be used on multiple timeframes.
For beginners, consider studying:
* 5-minute
* 15-minute
* 1-hour
* 4-hour
Do not assume that a signal on a lower timeframe is automatically stronger than a signal on a higher timeframe.
A useful approach is to identify the larger trend on a higher timeframe and then look for liquidity sweeps on a lower timeframe.
---
# 🚨 Important Risk Warning
No indicator can predict the market with 100% accuracy.
Liquidity sweeps can fail, especially during:
* High-impact news
* Extremely volatile markets
* Low-liquidity periods
* Strong trend continuation
* Sudden market manipulation or large orders
Always use:
**Risk Management + Stop Loss + Position Sizing + Market Analysis**
Never risk money you cannot afford to lose.
---
# 🔔 Alerts
The indicator includes TradingView alert conditions for:
* 🟢 Liquidity BUY
* 🔴 Liquidity SELL
* Exit LONG
* Exit SHORT
You can create alerts from TradingView's **Create Alert** menu after adding the indicator to your chart.
---
# 📚 How to Practice
Before using this indicator with real money, open a TradingView chart and study historical examples.
For every signal, ask yourself:
1. Where was the liquidity?
2. Did price actually sweep the level?
3. Did the candle close back through the level?
4. What was the trend?
5. Was price above or below the 200 EMA?
6. Was there strong volume?
7. Where would the stop-loss logically go?
8. Where was the next liquidity/support/resistance area?
Keep a trading journal and record both winning and losing setups.
The goal is not to take every signal.
The goal is to **understand why the signal appeared**.
---
# ⭐ Final Note
**Liquidity Sweep Buy/Sell ** is designed to make liquidity-based price action easier to visualize.
Use the indicator as a **confirmation and analysis tool**, not as an automatic trading system.
The best results come from combining the indicator with:
**Market Structure + Liquidity + Trend + Confirmation + Risk Management.**
Trade smart. Protect your capital. Learn the setup before trading it live.
指标

指标

Multi Symbol Participation Pulse [Pineify]Multi Symbol Participation Pulse
Overview
Multi Symbol Participation Pulse tests whether a chart move has broad support across a custom basket. Its pulse combines return breadth, EMA trend breadth, dispersion, and data coverage. It describes participation, not a forecast or trade signal.
Problem Definition
A simple advance ratio can hide synchronized movement, a few extreme outliers, or a thin sample caused by closed sessions. A one-bar vote also misses established trend position. This script keeps only valid observations in the denominator, separates fast return and slower trend votes, and lowers confidence when votes disagree, dispersion rises, or coverage falls. It measures a finite equal-weight basket, not official exchange breadth.
Design Rationale
Symbols are requested on the chart timeframe with gaps exposed and lookahead disabled. One-bar return direction supplies the fast vote; close versus a configurable EMA supplies slower context. Return dispersion is divided by its rolling EMA, so fragmentation is judged against the basket's recent scale instead of a fixed percentage. Coverage and vote agreement modulate amplitude. This structure suppresses incomplete or internally split evidence even when the raw advance ratio looks decisive.
Key Features
Ten configurable symbol slots with missing and invalid-symbol handling.
Return breadth, trend breadth, coverage, and normalized dispersion.
Confirmed broad-positive, broad-negative, fragmented, and neutral states.
Optional components, halo, rail, divergence markers, dashboard, and alerts.
How It Works
For each valid symbol, the script calculates one-bar return and tests whether close is above its EMA. Positive-return count gives fast participation; above-EMA count gives trend participation. Both ratios are mapped from 0–100% into -100 to +100.
Cross-sectional return standard deviation is divided by its rolling EMA to measure unusual dispersion. Coverage, agreement between the two votes, and dispersion-derived coherence form a bounded confidence term. The pulse blends return and trend votes 55/45 and reduces amplitude when evidence is weak. High relative dispersion also widens the halo.
States update only on confirmed bars. Broad states require the pulse threshold and both votes on the same side of 50%; hysteresis limits threshold chatter. Too few active symbols, low coverage, or warm-up produces no pulse. Invalid symbols return missing data rather than terminating the script. A lower rail maps dispersion into a fixed visual zone.
How Multiple Indicators Work Together
The components form one causal chain. Return breadth detects current participation but can chatter. Trend breadth adds persistence but lags. Dispersion reveals whether votes are compact or split by outliers. Coverage tests whether the sample is representative. Removing a component could make the result lag, overreact, hide fragmentation, or overstate a thin sample; their roles are not interchangeable.
Trading Ideas and Insights
Use the pulse as context, not an entry command. Broad states test whether a move is shared by selected proxies. Fragmentation flags disagreement between headline direction and internal distribution. Fixed-window divergence markers identify price/pulse disagreement for review, not a promised reversal. Compare similar sessions and build the basket around one coherent question.
Unique Aspects
Common breadth plots stop at an advance percentage or advance-decline difference. Here, fast and slow votes remain visible, dispersion is normalized to the basket's history, missing coverage reduces confidence, and confirmed hysteresis limits threshold chatter. Halo width exposes dispersion instead of hiding uncertainty behind the composite line, while the lower rail keeps fragmentation in a stable visual location.
How to Use
Choose a coherent basket and disable unused slots.
Check active coverage before interpreting the pulse.
Read sign and state color, then inspect component separation and halo width.
Use confirmed alerts beside price structure, liquidity, and risk controls.
The default US ETF basket is only an example.
Customization
EMA length controls the slower vote, while the dispersion baseline defines ordinary spread. Minimum active symbols and coverage set the evidence floor. Broad threshold and hysteresis balance sensitivity against stability. Fragmentation and agreement settings govern conflict states. Divergence settings control markers. Visual layers can be hidden without changing calculations.
Assumptions and Limitations
Every enabled symbol receives one vote; there are no constituent weights, official breadth, order flow, or membership data. Sessions, holidays, stale markets, delayed feeds, and permissions can reduce coverage or desynchronize timestamps. Gaps are exposed, so the active subset may change. EMA and dispersion baselines lag and depend on parameters. Pulse, halo, and divergence can change intrabar; states and alerts confirm at bar close. Fixed-window divergence is descriptive, not a reversal prediction. The script does not estimate probability, expected return, sizing, execution, or profitability.
Conclusion
Multi Symbol Participation Pulse turns a custom basket into an auditable breadth portrait. It separates fast and trend participation, dispersion, and coverage, then displays direction and uncertainty together. Use it while respecting asynchronous equal-weight data limits.
指标

VIX Seasonal Analog Composite█ OVERVIEW
VIX Seasonal Analog Composite draws three lines in a separate pane: the average seasonal path of all complete years of VIX history, a composite of the historical years whose year-to-date VIX path most closely resembles the current year, and the current year's own VIX path. The script requests CBOE:VIX daily closes directly, so it displays VIX seasonality on any chart symbol: applied to an S&P 500 chart, the pane still shows the VIX. All lines are expressed as a percentage of each year's first daily VIX close, and both seasonal lines are projected forward to the end of the current calendar year. The thesis is that the remainder of a VIX year can be contextualized by the average behavior of prior years, and more specifically by the subset of prior years that have tracked the current year most closely so far.
█ HISTORY / BACKGROUND
Seasonal averaging is a long-standing technique in technical analysis: normalize each historical year to a common starting point, average across years by position in the calendar, and read the result as the instrument's typical annual path. Applied to the VIX Index, it captures the well-documented tendency of implied volatility to trough in summer and firm into autumn. Its main weakness is that every year receives equal weight, so years with no resemblance to current conditions dilute the picture.
The analog-year refinement addresses this. Instead of averaging all history, it ranks past years by their similarity to the current year's realized path and averages only the closest matches. Variants of this approach appear in institutional volatility research. The specific similarity metric, selection count, and construction details vary by practitioner and are generally not disclosed. This script implements one explicit, reproducible version of the method for the VIX with all parameters exposed as inputs.
█ HOW IT WORKS
The script runs a single accumulation pass over the chart's daily history and defers all computation and drawing to the last bar.
1. On every chart bar, the script requests the CBOE:VIX daily close through `request.security`. Calendar-year boundaries are detected with `year(time)`. The first available VIX close of each year becomes that year's anchor. Every subsequent VIX close is stored as close divided by the anchor, indexed by trading-day-of-year (0 to 252), in a persistent matrix with one row per year. Bars where the VIX returns no data, such as chart history predating 1990, are skipped.
2. On the last bar, completed years are screened for eligibility: a year must contain at least the minimum number of observations (default 200 trading days) to enter any calculation. The current year is always excluded from the historical pools.
3. The seasonal average is computed per trading-day index as the arithmetic mean of the normalized values of all eligible years at that index.
4. Analog ranking begins once the current year has at least the minimum elapsed days (default 10). For each eligible year, the script computes the root mean square error between that year's normalized path and the current year's normalized path over the trading days elapsed so far, skipping missing pairs. Years are ranked by ascending RMSE and the closest N (default 10) are selected. The analog composite is the per-day mean of the selected years across the full 253-day span, including days the current year has not yet reached.
5. Both seasonal lines are drawn as polylines anchored to bar time: actual bar times for elapsed days, then projected dates stepped one calendar day at a time with weekends skipped for the remainder of the year.
6. The current-year line is drawn over elapsed days only. By default it is linearly rescaled so that its year-to-date range maps onto the vertical range of the two seasonal curves, emulating a second axis within a single-scale pane. A label at its last point shows the true unrescaled year-to-date percentage.
7. A table in the top right lists the selected analog years and their RMSE scores.
Ranking is recomputed on every update, so the analog set can rotate as the current year develops.
█ HOW TO USE
Apply the indicator to any daily chart of a symbol that trades on the US equity session calendar, such as an S&P 500 index chart or the VIX itself. The pane always displays VIX seasonality regardless of the chart symbol, which allows the seasonal context to sit directly beneath the index you are analyzing. The logic counts trading days within calendar years using the chart's bars, so it is designed for the daily timeframe only; other resolutions will produce meaningless day indexing. VIX daily history extends to 1990, so a chart with sufficient loaded history builds seasonal pools from roughly three and a half decades of complete years.
The gray line is the unconditional seasonal script: what an average year looks like. The colored composite line is the conditional version: what years resembling this one looked like, including how they finished. The red line is the current year. Divergence between the current year and the composite indicates the year is departing from its closest historical precedents; the table shows which years those precedents are and how tight the fits are (lower RMSE means closer). A rotating analog table across weeks means the current year lacks a stable historical match, which is itself information.
The projected segments beyond the current date are historical averages extended in time. They describe how past years behaved from this calendar point onward. They are not forecasts.
█ SETTINGS
• Top analog years : number of closest historical years in the composite. Default 10.
• Min trading days for an eligible year : observation floor for a year to enter any pool. Default 200.
• Min elapsed days before analog ranking : current-year data required before ranking begins. Default 10.
• Show all-year seasonal average : toggles the gray average line. Default on.
• Show top-N analog composite : toggles the composite line. Default on.
• Show current-year YTD line : toggles the current-year path. Default on.
• Rescale YTD onto seasonal range (RHS-style) : maps the current-year line onto the seasonal
curves' vertical range for readability. Default on.
• Project remainder of year : extends the seasonal lines to year end. Default on.
• Show analog year table : toggles the analog list with RMSE scores. Default on.
• Average color , Analog composite color , YTD color : line colors.
• Line width : width of all three lines. Default 2.
█ WHAT MAKES IT ORIGINAL
Published seasonality scripts typically plot a single all-year average. This script adds a similarity-ranked analog layer computed entirely on the chart: it maintains a full year-by-trading-day matrix of normalized paths, scores every eligible historical year against the current year by RMSE on each update, and averages only the closest matches, so the composite is conditional on how the current year has actually traded rather than on the calendar alone. The construction is fully disclosed and parameterized, including the similarity metric, the selection count, and the eligibility gates. The forward projection is drawn with time-anchored polylines so both seasonal paths extend beyond the last bar to year end, and the current-year line uses an optional range-mapping transform to keep all three curves readable on a single pane scale, with a label preserving the true value.
█ NOTES / LIMITATIONS
• Daily timeframe only. The trading-day indexing that underlies every calculation assumes one bar
per trading day.
• The analog set is re-ranked on every recalculation using the current year's realized path. The
composite line therefore changes shape as the year develops, including its already-drawn portion.
This is inherent to the method, and it means the line you see today is not the line you would
have seen a month ago. Treat it as a conditional historical average, not a signal history.
• The pane always shows the VIX. The chart symbol supplies only the bar grid and timeline.
• Trading-day indexing follows the chart symbol's bars. Chart symbols whose sessions differ from
the US equity calendar, such as symbols with weekend bars or non-US holiday schedules, will
misalign the day indexing. Use a chart symbol on the US equity session.
• The seasonal pools depend on the chart's loaded bar depth and on VIX data availability from
1990. A chart with shallow history averages over fewer years, and less than two complete years
of overlap draws no seasonal lines at all. Chart bars predating 1990 contribute nothing.
• Partial first years, and any year below the observation floor, are excluded by the eligibility
gate.
• Years are capped at 253 trading days; any bars beyond that index within a year are ignored.
• Forward projection steps calendar days and skips weekends but not exchange holidays, so
projected dates drift a few days long by December. Alignment between curves is by trading-day
index and is unaffected.
• With rescaling on, the pane axis is literal for the seasonal lines only. The current-year line's
axis position is a range mapping; read its true value from the label at its endpoint. Early in
a year, a small realized range makes the rescaled line visually exaggerated.
• All output is drawn over the current calendar year plus its projection. The pane is empty over
prior history, which is expected: prior years are inputs to the curves, not drawn objects.
• The script draws with polylines, a label, and a table only, and declares no plot series, so the
pane scale derives from the drawings.
• Nothing in this script is validated as predictive. Both curves are descriptive averages of
historical paths. 指标

EMA 200 Deviation Channels [Statistical Zones] by ZephyrosEMA 200 Deviation Channels is an adaptive overlay indicator that measures the percentage distance between price and the 200-period Exponential Moving Average and converts the recent distribution of those deviations into dynamic statistical zones.
## Purpose
The indicator is designed to show how unusually far the current price has moved away from EMA 200 relative to its own recent behavior.
Instead of placing channels at fixed percentage distances from the moving average, the script calculates the boundaries separately for the selected symbol, timeframe, and historical lookback. This allows the zones to adapt to instruments with different volatility characteristics.
The zones are not buy or sell signals. They identify statistically stretched price locations where a trader may evaluate the possibility of a reversal, consolidation, or return toward the moving average using their own analysis.
## Calculation Method
The indicator performs the following calculations:
1. Calculates EMA 200 using closing prices.
2. Measures the percentage deviation of each closing price from EMA 200:
`Deviation = (Close - EMA 200) / EMA 200 × 100`
3. Creates a rolling sample of deviations using the selected History Length.
4. Calculates the 95th percentile and the 5th percentile of that sample.
5. Converts those percentile values back into price levels around the current EMA 200.
6. Calculates additional outer boundaries from the average extension of observations beyond the 95th and 5th percentile levels.
The main statistical boundaries are:
* Upper Level - the price corresponding to the 95th percentile of historical deviations.
* Lower Level - the price corresponding to the 5th percentile of historical deviations.
* Extreme Upper Level - the 95th-percentile deviation plus the average additional extension above that percentile.
* Extreme Lower Level - the 5th-percentile deviation minus the average additional extension below that percentile.
All boundaries are recalculated continuously using the latest rolling sample.
## Visual Interpretation
* Blue line - EMA 200.
* Light red zone - the area between EMA 200 and the Upper Level.
* Light green zone - the area between the Lower Level and EMA 200.
* Darker red zone - the area between the Upper Level and the Extreme Upper Level.
* Darker green zone - the area between the Extreme Lower Level and the Lower Level.
The colors indicate the direction of the deviation from EMA 200. They do not represent automatic long or short recommendations.
The optional `Extreme Upper` and `Extreme Lower` background highlights mark bars whose closing price is above the Upper Level or below the Lower Level. These background highlights are disabled by default and can be enabled manually in the indicator's Style settings.
## History Length
`History Length for Percentiles` determines how many recent deviation observations are used for the statistical calculations.
The default value is 1000 bars.
* A shorter lookback adapts more quickly to recent market behavior but may produce less stable boundaries.
* A longer lookback changes more slowly and represents a broader historical sample.
The appropriate setting depends on the selected market, timeframe, and analytical objective. Changing the symbol, timeframe, or History Length recalculates the entire statistical distribution.
The indicator requires enough historical data to initialize both EMA 200 and the selected percentile lookback. Until sufficient data is available, some zones and statistical values may remain unavailable.
## Statistics Table
The statistics table is disabled by default. It can be enabled through:
`Settings → Inputs → Show Statistics Table`
The table displays:
* Maximum upward deviation in the current sample.
* Maximum downward deviation in the current sample.
* 95th percentile deviation.
* 5th percentile deviation.
* Average extension above the 95th percentile.
* Average extension below the 5th percentile.
* Current price.
* Current EMA 200 value.
* Current percentage deviation.
* Upper and Lower Levels.
* Extreme Upper and Extreme Lower Levels.
* Current numerical zone classification.
## Zone Classification Output
The script includes a hidden numerical output named `ZEP_EMA_DEV_SIGNAL`.
Despite its technical name, this output is not a trading signal. It is only a numerical classification of the current closing price relative to the calculated zones:
* `3` - below the Extreme Lower Level.
* `2` - between the Extreme Lower Level and the Lower Level.
* `1` - between the Lower Level and EMA 200.
* `-1` - between EMA 200 and the Upper Level.
* `-2` - between the Upper Level and the Extreme Upper Level.
* `-3` - above the Extreme Upper Level.
* `0` - insufficient data, undefined levels, or price exactly at EMA 200.
The hidden output can be used for visual inspection, data export, or integration with other Pine Script tools. It does not create orders, alerts, entries, exits, stop-loss levels, or profit targets.
## Suggested Use
1. Select the market and timeframe you want to analyze.
2. Choose a History Length appropriate for the amount of market history you want the indicator to evaluate.
3. Use EMA 200 as the central reference point.
4. Observe whether price is inside the regular deviation area, inside an outer statistical zone, or beyond the outer boundary.
5. Treat the zones as market context rather than standalone entry instructions.
6. Use independent confirmation such as market structure, price reaction, volume, momentum, or another method appropriate to your trading process.
The indicator can be applied to any market and timeframe with sufficient historical bars. All calculations are performed independently for the current chart symbol and timeframe.
## Originality
The original element of this indicator is its two-stage adaptive channel construction.
The first stage uses rolling 5th and 95th percentiles of percentage deviation from EMA 200. The second stage measures the average continuation beyond those percentile boundaries and uses it to create additional outer zones.
As a result, the channel distances are derived from the observed deviation distribution of the current market and timeframe rather than from a fixed percentage or manually selected distance.
This script is an original implementation by Zephyros and is published with open source code so that all calculations can be inspected.
## Limitations
* The indicator does not calculate or guarantee the probability of a reversal.
* Statistically unusual deviation does not mean that price must immediately return to EMA 200.
* Strong directional markets can remain inside or beyond an extreme zone for an extended period.
* All deviation calculations and zone classifications use closing prices, not candle highs or lows.
* Values on the currently open bar can change as its closing price changes.
* The calculated zones depend entirely on the selected symbol, timeframe, available history, and History Length.
* Very large History Length values can increase calculation time.
* The indicator is not a strategy and does not provide backtest results.
* It should not be used as the sole basis for a trading decision.
指标
