Pine Script®指标
移动平均线
Strateji Tablosu EMA9/WMA30If EMA9 crosses above WMA30 on the 4-hour chart, this is the first BUY signal.
If the price crosses above EMA9 on the daily chart, this is the second BUY signal.
If EMA9 crosses above WMA30 on the daily chart, this is a STRONG BUY signal.
Pine Script®指标
Swiss Army Moving Averages + VwapJust thew together a Swiss Army Knife of Moving Averages
4 EMA's, 4 SMA's, and Vwap all rolled into one simple indicator
that just uses one slot on your plans amount I hope this is useful
Happy Trading,
1. Exponential Moving Averages (EMAs)
EMA What it shows you Why it can be handy
EMA 1 (default length 9) Very short‑term trend, reacts quickly to price
changes. Good for spotting rapid momentum shifts or early entry
signals.
EMA 2 (default length 20) Short‑term trend, a bit smoother than the
9‑period EMA. Often used as a “fast” line in classic EMA cross‑overs.
EMA 3 (default length 50) Mid‑term trend. Helps confirm whether the
shorter EMAs are part of a larger move.
EMA 4 (default length 200) Long‑term trend, very smooth.Serves as a
major support/resistance level; price above it is generally bullish,
below it bearish.
All four EMAs can be turned on or off individually and coloured to your
liking.
2. Simple Moving Averages (SMAs)
SMA What it shows you Why it can be handy
SMA 1 (default length 9) Same short‑term window as EMA 1 but with equal
weighting of each bar. Useful if you prefer a less‑reactive line for
comparison with the EMA.
SMA 2 (default length 20) Classic “20‑day” SMA many traders watch.
Often used as a benchmark for medium‑term price action.
SMA 3 (default length 50) Mid‑term average, smoother than the 20‑day
SMA. Helps identify the overall direction over a few weeks.
SMA 4 (default length 200) Long‑term average, similar to the EMA 4 but
calculated differently. Acts as a strong support/resistance zone;
many traders treat a price crossing the 200‑SMA as a major signal.
Again, each SMA can be shown or hidden and coloured independently.
3. Volume‑Weighted Average Price (VWAP)
What it is: VWAP is the average price of the instrument weighted by the
amount of volume traded at each price. In other words, it tells you the
price level where the bulk of the day’s (or chosen period’s) trading
activity occurred.
Why it matters:
Institutional traders often aim to buy below VWAP and sell above it.
It acts as a dynamic support/resistance line that adapts to both price
and volume.
On intraday charts it gives a clearer picture of “fair value” than a
plain moving average.
Extra VWAP options in this script
Option What it does for you
Anchor period (Session, Week, Month, Quarter, Year, Decade, Century,
Earnings, Dividends, Splits) Instead of resetting every trading day, the
VWAP can be anchored to a longer window (e.g., weekly VWAP) or to
specific corporate events. This lets you see a longer‑term volume‑weighted
price reference.
Hide on daily‑or‑higher timeframes If you’re looking at a daily, weekly,
or monthly chart, you can automatically hide the VWAP to keep the view
clean.
Offset Shifts the VWAP line left or right on the chart, useful for
visual alignment with other studies.
4. VWAP “Bands”
Think of these as dynamic envelopes around the VWAP, similar to Bollinger
Bands but based on the VWAP’s volatility.
Band #1 (default multiplier 1) – a thin envelope close to the VWAP.
Band #2 (multiplier 2) – a wider envelope, optional.
Band #3 (multiplier 3) – the widest envelope, also optional.
How the bands are calculated
You can choose between two methods:
Standard Deviation – the band distance equals a multiple of the VWAP’s
standard deviation (a measure of how spread out prices are).
Percentage – the band distance is a percentage of the VWAP itself (e.g.,
1 % above/below).
Why you might use them
Support / resistance zones: Prices bouncing between the bands can
indicate range‑bound trading.
Volatility cues: Wider bands mean higher volatility; tighter bands
suggest a calmer market.
Entry / exit filters: Some traders only take trades when price breaks
above the upper band (bullish) or below the lower band (bearish).
Each band can be turned on/off, and the fill between the upper and lower
lines is shaded lightly so you can see the zone at a glance.
5. User Controls (the “inputs” you see in the settings pane)
Control What you can change
Show / Hide toggles (for each EMA, SMA, and each band) Instantly decide
which lines you want on the chart without editing the script.
Lengths (e.g., 9, 20, 50, 200) Adapt the moving‑average windows to
suit your trading style or the asset’s typical volatility.
Colors Pick colors that fit your chart theme or help you
differentiate the lines quickly.
VWAP anchor selection Switch between daily VWAP, weekly VWAP, monthly
VWAP, or event‑based VWAP with a single dropdown.
Band multipliers Change how far the bands sit from the VWAP (e.g., 1×,
2×, 3×).
Calculation mode (Standard Deviation vs. Percentage) Choose the
method that matches how you interpret volatility.
Offset Nudge any plotted line left/right for visual alignment.
Pine Script®指标
EMA 9/21 Shading OnlyThis is a 9 and 21 EMA cross over indicator that shades green when the 9 EMA is over the 21, and shades red when the 21 is over the green.
Pine Script®指标
Adaptive Entropy Trend [QuantAlgo]🟢 Overview
Adaptive Entropy Trend is a trend-following indicator built on Shannon information theory rather than conventional price averaging. It quantifies the statistical disorder of recent log returns to determine whether the market is in a directional regime or a random one, then feeds this entropy reading into every layer of the system simultaneously, helping traders identify directional shifts that are validated by both low-entropy momentum conditions and genuine volatility expansion across different timeframes and markets.
🟢 How It Works
The foundation of the indicator is a per-bar entropy calculation built from the distribution of log returns over the lookback window. Log returns are computed and their range is divided into equal-width histogram bins:
logReturn = math.log(close / close )
minReturn = ta.lowest(logReturn, lookbackLen)
maxReturn = ta.highest(logReturn, lookbackLen)
returnRange = maxReturn - minReturn
Each historical return within the lookback is assigned to a bin, building a frequency distribution. Shannon entropy is then calculated from the probability of each bin, measuring how uniformly returns are spread across the range:
probability = array.get(binCounts, i) / lookbackLen
if probability > 0
entropy := entropy - probability * math.log(probability) / math.log(2)
A uniform distribution produces maximum entropy, reflecting a chaotic, non-directional market. A concentrated distribution produces low entropy, reflecting a market where returns are clustering in a consistent direction. The raw entropy is normalized against the theoretical maximum for the bin count to produce a stable 0-1 score:
normalizedEntropy = maxEntropy > 0 ? entropy / maxEntropy : 0.5
This score is then wired directly into the EMA smoothing factor. Higher entropy lengthens the effective period of the EMA, insulating it from noise. Lower entropy shortens it, allowing the EMA to track price closely during genuine trends:
adaptiveAlpha = 2.0 / (lookbackLen * (0.3 + normalizedEntropy * 1.4) + 1.0)
adaptiveEma := na(adaptiveEma) ? close : adaptiveEma + adaptiveAlpha * (close - adaptiveEma)
The same entropy reading drives band width through an inverted trend strength factor. Unlike volatility-based bands that widen during noise, these bands widen specifically during trending conditions and tighten during choppy ones:
trendStrength = 1.0 - normalizedEntropy
fastBandWidth = atr * fastMultiplier * (0.5 + trendStrength)
slowBandWidth = atr * slowMultiplier * (0.5 + trendStrength)
Finally, trend state is determined when price breaks beyond the inner bands, and transitions are tracked for alert conditions:
if close > innerUpper
trendDirection := 1
else if close < innerLower
trendDirection := -1
trendTurnedBullish = trendDirection == 1 and trendDirection != 1
trendTurnedBearish = trendDirection == -1 and trendDirection != -1
This creates a self-regulating trend system where the EMA baseline, the trigger threshold, and the visual envelope all adapt together from the same entropy source, rather than using a fixed center with adaptive edges or vice versa.
🟢 Signal Interpretation
▶ Bullish Trend (Price Above Inner Upper Band, Green): When price closes above the inner upper band, the indicator switches to bullish mode with bullish coloring across all visual elements = Confirmed uptrend signal for trend-following long positions. Because the inner band expands in low-entropy trending conditions, a bullish confirmation in a genuinely directional market requires a more meaningful breakout than in a noisy one. The trend remains bullish until price breaks below the inner lower band, allowing traders to stay positioned through normal pullbacks that remain within the band range.
▶ Bearish Trend (Price Below Inner Lower Band, Red): When price closes below the inner lower band, the indicator switches to bearish mode with bearish coloring throughout all visual elements = Confirmed downtrend signal for short positions or long exit signals. The adaptive band floor ensures the trigger threshold in choppy, high-entropy markets is tighter, reducing the risk of false breakdowns on thin directional moves. The trend remains bearish until price breaks above the inner upper band.
▶ Neutral Zone (Price Between Inner Bands): When price trades between the inner upper and lower bands, the indicator holds its previous trend direction = Continuation of existing trend during consolidation or normal volatility retracements. This prevents whipsaws during sideways action by requiring price to make a statistically meaningful move beyond the entropy-scaled band boundaries rather than reacting to minor crosses of the adaptive EMA centerline.
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets for different trading approaches and timeframes. "Default" provides balanced trend detection for swing trading on 4-hour and daily charts, "Fast Response" delivers quicker trend signals for intraday trading on 1-minute to 1-hour charts, and "Smooth Trend" focuses on major trend changes for position trading on daily to weekly timeframes.
▶ Built-in Alerts: Three alert conditions enable automated monitoring of trend changes without constant chart watching. "Bullish Trend Signal" triggers when the indicator switches to bullish mode after price breaks above the inner upper band, alerting for potential long entries. "Bearish Trend Signal" activates when the indicator switches to bearish mode after price breaks below the inner lower band, signaling potential short entries or long exits. "Trend Direction Changed" provides a combined alert for any trend transition regardless of direction, allowing traders to monitor both bullish and bearish opportunities with a single alert setup.
▶ Visual Customization: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) accommodate different chart backgrounds and aesthetic preferences, with coordinated bullish, bearish, and neutral color schemes applied across all indicator elements. Inner and outer band fills create a two-layer gradient envelope around the adaptive EMA, with the inner zone between the two bands rendered slightly more transparent than the outer zone to preserve natural depth, both controlled by a single fill transparency input (0-100%) so the visual weight of the envelope can be adjusted without disrupting the gradient relationship. Optional bar coloring tints price bars with trend-appropriate colors during bullish and bearish periods, enabling instant visual confirmation of trend state across multiple timeframes without switching between chart and indicator panels.
Pine Script®指标
Supply and Demand Zone Indicator (5m)Core Concept (Simple explanation)
Supply and demand zones are created when:
Price moves away aggressively from an area
This means large institutions entered there
Two main zones:
Demand zone = price exploded upward from a base
→ future buy area
Supply zone = price exploded downward from a base
→ future sell area
Institutional footprint pattern
Demand zone pattern:
Drop → Base → Rally (DBR)
Supply zone pattern:
Rally → Base → Drop (RBD)
Base = small candles
Move = large candles
Entry model (5-minute timeframe)
Buy entry conditions:
Price returns to demand zone
Bullish confirmation candle appears
Optional: break of micro structure
Sell entry conditions:
Price returns to supply zone
Bearish confirmation candle appears
Optional: break of micro structure
Indicator Features we will build
This indicator will:
• Automatically detect supply zones
• Automatically detect demand zones
• Draw rectangles on chart
• Alert when price enters zone
• Show entry signals
Pine Script®指标
Long Short MA %Band Breakout with Fixed StopStrategie with different Moving Averages and a Bandwidth +/- arround it . Works well on daily charts for swingtrades. Profitable underlyings are Main Crypto like BTC, ETH or Solana as well Nasdaq or S+P 500.
There are Parameter to choose for:
The Type of MA: SMA, EMA, TEMA, ALMA, HMA
The Bandwith: % differenz to the upper and lower border
Entry: Long only, short only + long and short
Fixed stop loss (if not needed set it to 90%) in %
Start date, end date
Slippage + provision etc.
The idea is to try differnt setting on your preferred underliying.
For example for BTC/usd: TMA 260 +2/-4%, Stopp 30%, long only, start 2018
Don't optimze too much on the past !
Let me know your comments or suggestions. FWO
Pine Script®策略
Daily Multi MA Transfer (Up to 7 MAs)This script automatically transfers daily MA levels to lower timeframe charts
Up to 7 Moving Averages
User can select either EMA or SMA for each separate MAs
Pine Script®指标
TEMACDTEMACD
-HOW IT WORKS?-
uses 3 ema cross overs and a macd
if one of the emas cross OR the macd cross it opens or close the positions
-FEATURES-
macd and ema settings
propare backtest table
long or short only and long and short backtest types
-DOES IT WORK?-
managed to get a over 1,5 sharpe for volitile assets like BTC with 14% maxDD
for more low volitile assets like QQQ over 1,6 sharpe with 12% maxDD
Pine Script®策略
L-EMALimited Number Display of EMA
The calculation is the same EMA as Trading View's, but the allowing custom input of how long the EMA is displayed.
Pine Script®指标
Trinitrotoluene BTC [ Jo-Pippin ]Trinitrotoluene BTC – Ultimate Market Terminal
Trinitrotoluene BTC is a powerhouse dashboard that consolidates every critical mathematical level a trader needs into one unified table. It allows you to analyze in seconds how far the price is from Volume Weighted Averages (VWAP), historical peaks (ATH), and psychological round numbers.
💎 Key Features
Advanced VWAP Suite: Monitor Weekly, Monthly, Quarterly, Yearly, and even custom Bitcoin Halving anchored VWAP levels in real-time.
ATH Insights: Track exactly how many days have passed since the All-Time High and the percentage distance from the peak.
Psychological Levels: Automatically calculates the distance to the nearest upper and lower "Round Number" milestones.
Dynamic Pivots & Fibs: Plots high/low pivot lines from a custom starting date and calculates internal Fibonacci levels (0.5, 0.618, 0.382) within that range.
Technical Health Check: View Daily RSI and the distance from major moving averages (like the 200 EMA/SMA) for up to 12 symbols simultaneously.
💡 Trading Insights
Cycle Support: The Halving VWAP is a legendary macro level for BTC. Use the dashboard to see how the current price respects this long-term anchor.
Confluence Hunting: Look for symbols where multiple metrics (e.g., Weekly VWAP + Monday Low + Round Number) align in the same percentage area.
Smart Sorting: Sort the table by "Distance to ATH" or "RSI" to find the most oversold or overextended assets in your watchlist.
Note: This indicator was developed by our dear friend Jo-Pippin.
Pine Script®指标
Trend flow X StrategyTrend Flow X Strategy
Trend Flow X Strategy is a rule-based trend identification and trading system built using a composite scoring model derived from multiple technical indicators. The strategy evaluates overall market direction by combining trend, momentum, and strength components into a single unified score.
The system uses a fixed master timeframe of 15 minutes, which is the recommended timeframe for optimal signal consistency, particularly on NIFTY MID SELECT. The strategy is also compatible with other indices, stocks, futures, forex, and crypto instruments.
How It Works
The strategy calculates a directional score using the following technical components:
• EMA 20 and EMA 50 for short and medium trend direction
• SMA 20 and SMA 50 for additional trend confirmation
• RSI for momentum strength evaluation
• MACD for trend continuation and reversal confirmation
• ADX with DI+ and DI- for directional strength validation
• Williams %R for momentum positioning within recent price range
Each component contributes positively or negatively to the overall score. The combined score determines the directional bias.
Score Interpretation
• Score greater than zero indicates bullish conditions
• Score less than zero indicates bearish conditions
• Score equal to zero indicates neutral conditions
Trade Execution
The strategy executes trades only after confirmed candle close to ensure signal stability. This helps avoid intra-bar fluctuations and maintains consistent backtesting and live behavior.
Recommended Usage
Primary recommended instrument: NIFTY MID SELECT
Recommended timeframe: 15 minutes
Compatible with:
• NIFTY
• BANKNIFTY
• FINNIFTY
• Stocks
• Futures
• Forex
• Crypto
Key Features
• Open-source and fully transparent logic
• Uses confirmed bar data only
• No repaint behavior
• No future data access
• Multi-indicator composite scoring system
• Suitable for systematic trading and research
• Compatible with multiple markets
Execution Model
Orders are processed using confirmed bar close values. Commission and slippage parameters are included to simulate more realistic execution conditions.
Important Information
This script is provided for educational and research purposes only. Users should evaluate and test the strategy according to their own requirements before using it in live trading environments.
Open-Source License
This script is published as open-source to support transparency, learning, and further development by the TradingView community.
Pine Script®策略
Dave's Customizable SMA Suite (Simple Moving Averages, Arete)Vibe coded with the help of Google Gemini 3... haha. It's my solution to have everything I need for SMAs in one indicator. It comes set to Arete Trading's prefered SMAs of 12, 22, and 55, and then has the 100 and 200 as well. You can turn any off and any time. You can also set your own for all 5 SMAs. ALSO, you can change the time frame to be different than the chart so that you can see the daily SMAs on the 30 minutes chart, for example.
I hope you guys like it!
Pine Script®指标
Custom EMA SMA Ribbon
Indicator name and purpose
Custom EMA SMA Ribbon is a six-layer moving average ribbon built to show trend alignment, momentum structure, and signal readiness in a single glance. Rather than relying on one crossover, it renders a stacked relationship between fast, medium, and slow averages so the trend context is visible without extra indicators. The purpose is to make trend direction, trend stability, and momentum alignment readable at a glance, while also providing filtered entry signals and a visual status matrix that summarizes the current bias against each moving average.
Long set up
Short set up
Mixed scenario
What it does
Each moving average layer is colored based on whether it is above or below the next slower layer. When the ribbon is stacked with fast lines above slow lines, the structure is bullish. When fast lines fall below the slower lines, the structure is bearish. This layered coloring reveals whether the trend is cleanly aligned or mixed. The script also highlights full alignment, where all fast layers sit above or below the slowest line, which is usually the most stable trend condition. In addition to the visual ribbon, it generates trend-filtered signals: a bullish signal appears only when the slow ribbon is aligned bullish and MA1 crosses above MA2, while a bearish signal appears only when the slow ribbon is aligned bearish and MA1 crosses below MA2. A signal status matrix in the chart corner shows whether price is above or below each moving average, giving a compact snapshot of current bias without scanning every line.
How it works in detail
The indicator calculates six moving averages from a single price source. You can use EMA for a more responsive ribbon or SMA for a smoother ribbon that reduces noise. Each line’s color is determined by its position relative to the next slower line, building a visible map of internal trend health. The slowest line acts as the anchor. If all faster lines remain above it, the ribbon is fully bullish. If all faster lines remain below it, the ribbon is fully bearish. The trend-filtered signals add a momentum layer: they require a clean macro stack first, then confirm entry with the fast crossover of MA1 and MA2. Signals are plotted as tiny circles, so they do not clutter the chart. Bullish signals plot at the bottom in green, bearish signals plot at the top in red. Optional background shading emphasizes the full alignment zones, and all signal states can be confirmed on bar close with the non-repainting toggle. The signal status matrix is updated on the last bar and labels each MA as LONG or SHORT depending on whether the current close is above or below that line, allowing quick context checks during live monitoring.
Default settings
The default lengths 10, 20, 50, 100, 150, and 200 create a balanced mix of short-term, mid-term, and long-term context. The 10 and 20 lengths capture fast swings and early shifts. The 50 and 100 lengths reflect the core trend structure. The 150 and 200 lengths anchor the ribbon to the broader market bias. This combination makes it easy to see if short-term momentum is moving with the larger trend or if it is fighting it. EMA is selected by default to keep the ribbon responsive enough for intraday and swing traders, but you can switch to SMA for smoother, slower trend mapping. With the default configuration, the signal logic is naturally conservative because the faster cross must occur only after MA3, MA4, MA5, and MA6 are stacked in the same direction, filtering many counter-trend crosses. The matrix defaults to the bottom right so it stays visible without covering price action, but you can move it to any corner or center position.
How to use it on charts
Use the ribbon as a trend filter first. When most lines are green and stacked in order, the trend is bullish and pullbacks can be treated as potential continuation zones. When most lines are red and stacked downward, rallies can be treated as corrective unless the stack flips. The strongest trend environments occur when the ribbon is fully aligned above or below the slowest line. If the ribbon becomes mixed with alternating colors, that signals transition or consolidation and signals should be treated more cautiously. In those mixed states, ignore the MA1/MA2 crosses because the macro alignment filter will not allow signals, which is intentional to reduce noise. The matrix helps confirm whether price is holding above multiple layers during a bullish trend or below multiple layers during a bearish trend, which can support trade management decisions like scaling in or tightening stops.
Signal logic explained
Bullish signal requirements: MA3 above MA4, MA4 above MA5, and MA5 above MA6 must all be true, confirming a clean bullish macro stack. Once that macro alignment exists, a bullish signal is generated when MA1 crosses above MA2. This is the earliest momentum entry that still respects the larger trend. Bearish signal requirements: MA3 below MA4, MA4 below MA5, and MA5 below MA6 must all be true. Once that macro alignment exists, a bearish signal is generated when MA1 crosses below MA2. This ensures the momentum entry is taken only in the direction of the larger ribbon stack. Signals appear as tiny circles to keep the chart clean: white at the bottom for bullish signals, black at the top for bearish signals. The matrix adds a second layer of confirmation by showing whether the close remains above each MA during a bullish signal or below each MA during a bearish signal.
Practical usage examples
Trend continuation example: price rises, the ribbon is fully bullish, and fast lines stay above the slowest line during pullbacks. When MA1 crosses back above MA2 after a shallow pullback, the green circle appears at the bottom, indicating a momentum continuation aligned with the macro structure. If the matrix also shows LONG across most rows, it confirms that price remains above the key layers. Trend reversal example: the ribbon compresses, fast lines cross down, and the full alignment flips bearish after several mixed states. Once MA3 to MA6 are stacked bearish, the red top circle appears when MA1 crosses below MA2, signaling the first momentum entry in the new trend direction. If the matrix shifts to SHORT across multiple rows, it confirms the shift in control.
All Long signals on matrix
Mixed signals on matrix
How the components work together
The layered coloring shows immediate, mid, and macro alignment in one view. The full alignment state acts as a high confidence filter for trend bias. Optional background shading gives a quick visual signal of those high confidence zones. The trend-filtered MA1/MA2 cross signals provide a concise momentum trigger that only fires when the broader ribbon is aligned. The signal status matrix summarizes price position versus each MA, helping traders quickly gauge whether momentum entries are supported by broader structure. Together these components provide a complete trend map, entry framework, and state dashboard without overloading the chart.
What makes this script original
This ribbon is not a simple fast slow crossover. Each layer is colored relative to its adjacent layer, which exposes the internal order of the ribbon and the health of the trend rather than only the outer edges. The macro alignment filter combined with a fast crossover creates a structured momentum signal that is stricter than most ribbons, helping avoid counter trend entries. The added status matrix provides a compact decision aid that shows whether price is above or below each layer in real time, which most ribbons do not include. The non-repainting toggle ensures the behavior is consistent between historical and live data. The indicator focuses on structural clarity and disciplined signals rather than generic crossover spam.
Markets, timeframes, and trading styles
This indicator is suitable for any liquid market including Forex, Crypto, Stocks, Commodities, and Indices. For scalping on 1m to 5m charts, keep lengths shorter or use EMA to maintain responsiveness, and focus on quick momentum continuation after macro alignment while using the matrix to confirm price remains above the faster layers. For day trading on 5m to 1H charts, the default lengths provide a balanced view of trend and pullback structure. For swing trading on 1H to daily charts, the default lengths remain effective and reduce noise. For position trading or investing on weekly charts, consider increasing all lengths proportionally to match the longer holding horizon and only take signals that align with the macro stack and matrix bias.
Settings guidance
Shorter lengths create faster signals but more noise; longer lengths create smoother signals but more lag. EMA reacts faster and suits active styles, while SMA smooths the ribbon for broader trend interpretation. Line styles and thickness controls let you emphasize the layers you care about most. Background shading is best kept subtle to preserve chart readability and should be used primarily to highlight full alignment states. Signal markers can be toggled off if you want a purely visual ribbon without entries. The matrix position can be moved to any corner or center area of the chart to avoid overlapping price action or other annotations.
Alerts
The script includes alerts for full bullish alignment, full bearish alignment, fast crosses between MA1 and MA2, and the trend-filtered bullish and bearish cross signals. All alerts respect the non-repainting toggle, so they fire on confirmed bars only when that option is enabled. Messages include symbol, timeframe, and price placeholders for automation or logging.
Non-repainting behavior
When non-repainting mode is enabled, all signal conditions and background states are confirmed on closed bars. This avoids signals appearing and disappearing mid bar and ensures live behavior mirrors historical behavior. Disabling the toggle makes the ribbon update in real time but signals should be treated as provisional until the bar closes.
Disclaimer
This indicator is a technical analysis tool and does not constitute financial advice. Always test settings on your chosen market and timeframe, use risk management, and confirm signals with additional context. No indicator is perfect; use this ribbon as one component of a broader trading plan.
Pine Script®指标
Adaptive Finite Volume Elements [UAlgo]Adaptive Finite Volume Elements (AFVE) is an enhanced, volatility-adaptive interpretation of the classic Finite Volume Elements concept. The indicator transforms raw volume into a directional volume-flow oscillator by evaluating whether each bar’s “money flow impulse” is meaningful enough to be considered bullish, bearish, or noise. Instead of using a fixed percentage threshold, AFVE uses an ATR-based cutoff that expands and contracts with market volatility. This allows the signal to remain responsive in slow conditions while avoiding excessive whipsaws during high-volatility phases.
AFVE is designed as a practical workflow tool rather than a purely academic oscillator. It provides three layers of information in one pane:
1) A smoothed, normalized AFVE line that represents net volume flow as a percentage.
2) A signal line used for reversal detection in extreme zones.
3) A divergence engine that scans recent pivots and highlights classical bullish and bearish divergences between price and AFVE.
The script also implements a lightweight “engine” architecture using Pine v6 types and methods. This keeps the logic modular, improves readability, and enables controlled memory management for pivot history.
🔹 Features
1) Volatility Adaptive Cutoff (ATR-Based Noise Filter)
AFVE replaces fixed thresholds with a dynamic cutoff derived from ATR. This means the indicator automatically adapts to changing volatility regimes. In calm markets, smaller impulses can still be recognized as meaningful. In fast markets, minor fluctuations are filtered out as noise, reducing false volume-flow flips.
2) Directional Volume Flow Classification
Each bar is classified into one of three states based on the money flow impulse versus the adaptive cutoff:
- Bullish flow: full positive volume is counted.
- Bearish flow: full negative volume is counted.
- Neutral flow: volume is ignored if the impulse is inside the cutoff band.
This produces a cleaner oscillator that focuses on decisive participation rather than constant micro-changes.
3) Normalized Oscillator Output
AFVE is normalized by total volume over the lookback period, then scaled to a percentage. This keeps the output comparable across symbols and timeframes, since it expresses net flow relative to total activity.
4) Optional Smoothing
A selectable EMA smoothing stage is provided. Smoothing reduces jitter and makes trend and reversal structures clearer, while still preserving responsiveness when set to low values.
5) Signal Line Reversal Logic in Extreme Zones
A simple moving average of AFVE is used as a signal line. Reversal markers are produced only when crosses occur in statistically meaningful regions:
- Bullish reversal: AFVE crosses above the signal line while the signal line is below the negative threshold (oversold regime).
- Bearish reversal: AFVE crosses below the signal line while the signal line is above the positive threshold (overbought regime).
This design reduces “mid-range” crosses that tend to be less actionable.
6) Divergence Detection Using Pivot Memory
The script maintains small rolling arrays of recent pivot highs and pivot lows in AFVE (up to 5 each). When a new pivot is confirmed:
- Bearish divergence is flagged if price makes a higher high while AFVE makes a lower high.
- Bullish divergence is flagged if price makes a lower low while AFVE makes a higher low.
The script draws both the oscillator divergence line and the corresponding dashed price line on the main chart (force overlay), allowing fast visual confirmation.
7) Dynamic Coloring and Gradient Fill
AFVE is colored based on both sign and momentum:
- Above zero and rising: strong bullish color.
- Above zero but weakening: faded bullish color.
- Below zero and falling: strong bearish color.
- Below zero but weakening: faded bearish color.
A split fill system paints positive and negative regions separately for clear regime identification.
🔹 Calculations
1) Typical Price and Money Flow Impulse
AFVE starts from typical price and a money-flow style impulse that reacts to both bar structure and short-term change in typical price:
float tp = hlc3
float mf = close - (high + low) / 2 + tp - tp
Interpretation:
- close - (high + low) / 2 measures where the close sits relative to the bar’s midpoint.
- tp - tp adds a short-term directional component based on typical price change.
- Combined, mf becomes a compact impulse term that helps decide whether volume should be counted as bullish, bearish, or ignored.
2) Adaptive Cutoff Using ATR
Instead of using a fixed cutoff, AFVE scales the cutoff by ATR for the selected period:
float volatility = ta.atr(period)
float cutoff = volatility * cutoff_factor
Interpretation:
- Higher volatility increases the cutoff, requiring stronger impulses to classify volume as directional.
- Lower volatility reduces the cutoff, allowing smaller but meaningful impulses to be recognized.
3) Volume Flow Decision (Directional or Neutral)
Volume is converted into a signed flow value using the impulse versus cutoff comparison:
float v_flow = 0.0
if mf > cutoff
v_flow := volume
else if mf < -cutoff
v_flow := -volume
else
v_flow := 0.0
Interpretation:
- If mf exceeds +cutoff, the bar’s volume is treated as bullish participation.
- If mf is below -cutoff, volume is treated as bearish participation.
- Otherwise, volume is ignored to reduce noise in choppy conditions.
4) Summation, Normalization, and Scaling
AFVE is calculated as net directional flow relative to total volume over the lookback:
float fve_raw = math.sum(v_flow, period) / math.sum(volume, period) * 100
Interpretation:
- math.sum(v_flow, period) represents net signed participation.
- math.sum(volume, period) represents total activity.
- The ratio produces a bounded percentage-style oscillator.
5) Optional EMA Smoothing
A smoothing stage is applied if smoothness is greater than 1:
float fve_final = smooth > 1 ? ta.ema(fve_raw, smooth) : fve_raw
Interpretation:
- Low smoothing values keep AFVE responsive.
- Higher smoothing values produce cleaner swings and clearer divergence structures.
6) Signal Line and Extreme-Zone Reversal Conditions
A simple moving average is used as the signal line, and reversal triggers require both a cross and an extreme regime:
float signal_line = ta.sma(fve_value, i_sig_len)
bool is_oversold = signal_line < -i_rev_trsh
bool is_overbought = signal_line > i_rev_trsh
bool bull_rev = ta.crossover(fve_value, signal_line) and is_oversold
bool bear_rev = ta.crossunder(fve_value, signal_line) and is_overbought
Interpretation:
- The threshold defines when the market is treated as stretched.
- Crosses are only considered “reversal-grade” when they occur in these zones.
7) Pivot Detection and Divergence Logic
AFVE pivots are detected using a fast pivot rule (left 2, right 1). When a pivot is confirmed, the script stores it in memory and compares it to the prior pivot:
Pivot High and bearish divergence:
float ph = ta.pivothigh(current_fve, 2, 1)
if not na(ph)
Pivot p = Pivot.new(current_fve , high , bar_index )
high_pivots.unshift(p)
if high_pivots.size() > 5
high_pivots.pop()
if high_pivots.size() >= 2
Pivot p0 = high_pivots.get(0)
Pivot p1 = high_pivots.get(1)
if p0.price > p1.price and p0.val < p1.val
// Bearish Divergence
Interpretation:
- Price higher high (p0.price > p1.price) combined with AFVE lower high (p0.val < p1.val) flags bearish divergence.
Pivot Low and bullish divergence:
float pl = ta.pivotlow(current_fve, 2, 1)
if not na(pl)
Pivot p = Pivot.new(current_fve , low , bar_index )
low_pivots.unshift(p)
if low_pivots.size() > 5
low_pivots.pop()
if low_pivots.size() >= 2
Pivot p0 = low_pivots.get(0)
Pivot p1 = low_pivots.get(1)
if p0.price < p1.price and p0.val > p1.val
// Bullish Divergence
Interpretation:
- Price lower low (p0.price < p1.price) combined with AFVE higher low (p0.val > p1.val) flags bullish divergence.
8) Dynamic Coloring Logic
The AFVE line color reflects both direction (above/below zero) and momentum (rising/falling vs previous value):
val > 0
? (val > val ? bull : color.new(bull, 40))
: (val < val ? bear : color.new(bear, 40))
Interpretation:
- Strong color indicates acceleration in the prevailing direction.
- Faded color indicates weakening momentum, often useful for reading transitions and potential divergence setups.
Pine Script®指标
CPR Supertrend SMA Credit Spread(Options Sellers) [KedArc Quant]Overview
CPR Supertrend SMA - Credit Spread Engine is a structure-based options selling indicator designed exclusively for traders who deploy credit spreads such as Bull Put Credit Spread and Bear Call Credit Spread.
This system identifies low-risk option selling opportunities using weekly Central Pivot Range (CPR), Supertrend structure, and trend confirmation via SMA21. The indicator helps option sellers determine when to sell premium safely and when to exit to protect capital.Unlike directional trading indicators that attempt to predict price movement, this engine focuses on identifying statistically favorable zones where option sellers can safely collect theta decay while minimizing directional risk.This is not a buy or sell stock indicator. It is specifically engineered for option sellers using defined risk credit spreads.
Recommended timeframe: 1 hour
Recommended instruments: Index options such as NIFTY, BANKNIFTY, SPX, NASDAQ, and liquid stocks
Core Philosophy
Option sellers make consistent profits by selling premium when price structure provides statistical protection.
This engine identifies those protected structural zones using:
Weekly CPR positioning
-Supertrend structure bias
-Trend confirmation via SMA21
-Candle close confirmation (non-repainting)
The system provides clear visual signals for:
-Bull Put Credit Spread opportunities
-Bear Call Credit Spread opportunities
-Structural exit signals
What This Indicator Does
This indicator helps option sellers answer three critical questions:
-When to sell PUT credit spreads
-When to sell CALL credit spreads
-When to exit credit spreads safely
This improves decision quality and reduces emotional trading.
Why This Is NOT a Mashup Indicator
This indicator is not a mashup because it does not combine unrelated indicators blindly.
Each component serves a specific structural role:
CPR defines institutional support and resistance zones
Supertrend defines directional bias and structural regime
SMA21 confirms trend stability and filters noise
These components work together as a unified structure-based options selling framework.
The logic is purpose-built for credit spread deployment, not signal stacking.
This is a structural options selling engine, not an indicator mashup.
How It Helps Options Sellers
This indicator helps option sellers:
Avoid selling premium during high risk structural zones
Sell credit spreads only when structure provides protection
Avoid emotional decision making
Exit positions when structural protection breaks
Improve consistency in premium selling strategies
It visually converts market structure into actionable credit spread opportunities.
Recommended Use Case
This indicator is designed exclusively for:
Option sellers deploying:
-Bull Put Credit Spreads
-Bear Call Credit Spreads
Not intended for:
-Option buyers
-Scalpers
-Directional intraday trading
Input Configuration
Weekly CPR
Uses weekly pivot, top CPR, and bottom CPR to define structural zones.
Supertrend Settings
ATR Length: Default 10
Multiplier: Default 3
Defines structural trend regime.
SMA21
Used to confirm directional stability.
Timeframe
Recommended: 1 hour
Supports higher timeframes such as 2H and 4H.
Signal Logic Summary
Bull Put Credit Spread appears when:
Price closes above Weekly CPR
Supertrend is below price
Price is above SMA21
Bear Call Credit Spread appears when:
Price closes below Weekly CPR
Supertrend is above price
Price is below SMA21
Exit signal appears when structure invalidates.
Glossary (Important for Option Sellers)
Credit Spread
A credit spread is an options strategy where a trader sells one option and buys another option to define risk while receiving premium upfront.
This is a defined risk premium selling strategy.
Bull Put Credit Spread (PUT CREDIT SPREAD)
A Bull Put Credit Spread is an options selling strategy used when the trader expects price to stay above a support level or move sideways.
Structure:
Sell higher strike PUT
Buy lower strike PUT
Example:
Sell PE 25550
Buy PE 25350
This creates:
Limited risk
Limited profit
Profit if price stays above 25550
Goal: collect premium safely
This is a bullish or neutral options selling strategy.
Bear Call Credit Spread (CALL CREDIT SPREAD)
A Bear Call Credit Spread is an options selling strategy used when the trader expects price to stay below resistance or move sideways.
Structure:
Sell lower strike CALL
Buy higher strike CALL
Example:
Sell CE 25800
Buy CE 26000
This creates:
Limited risk
Limited profit
Profit if price stays below 25800
Goal: collect premium safely
This is a bearish or neutral options selling strategy.
CPR (Central Pivot Range)
Institutional support and resistance zone derived from previous week's price.
Defines structural balance zones.
Supertrend
Trend structure indicator that defines directional bias and regime.
Used here to confirm structural alignment.
Credit Spread Engine
A structured system that helps identify optimal zones for selling option spreads safely.
FAQ
Is this indicator for option buyers?
No. This indicator is exclusively designed for option sellers deploying credit spreads.
Does this repaint?
No. Signals appear only after candle close.
No repainting.
Which timeframe is best?
1 hour timeframe is recommended.
Which instruments work best?
Index options such as:
NIFTY
BANKNIFTY
SPX
NASDAQ
Highly liquid instruments are preferred.
Is this suitable for beginners?
This indicator is best suited for traders familiar with options credit spreads.
Does it show exact strike selection?
It provides structural reference. Strike selection should be chosen near structural levels such as CPR or Supertrend.
Why This Strategy Works Well for Options Sellers
Option sellers profit when price stays within protected zones.
This engine helps identify those zones using structural market logic.
It prevents selling premium blindly.
It enables structured, probability-based premium selling.
Disclaimer
This script is provided for educational purposes only.
Past performance does not guarantee future results.
Trading involves risk, and users should exercise caution and use proper risk management when applying this strategy.
Pine Script®指标
Mean Deviation Trend [BackQuant]Mean Deviation Trend
Overview
Mean Deviation Trend is a structure-based trend and regime indicator that measures directional pressure as the market’s sustained deviation from a moving “mean,” then uses that pressure to drive an adaptive band , dynamic coloring, and a level engine that marks deviation peak extremes after momentum fades.
Most trend tools start with direction, for example slope or MA cross, then try to estimate strength later. This script does the reverse:
It first quantifies how far price is displaced from a central mean in volatility-adjusted units .
It then smooths and accumulates that deviation to determine trend direction and conviction .
Finally it converts conviction into a band that tightens when pressure is strong and widens when pressure is weak.
The result is a single framework that blends:
A mean anchor (EMA).
A signed deviation engine normalized by ATR.
A conviction score based on sustained deviation.
An adaptive band that behaves like dynamic support/resistance.
A “deviation peak” level system that plants levels at extremes after the push fades.
Optional glow, fills, candle coloring, and flip markers.
Core concept: deviation from mean as trend fuel
A trend is not just “price up” or “price down.” A trend is a persistent imbalance where price spends time displaced from fair value and keeps re-asserting that displacement. This indicator treats the mean as a moving fair value proxy, and it measures how aggressively price is departing from it.
Key idea:
If price stays above the mean and that displacement is sustained, bullish pressure is dominant.
If price stays below the mean and that displacement is sustained, bearish pressure is dominant.
If price keeps snapping back and deviation cannot sustain, regime is weak and uncertainty is high.
This is why the script doesn’t rely on a single moment like a cross. It cares about persistence .
Mean anchor (the “center of gravity”)
The mean is defined as an EMA of close:
mean = EMA(close, meanLen)
Why EMA:
It responds faster than SMA to regime changes.
It provides a stable anchor without overreacting to single bars.
The mean line is not just a moving average here, it is the reference line that deviation is measured against. Everything downstream depends on the mean being a consistent “center.”
Volatility normalization (why ATR is essential here)
Raw distance from mean is meaningless across volatility regimes. A $200 deviation on BTC might be noise one week and huge another week. To fix this, the script normalizes deviation by ATR:
atr = ATR(14)
rawDev = (close - mean) / atr
Interpretation:
rawDev is “how many ATR units price is away from the mean.”
This makes deviation comparable across timeframes and volatility states.
This is critical because it turns the indicator into a dimensionless pressure metric rather than a price-distance tool.
Deviation smoothing (instantaneous pressure vs noisy pressure)
Instantaneous deviation can spike on one candle and mean nothing. So the script applies EMA smoothing to raw deviation:
devSmooth = EMA(rawDev, devLen)
What this does:
Reduces single-bar spikes.
Keeps the sign and general magnitude of displacement.
Creates a cleaner “pressure line” that responds but does not jitter.
This is the first stage of filtering: “Are we meaningfully deviating, or just wicking?”
Deviation accumulation (turning pressure into conviction)
This is the part that makes the indicator behave like a trend conviction model rather than a simple oscillator.
The script computes:
cumDev = SMA(devSmooth, devAccum)
Even though it’s coded as an SMA, conceptually it behaves like a rolling accumulation of the deviation signal:
If devSmooth stays positive for multiple bars, cumDev rises and stays positive.
If devSmooth stays negative for multiple bars, cumDev drops and stays negative.
If devSmooth flips sign repeatedly, cumDev compresses toward zero.
This is the key “persistence detector.” It converts short-term deviation into a medium-term conviction read.
Trend direction and flips
Trend direction is derived purely from the sign of cumulative deviation:
tDir = cumDev > 0 ? +1 : -1
flip = tDir != tDir
Interpretation:
Bull regime means the market’s sustained deviation is above the mean (pressure up).
Bear regime means sustained deviation is below the mean (pressure down).
A flip marks a regime transition where the sustained bias changes sign.
This is intentionally simple because all the complexity is in how cumDev is built.
Measuring conviction: devNorm (adaptive strength scale)
The script measures absolute conviction:
devAbs = abs(cumDev)
Then it normalizes it relative to a rolling peak:
devHigh = highest(devAbs, 80)
devNorm = devHigh > 0 ? min(devAbs / devHigh, 1) : 0
Meaning:
devNorm is a 0..1 strength scale.
0 means current conviction is tiny relative to recent extremes.
1 means conviction is at the strongest level seen in the last ~80 bars.
This is not a z-score, it’s a “relative-to-recent-peak” normalization. That matters because it makes the band behavior adapt to each instrument’s recent character, not a fixed threshold system.
Adaptive band logic (tight when confident, wide when uncertain)
The band is built to behave differently depending on conviction. When conviction is strong, the band should hug price and act like a close structural guide. When conviction is weak, the band should widen and stop pretending it is precise.
This is done by interpolating between two ATR multipliers:
bandTight = ATR multiplier when devNorm is high
bandWide = ATR multiplier when devNorm is low
bandMult = bandWide - devNorm * (bandWide - bandTight)
bandW = atr * bandMult
Interpretation:
devNorm near 1 → bandMult approaches bandTight → band width shrinks.
devNorm near 0 → bandMult approaches bandWide → band width expands.
So the band width is not arbitrary. It is a direct function of trend conviction.
Active band placement (trend-aware support/resistance)
The “active band” is placed on the opposite side of the mean depending on direction:
If bullish: activeBand = mean - bandW
If bearish: activeBand = mean + bandW
So in bullish regimes, the band behaves like a dynamic support zone beneath the mean. In bearish regimes, it behaves like dynamic resistance above the mean.
Then it is smoothed:
activeBand = EMA(activeBand, 3)
This prevents the band from stepping too harshly when ATR shifts.
Outer band (secondary structure reference)
A second band is created at half width on the opposite side:
bull: outerBand = mean + bandW * 0.5
bear: outerBand = mean - bandW * 0.5
Then smoothed again. This outer line is not the main “stop band,” it is more of an additional structure marker to show where the mean plus/minus partial deviation zone sits. It can help visually gauge whether price is extended relative to the mean structure while still in the same regime.
Color system (strength-aware gradient)
The trend color is not binary. It is strength-weighted:
If bullish, devNorm drives a gradient from a faint bull tint to full bull.
If bearish, devNorm drives a gradient from a faint bear tint to full bear.
This gives you an immediate read:
Bright strong color = conviction high.
Faded color = conviction low, regime fragile.
It also ties into the glow and fill so the whole visual language matches the same underlying “pressure” variable.
Deviation peak level engine (how the script plants levels)
This indicator includes a separate mechanism that marks important extremes after a strong deviation push fades. The idea is:
When trend pressure peaks and then collapses, the extreme price printed at peak deviation often becomes a reaction level later.
This is similar in spirit to:
exhaustion extremes,
climactic deviation points,
distribution/accumulation turning zones,
but the script formalizes it using the deviation engine.
1) Track the strongest deviation peak
The script stores a running peak:
peakDev: maximum devAbs seen since last reset
peakPrice: the extreme price at that peak (high for bull, low for bear)
peakDir: direction at peak
peakBar: bar index of peak
When devAbs prints a new high, it updates those values.
2) Define “fade” (momentum has cooled)
A fade event triggers when:
peakDev is meaningfully large (peakDev > 0.3)
current devAbs drops below a fraction of the peak: devAbs < peakDev * fadeThr
fadeThr is the key user control. Lower fadeThr requires a deeper drop from peak before planting a level.
What “fade” means in practice:
A strong push happened (deviation expanded).
That push is no longer active (deviation contracted).
So the extreme created during the push is now “locked in” as a candidate level.
3) Plant a level at the extreme
When faded:
A dashed horizontal line is created at peakPrice.
The line is projected forward (bar_index + 60).
It is stored in an array with direction and retest state.
It also respects maxLvls by deleting the oldest levels to avoid clutter.
4) Maintain levels and delete invalid ones
Each bar, levels are checked:
If price breaks far beyond the level (by about 2 ATR in the wrong direction), the level is deleted.
That “broken” rule is a pragmatic invalidation filter. If price rips through a former deviation extreme by a large margin, the level is no longer acting like a meaningful reaction zone.
5) Detect retests and mark them
A retest is detected when:
close is within ~0.25 ATR of the level,
and two bars ago price was not near it (distance > 0.5 ATR),
and the level hasn’t already been marked as retested.
When that happens:
A diamond marker is printed (◆) above or below depending on approach.
The level is flagged as retested so it won’t spam markers.
So levels are not just static drawings. They have state: naked vs retested, and they get culled if invalidated.
Glow system (volatility-scaled aesthetic, strength-scaled intensity)
Glow is not random decoration here. Its width scales with devNorm:
glowMult = 0.4 + devNorm * 1.2
glowW = atr * 0.08 * glowMult
So in strong trends:
Glow band expands.
The mean core visually “radiates” more.
In weak trends:
Glow shrinks and becomes less prominent.
The glow is built using multiple invisible plots above and below the mean, then layered fills with different transparencies. It creates a soft gradient aura around the mean that encodes strength.
Band fill and line break behavior
The active band is plotted with plot.style_linebr and forced to break on flips:
bandBrk = flip ? na : activeBand
This prevents the band from drawing a misleading connecting line across a regime change. It visually resets when direction flips, which matters because the band swaps sides of the mean when regime changes.
Fill is drawn between:
the active band line
and hl2 (mid-price reference)
So you get a shaded zone that reflects the current regime color and strength.
Candles and flip labels
Candles can be colored by the same strength-weighted regime color, which makes the entire chart consistent.
On flips:
Bull flip prints ▲ at the low.
Bear flip prints ▼ at the high.
These are regime markers, not “entry signals” by default. They simply identify when the cumulative deviation sign changed.
How to read this indicator in practice
1) Regime and conviction
Direction comes from cumDev sign.
Conviction comes from devNorm intensity.
Bright color + stable band on one side means strong sustained pressure.
Faded color + widening band means weak sustained pressure and higher uncertainty.
2) Using the active band as structure
In a bullish regime, activeBand is below mean and can behave like:
dynamic support,
risk boundary,
trend “line in the sand.”
In bearish regime, it flips above mean and acts like dynamic resistance.
Because the band widens when conviction is low, it naturally tells you “do not treat this as a tight stop zone when the trend is weak.”
3) Using deviation peak levels
Peak levels represent exhaustion extremes after a strong deviation impulse faded:
If price returns to a naked level, that area can act as a reaction zone.
Once retested, the script marks it and treats it as less “special.”
If price breaks it by a wide margin, the script removes it as invalid.
This level engine is best viewed as “structural memory of deviation events,” not generic support/resistance.
4) Extreme deviation alert
devNorm > 0.85 means the current sustained deviation is near the strongest seen recently. That’s useful for:
identifying trend climax states,
detecting when continuation is strong but risk of snapback rises,
flagging conditions where mean reversion pressure is building.
It does not guarantee reversal, it flags “stretch.”
Inputs and what they actually change
Mean Length (meanLen)
Controls the anchor responsiveness:
Lower = mean follows price more closely, deviation shrinks, more frequent flips.
Higher = mean is slower, deviation grows, trend regimes last longer.
Deviation Smoothing (devLen)
Controls how noisy the deviation signal is:
Lower = faster response, more jitter.
Higher = smoother pressure, slower flips.
Deviation Accumulation (devAccum)
Controls persistence requirement:
Lower = trend conviction reacts quickly but can whipsaw.
Higher = requires sustained deviation, fewer flips, more confirmation.
Band Tight / Band Wide
These define the band behavior range:
bandTight: how close the band gets when conviction is strong.
bandWide: how far it drifts when conviction is weak.
If you want the band to behave more like a stop guide, reduce bandWide. If you want it to act more like a regime boundary, increase bandWide.
Fade Threshold + Max Levels
These shape the level engine:
fadeThr lower = requires bigger cooling before planting levels (fewer, more meaningful).
fadeThr higher = plants levels earlier (more levels, more noise).
maxLvls controls clutter and historical depth.
Alerts (what they represent)
Dev Bull / Dev Bear: regime flips, cumulative deviation changed sign.
Dev Faded: a deviation peak cooled enough to plant a level.
Extreme Dev: sustained deviation is near local maximum, stretch condition.
Summary
Mean Deviation Trend models trend as sustained, volatility-normalized displacement from a mean rather than simple direction. It smooths and accumulates signed deviation to extract regime and conviction, then converts that conviction into an adaptive ATR band that tightens when pressure is strong and widens when pressure is weak. On top of that, it tracks deviation peak extremes and plants forward levels only after deviation fades, creating a structured map of “where trend impulses peaked” and how price reacts when those zones are revisited.
Pine Script®指标
Confluence SuiteConfluence Suite is an all-in-one overlay toolkit built around an adaptive supertrend engine, a neural network signal classifier, and a suite of indicator overlays. Every component is designed to work together or independently, giving traders a flexible system that adapts to any style — trend following, swing trading, scalping, or contrarian approaches.
The core idea is simple: signals fire when the underlying trend engine flips direction, and the neural network then evaluates six market conditions to grade how strong that setup is. Overlay indicators and dashboard metrics give you the context to decide how much weight to put on any given signal.
---
🔶 **SIGNALS**
Signals appear directly on the price chart as labelled markers above or below candles. A buy signal appears below the bar, a sell signal above it. When the AI Signal Classifier is enabled, each signal carries a plain-English quality label — **Strong Buy**, **Good Buy**, **Moderate Buy**, or **Weak Buy** (and equivalently for sells). When the classifier is off, signals show a simple ▲ or ▲+ (▼ or ▼+) depending on whether the 50 EMA is above or below the 200 EMA.
Exit markers appear as a small ✖ on the chart. These fire when a fast EMA crosses the slow EMA in the opposite direction of your open position and RSI confirms the move — a lightweight signal to consider taking profit or tightening your stop. They are not hard exit instructions.
**How signals are generated**
The signal engine is an adaptive supertrend. It continuously runs multiple ATR-based supertrend calculations across a range of sensitivity factors, clusters their performance using a k-means algorithm, and selects whichever factor cluster has performed best recently relative to the current volatility regime. This means the engine self-tunes — it naturally becomes more reactive in fast markets and more patient in slow ones. A buy signal fires when this adaptive supertrend flips from bearish to bullish; a sell signal fires when it flips the other way.
---
🔶 **AI SIGNAL CLASSIFIER**
When enabled, each signal is scored by a six-factor neural network. The six inputs are:
- **AMF Momentum** — measures whether a DEMA-based oscillator is rising and crossing its signal line in the direction of the trade
- **ALMA Alignment** — checks whether fast and slow Arnaud Legoux Moving Averages are aligned with the trade direction and have meaningful separation
- **Support / Resistance Context** — evaluates whether price has recently broken a pivot level, is sitting near support (for buys) or resistance (for sells), or is in a neutral zone
- **Swing Structure** — compares the current 20-bar high/low range to the previous 20-bar range to assess whether the market is making higher highs and higher lows (bullish structure) or lower highs and lower lows (bearish structure)
- **Market Regime** — uses a 30-period ADX calculation to determine whether the market is in a strong directional trend and, if so, whether that trend is in the direction of the signal
- **Volume Sentiment** — uses the candle's close position within its high/low range as a proxy for buying or selling pressure, then computes the ratio of bullish to bearish volume over recent bars
Each factor produces a score between -1 and +1. These flow through a three-layer neural network with tanh activation and a sigmoid output, producing a final confidence value between 0 and 1.
**Signal labels by score:**
Strong Buy / Sell (≥76%) — Most factors align, high confidence setup.
Good Buy / Sell (65–75%) — Majority of factors agree.
Moderate Buy / Sell (37–64%) — Mixed conditions, use additional confluence.
Weak Buy / Sell (<37%) — Few factors supporting the move.
Label colours follow a cyan → teal → dark teal → orange → red gradient from Strong to Weak, giving an immediate visual cue.
When the classifier is off, signal quality is not evaluated and labels revert to directional arrows only.
---
🔶 **SIGNAL SENSITIVITY & TUNING**
**Signal Sensitivity** (default: 5, range: 1–26) controls the range of ATR multipliers the adaptive engine considers. Lower values bias the engine toward short-term, more frequent signals. Higher values produce longer-term, less frequent signals with more lag but less noise. This is the primary control for matching the indicator to your timeframe.
**Signal Tuner** (default: 10, range: 1–25) sets the ATR lookback period used in the supertrend calculation. Higher values smooth the ATR, making signals more refined but introducing slightly more lag. Think of this as a fine-tuning control once you have Sensitivity set where you want it.
**Autopilot Sensitivity** removes the need to manually set Sensitivity at all. When set to Short-Term, Mid-Term, or Long-Term, it overrides the Sensitivity and Tuner inputs with optimised values for that trading horizon. Useful if you trade the same setup on different timeframes without wanting to re-tune manually.
The dashboard shows whether Autopilot is active and, when it is, which mode is running. When Autopilot is off and the AI Signal Classifier is enabled, the dashboard Optimal Sensitivity row shows "On" in green, confirming the classifier is active.
---
🔶 **PRESETS & FILTERS**
Presets automatically configure multiple settings at once, giving you a starting point for a specific trading style.
**Trend Trader ** — Enables Smart Trail, Trend Catcher, Neo Cloud, and Trend Tracer together. Best suited to traders who want maximum visual confluence for trend-following setups.
**Scalper ** — Sets Sensitivity to 4 (short-term), enables Smart Trail and Trend Tracer, and switches candle colouring to Confirmation Gradient. Designed for fast timeframes where more signals and tighter visual feedback are preferred.
**Swing Trader ** — Sets Sensitivity to 18 (long-term), enables Neo Cloud, and uses simple confirmation colouring. Reduces signal frequency significantly, appropriate for daily or weekly charts.
**Contrarian Trader ** — Enables Reversal Zones and Smart Trail with contrarian gradient candle colouring. Useful when price is ranging and you are fading moves into the zone extremes rather than following breakouts.
Filters allow you to require a specific overlay condition to be true before a signal is shown. Rather than changing what the signal engine detects, they simply suppress signals that don't have the filter's confirmation. Each filter involves a trade-off: you get cleaner, more confluent signals, but you will miss some entries that would have worked without the filter.
**Smart Trail ** — Only shows buy signals when the Smart Trail is in a bullish state (blue, below price) and sell signals when bearish (red, above price).
**Trend Tracer ** — Only shows signals aligned with the current Trend Tracer direction.
**Trend Strength ** — Suppresses signals when the Trend Strength metric is below 30% in absolute terms, filtering out signals during low-momentum, ranging conditions.
**Trend Catcher ** — Only shows signals aligned with the current Trend Catcher direction.
**Neo Cloud ** — Uses the Neo Cloud Senkou values as a trend bias filter, only passing signals in the direction the cloud suggests.
---
🔶 **CANDLE COLOURING**
Candle colouring gives a continuous visual read on the trend state between signals, helping you see how a trend is developing or fading without relying on signals alone.
**Confirmation Simple** — Candles are green during uptrends and red during downtrends, switching when the adaptive supertrend changes direction. Straightforward and readable at a glance.
**Confirmation Gradient** — The same directional logic, but the colour intensity scales with the strength of the trend signal. Lighter shades indicate weaker momentum, deeper shades indicate stronger conviction. Useful for identifying when a trend is accelerating or losing steam before a signal fires.
**Contrarian Gradient** — Colouring is inverted relative to the signal direction, making it easier to spot exhaustion points and potential reversals. Designed for use alongside Reversal Zones when trading counter-trend.
**None** — Candle colouring is disabled.
---
🔶 **INDICATOR OVERLAYS**
**Smart Trail**
The Smart Trail is a dynamic band that sits above price in downtrends (red) and below price in uptrends (blue). It acts as a trailing area of support or resistance that adapts to volatility — widening during fast, volatile moves and tightening during calm periods.
Technically it is built on a Trend Flow Line (a hybrid of Hull Moving Averages and double-smoothed WMA), surrounded by inner and outer bands derived from standard deviation. Direction is determined by comparing the current Trend Flow Line to its value nine bars ago. Guard conditions prevent the band from rendering when price has already significantly broken through the outer edge, keeping the display clean.
The primary uses are: (1) as a dynamic support/resistance reference — price holding above the blue band during an uptrend is a positive sign; (2) as an entry filter, only taking buy signals when the band is blue and below price.
**Reversal Zones**
Reversal Zones are shaded probability bands above and below the current price, highlighting areas where reversals are statistically more likely. They use a Rational Quadratic Kernel regression to compute a smooth baseline, then build inner and outer bands using hybrid ATR and mean deviation volatility. The bands widen with volatility and contract in calm conditions.
The upper zone is purple and the lower zone is green, both with a gradient fill that darkens toward the outer edge — meaning price is deeper into the zone. In trending markets, price can push through the zones and continue, so the zones are most useful as a prompt to reduce position size, tighten stops, or look for a signal reversal rather than as hard exit levels.
**Trend Catcher**
The Trend Catcher is a single-line overlay derived from a Hull Moving Average calculation. It changes colour depending on its direction — green when rising, red when falling. It provides a smooth, responsive read on the prevailing trend and is designed to stay close to price without excessive whipsawing. It is most effective on trending instruments and timeframes.
**Trend Tracer**
The Trend Tracer is a crosshair-style line based on a Donchian midpoint supertrend calculation. It is less reactive than the Trend Catcher and changes direction less frequently. It is displayed using a cross marker style so it is visually distinct from the other overlays, and changes colour when its trend direction changes. It works well as a longer-term bias reference alongside shorter-term signals.
**Neo Cloud**
The Neo Cloud is a forward-projected cloud similar in concept to the Ichimoku cloud, but built using ATR-adaptive supertrend calculations rather than simple high/low averages. Three lines — Tenkan, Kijun, and Senkou B — are computed using progressively longer ATR periods and multipliers, and the resulting cloud is projected two bars forward. A bullish cloud (teal) suggests an upward bias; a bearish cloud (red) a downward bias. The cloud's crossovers are marked with circles on the chart.
The Neo Cloud is best used for a macro trend bias rather than precise entry timing. Using the Neo Cloud Filter ensures signals only fire in the direction the cloud is leaning.
**Trailing Stoploss**
When enabled, a line is plotted at the current adaptive supertrend level — the actual threshold the price engine uses to determine direction. This gives you a visual reference for where the engine would flip. You can use this as a mechanical stop placement level.
**AI Moving Average**
An adaptive moving average driven by the performance index of the signal engine. It smooths the supertrend line using a rate that scales with how well the current factor cluster is performing. In strongly trending conditions where the engine is performing well it moves quickly; in weak or choppy conditions it slows down. It changes colour based on whether price is above (bullish) or below (bearish) it.
---
🔶 **DASHBOARD**
The dashboard displays six live metrics and can be positioned in the top right, bottom right, or bottom left of the chart. Size can be set to Tiny, Small, Normal, or Large.
**Optimal Sensitivity / Autopilot** — Shows whether Autopilot is active and which mode, or "On/Off" for the AI Signal Classifier when Autopilot is not in use.
**Trend Strength** — Measures how far the current close is from the 14-period VWMA, normalised by ATR and expressed as a percentage from -100% to +100%. A positive value means price is above the volume-weighted average (bullish bias); a negative value means below (bearish bias). The 🔥 emoji appears when the absolute value exceeds 30%, indicating a meaningful trend. ❄️ appears when the market is weak or ranging.
**Trend Bias** — A qualitative summary row derived from the Trend Strength value: Strongly Bullish (≥75%), Mildly Bullish (30–75%), Neutral (-30% to 30%), Mildly Bearish (-75% to -30%), or Strongly Bearish (≤-75%).
**Volatility** — A normalised ATR reading expressed as Stable (below 30), Moderate (30–80), or Volatile (above 80), with a 📈 or 📉 emoji indicating whether volatility is currently rising or falling.
**Squeeze** — A Bollinger Band / Keltner Channel squeeze metric expressed as a percentage. A high squeeze percentage indicates momentum is building inside a tightening range and a breakout may be approaching.
**Volume Sentiment** — Measures the balance of bullish versus bearish volume over recent bars. Each bar's volume is classified as bullish or bearish based primarily on where the close falls within the bar's high/low range (close near the high = bullish volume; close near the low = bearish volume), with open vs close and close vs previous close as fallbacks. The resulting ratio is expressed as a positive percentage with a green background for bullish dominance and red for bearish.
---
🔶 **SIGNAL MODE**
**Confirmation + Exits** — Standard mode. Buy and sell signals follow the trend direction, with ✖ exit markers when conditions suggest the trend may be losing momentum.
**Contrarian + Exits** — Signal direction is reversed. Signals fire at potential exhaustion points rather than trend continuations. Most effective when combined with the Contrarian Trader preset and Reversal Zones.
**None** — Signals are hidden. Useful if you want to use only the overlay indicators and dashboard without signal labels cluttering the chart.
---
🔶 **RECOMMENDED SETUPS**
For most users, the clearest starting point is the default configuration: Confirmation + Exits signal mode, Smart Trail enabled, Reversal Zones enabled, and the AI Signal Classifier on. This gives you trend-following signals with quality grading, a dynamic support/resistance band, and zone extremes for profit targets.
If you find too many signals, increase Signal Sensitivity toward 10–18 or enable the Trend Strength Filter to suppress signals in ranging conditions.
If you trade short timeframes (1m–15m), the Scalper preset with Sensitivity at 4 and Trend Strength filter active will produce more selective entries with tighter visual feedback from the Confirmation Gradient candle colouring.
For swing trading on daily or weekly charts, the Swing Trader preset with Neo Cloud enabled provides a low-noise setup with long-term trend context.
Regardless of setup, signals should not be followed blindly. The indicator is designed to support your analysis, not replace it. The most effective use is to identify confluence — when signals, overlays, volume sentiment, and trend strength metrics all agree, the probability of a strong move is higher.
---
🔶 **RISK DISCLAIMER**
Trading involves significant risk and most retail traders lose money. All content, scripts, and indicators provided here are for informational and educational purposes only. Past performance does not guarantee future results. Nothing in this indicator or its documentation constitutes financial advice.
🔶 **CREDITS AND ACKNOWLEDGEMENTS**
Thanks to the following authors/scripts, which were used in this indicator:
Ultra Smart Trail by Rathack
Neural Probability Channel by Iamalala
Neural Network Buy and Sell Signals by B3AR_Trades
SuperTrend AI by LuxAlgo
Pine Script®指标
SuperTrend AI AdaptiveSuperTrend AI detects market regime shifts and adapts the band width automatically, then scores every trend flip with a 5-factor quality engine so you know which signals to trust.
◈ How It Works
Standard SuperTrend has one fixed multiplier. It works great in trending markets but gets chopped apart in ranging conditions. This version solves that by detecting the current market regime and adapting in real time.
The indicator classifies every bar into one of three regimes:
TRENDING: ADX above threshold + normal ATR. Multiplier stays at base. SuperTrend works as intended.
RANGING: ADX below threshold + compressed ATR. Multiplier tightens slightly for faster response. Band draws as a dotted line to warn you.
VOLATILE: ATR expanding well above its historical average. Multiplier widens to absorb the noise and prevent false flips.
The regime is determined by two factors: the ATR ratio (current ATR vs its moving average over the lookback period) and the ADX reading. This gives you a structural view of market conditions, not just price direction.
◈ Adaptive Multiplier
When adaptation is enabled, the multiplier adjusts dynamically:
In volatile regimes, the multiplier increases proportionally to how expanded the ATR is. This widens the band and filters out noise-driven flips.
In ranging regimes, the multiplier drops to 85% of base. Tighter bands let you catch the transition when a real trend starts.
In trending regimes, the multiplier stays at base. No adjustment needed when conditions are ideal.
The multiplier is capped between 0.5x and 2x of your base setting so it never goes extreme. You can see the current adaptive multiplier in the dashboard at all times.
◈ AI Signal Scoring
Every SuperTrend flip gets a quality score from 0 to 100 based on 5 factors:
Volume Surge (0-20 pts): Volume on the flip bar vs 20-period average. Higher volume = more conviction behind the move.
Displacement (0-25 pts): How far price closed beyond the band on the flip. Bigger displacement = stronger breakout.
Trend Alignment (0-20 pts): Does the flip direction match the EMA trend? Aligned signals score higher.
Regime Quality (0-15 pts): Signals in trending regimes score highest. Ranging regime signals get penalized.
Band Distance (0-20 pts): How far price traveled to reach the band before flipping. Wider gap = more conviction.
Bright signals (★) score above 70 and represent high-quality flips with multiple factors confirming. Dim signals (○) score 40-69 and are worth watching but carry more risk. By default only bright signals display.
◈ Visual System
The band uses a neon glow effect (three layered plots) that makes it easy to track on any chart. The band color itself tells you the current regime at a glance:
Green/red glow = trending regime, normal SuperTrend behavior.
Amber glow = volatile regime, multiplier has widened to absorb noise.
Gray dotted line = ranging regime, multiplier tightened, use caution.
A subtle background tint appears during volatile (amber) and ranging (gray) periods so you can see regime context without looking at the dashboard. Both the glow and background tint can be toggled off in settings.
The gradient fill between price and band is available but off by default. Enable it in settings if you prefer that style.
◈ How to Read the Dashboard
ST AI ◈: header
Trend: current SuperTrend direction (▲ BULLISH / ▼ BEARISH) with bias label
Regime: current market classification (TRENDING / VOLATILE / RANGING) with ATR ratio
EMA: whether the trend EMA agrees with SuperTrend direction (✓ ALIGNED / ✗ COUNTER)
Multiplier: current adaptive value vs your base setting
ADX: trend strength reading with visual bar
Signal: last signal state with score in points
◈ Recommended Settings
Forex (EUR/USD, GBP/JPY) 1H to 4H: ATR 10, Multiplier 3.0, Regime Lookback 40, ADX 14
Crypto (BTC, ETH) 1H to 4H: ATR 10, Multiplier 3.0, Regime Lookback 50, ADX 14
Scalping 5min to 15min: ATR 7, Multiplier 2.0, Regime Lookback 30, ADX 10
Swing trading Daily: ATR 14, Multiplier 3.5, Regime Lookback 50, ADX 14
Indices (NAS100, SPX500) 15min to 1H: ATR 10, Multiplier 2.5, Regime Lookback 40, ADX 14
For fewer signals: Raise Min Signal Score to 60+, increase cooldown
For more signals: Lower Min Signal Score to 30, enable dim signals, reduce cooldown
◈ Key Features
✓ Non-repainting: all signals on confirmed bar close
✓ Regime-adaptive: multiplier adjusts to trending, ranging, and volatile conditions automatically
✓ AI signal scoring: 5-factor quality engine, 0-100 per flip
✓ Neon glow band: color shifts with regime state, visible at a glance
✓ Regime background: subtle tint shows volatile and ranging periods on the chart
✓ ADX integration: trend strength directly influences regime detection and scoring
✓ 7 alert conditions: bull/bear signals, AI-confirmed signals, trend flips, regime changes
✓ Clean dashboard: trend, regime, multiplier, ADX, and signal score in one panel
✓ 100% original code: not derived from any existing script
◈ What Makes This Different
Standard SuperTrend uses a fixed multiplier. It works until the market changes character, then gives false flips until you manually adjust. This version detects the change and adjusts for you.
The scoring tells you not just that a flip happened, but whether it is likely to be meaningful. A flip during a trending regime with high volume and strong displacement scores 85+. The same flip during a ranging regime with weak volume might score 45. Both are flips, but only one is worth trading.
◈ Disclaimer
No indicator predicts the future. Regime detection is probabilistic, not certain. Use proper risk management and combine with your own analysis. Past performance does not guarantee future results.
Happy trading.
Pine Script®指标
Eight Moving Average Cross with Macro DivergencesCredits and acknowledgment
The percentage-based moving average difference concept that powers the core oscillator in this script was inspired by the open-source "MA difference" indicator created by @cereallarceny
I am grateful for that foundation and have expanded it into an eight-layer system with cascade alignment logic, macro divergence detection, additional filters, a non-repainting framework, and a publication-ready alert suite. This credit appears first to clarify lineage, and the rest of the description focuses on the specific additions and behavioral logic in this version.
Indicator name and purpose
Eight Moving Average Cross with Macro Divergences is a multi-layer trend alignment and macro reversal map. It converts eight moving averages into a percentage-difference oscillator so you can read how far each layer of the trend structure is positioned relative to a base reference. The script then adds two complementary decision layers: a Cascade signal to detect synchronized momentum shifts across the trend stack, and a Macro Divergence map that highlights early warning signs of trend exhaustion or trend continuation.
What it does
You receive a clean oscillator pane that shows when short-term momentum aligns with the long-term structure, and when the price action is losing strength at meaningful pivots. The Cascade layer provides a filtered trigger for momentum shifts, while the divergence layer provides a higher-timeframe context for reversals or continuation. The result is an indicator that can be used as a standalone oscillator for structure analysis, or as a confirmation layer in a broader trading plan. If you already use moving averages in your workflow, this script turns them into an objective percentage-based structure map that is easier to compare across markets and timeframes.
How it works in detail
The engine calculates the percentage distance between a base moving average and seven additional moving averages. Every layer expresses whether it is above or below the base, and by how much. These percentage differences are plotted and can be filled against the zero line to visualize bullish and bearish structure. The Cascade logic looks for a cross of the zero line from the short, medium, or long layer, but only allows a signal when the extra long-term layers are already aligned in the same direction. This ensures that a short-term shift is supported by the broader trend stack instead of being a simple noise move.
The Macro Divergence module is built from confirmed pivot swings. It uses a long-term reference, defined by the long moving average, to find price pivots and compares those pivots with a smoothed oscillator derived from the extra long-term averages. Classic divergences are detected when price makes a higher high while the oscillator makes a lower high, or when price makes a lower low while the oscillator makes a higher low. Hidden divergences are detected when price retains trend structure but the oscillator counter-swings, often signaling trend continuation. To reduce random signals, the algorithm enforces a minimum spacing between pivots and a minimum amplitude for divergence strength. This makes the divergence layer a macro view rather than a noisy micro-signal engine.
How to use it
Use the zero line as the structural boundary. When the short, medium, and long layers move above zero, the short-term structure is bullish. When they move below zero, the short-term structure is bearish. Cascade signals are intentionally strict: they appear only when a base layer crosses zero and all extra long-term layers are aligned. This is a momentum confirmation event rather than a prediction. Divergences should be interpreted as early warnings: a classic bearish divergence suggests that a rally is losing strength at a macro high; a classic bullish divergence suggests accumulation at a macro low. Hidden divergences help you stay with the dominant trend when a temporary retracement appears.
Practical examples
Example for a bullish setup: The short or medium layer crosses above zero, all extra layers are already above zero, and a Cascade Buy highlight appears. This indicates a synchronized bullish structure across short and long horizons. If a hidden bullish divergence appears during a pullback while the extra layers remain positive, it supports the continuation case and provides a structure-based reason to hold the position rather than exit too early.
Example for a bearish setup: The short or medium layer crosses below zero, extra layers are already negative, and a Cascade Sell highlight appears. If a classic bearish divergence appears near a price high, it warns that the bullish structure is weakening and that risk should be reduced.
How the components work together
The Cascade layer acts as a strict trend-alignment filter. The Divergence layer provides macro context and early warnings. Together, they allow you to trade momentum in the direction of the dominant structure while also identifying areas where the structure is at risk of reversal. The oscillator visuals let you see when the trend stack is compressing or expanding, which adds additional context beyond simple cross signals. The percentage-difference approach also makes it easier to compare trend strength across different instruments, because the values scale relative to the base average instead of absolute price.
What makes this script original
This is not a simple moving-average mashup. The script transforms eight averages into a percent-difference oscillator, then uses a layered alignment system to validate momentum shifts and a pivot-based divergence engine to detect macro-level structure shifts. The combination of these two modules produces information that you do not get from a single MA crossover or a standard oscillator divergence. The multi-layer structure, amplitude filtering, pivot spacing, non-repainting framework, and alert language are original additions and are central to the script’s usefulness.
Markets and timeframes
The script is designed for any liquid market, including Forex, Crypto, Stocks, Commodities, and Indices. For intraday use, 15m to 4H timeframes give stable Cascade signals and readable divergences. On daily and weekly charts, divergences are fewer but carry higher significance. For scalping on 1m to 5m charts, reduce moving average lengths and pivot spacing to maintain responsiveness and keep the divergence layer from lagging too far behind. For day trading on 5m to 1H, the defaults work well and provide a balanced signal frequency. For swing trading on 1H to daily charts, consider increasing pivot spacing and smoothing to emphasize macro swings. For longer-term investing on weekly to monthly charts, increase the long and extra MA lengths to match the broader cycle.
Settings guidance
Base Length controls the anchor average used for all percentage differences. Short, Medium, and Long define the base cross structure and provide the momentum layer. Extra MA 1-4 are the long-term alignment stack for Cascade and the core of the divergence oscillator. Pivot lookback left and right define how far the script looks to confirm a swing; higher values mean fewer but stronger divergences. Minimum bars between pivots is a noise filter that avoids consecutive pivots. Oscillator smoothing reduces erratic swings and sharpens macro structure. Minimum divergence amplitude filters out weak divergence signals.
Tips for tuning
If the oscillator feels too reactive, increase the base length and smoothing to reduce noise. If Cascade signals are too rare, reduce the extra MA lengths or increase the base layer responsiveness. If divergences are too frequent, raise the minimum amplitude or increase the bars-between-pivots setting. If divergences are too slow, reduce smoothing and pivot length, but expect more false positives. These changes should be tested per symbol, because volatility and trading session behavior can differ significantly between markets.
Alerts
The alert system is fully integrated with the non-repainting framework. Cascade Buy and Cascade Sell alerts trigger only after confirmed bar close when the Cascade conditions are met. Divergence alerts trigger only after confirmed pivot formation, so they do not move once printed. Alert messages include symbol, timeframe, and price to support automation or manual monitoring. This makes the alerts suitable for discretionary traders and for automated alert-to-webhook workflows.
Non-repainting behavior
This script includes a dedicated non-repainting toggle. When enabled, all signals, drawings, and alerts are confirmed on closed bars. This means a signal cannot appear and then disappear. The trade-off is a small delay in signaling, but it ensures historical and live behavior match, which is critical for honest backtesting and reliable alerts. When disabled, the script remains visually responsive for exploration, but users should treat signals as provisional until the bar closes.
Disclaimer
This indicator is a technical analysis tool and does not constitute financial advice. No indicator is perfect. Always use risk management, validate signals with additional context, and test settings on your chosen market and timeframe before trading with real funds.
Pine Script®指标
Piv X**Title:** Piv X: Confluence-Based Market Structure & Volume Analyzer
**Introduction**
Piv X is a comprehensive market structure analysis tool designed to grade the quality of Pivot Points using a composite "Confluence Score." Unlike standard indicators that simply identify local highs and lows based on price alone, this script evaluates the *strength* of every pivot by cross-referencing it against volume data, momentum divergences, multi-timeframe structure, and institutional key levels.
**Concept & Methodology**
The core functionality of this script builds upon a **Dynamic Pivot Quality Scoring System**. When a pivot point is detected (using an ATR-based dynamic lookback), the script runs a background analysis on 10+ technical factors to assign a "Confluence Score" (0-100).
The score is calculated based on the accumulation of the following factors:
1. **Volume Anomalies**: Detects volume spikes at the pivot, suggesting institutional participation.
2. **Momentum Divergence**: Checks for RSI and Williams %R divergences relative to price action to identify exhaustion.
3. **Liquidity Mechanics**: Identifies "Swing Failure Patterns" (SFP) and "Sweeps" where price pierces a previous structure but closes back inside.
4. **Multi-Timeframe Alignment**: Verifies if the pivot aligns with Higher Timeframe (HTF) trends and structures to filter out counter-trend noise.
5. **Key Level Interaction**: Rewards pivots that form near Daily/Weekly Highs or Lows.
6. **Fair Value Gap (FVG) Fills**: Detects if the pivot is reacting to a market imbalance fill.
**Unique Feature: Williams %R Divergence Anchored VWAP**
This tool introduces a logic-driven Anchored VWAP. Instead of arbitrarily anchoring VWAPs to high/low dates, the script automatically anchors a VWAP from the exact candle where a Williams %R Momentum Divergence is confirmed. This allows traders to visualize the "true cost basis" of participants who entered specifically on the momentum reversal signal.
**How to Use**
1. **Golden Zones (High Confluence)**: Pivots that achieve a high Confluence Score (e.g., >80) are highlighted with a distinct "Golden" border and background. These represent high-probability Support/Resistance levels backed by multiple forms of technical evidence.
2. **Standard Zones (Normal Confluence)**: Pivots with moderate scores are shown in standard Green/Purple. These are valid structure points but may require additional confirmation before trading.
3. **Trend Filtering**: The "Trend System" overlay (using EMA Clouds and RSI filters) provides visual context for the dominant trend direction, helping traders avoid taking structure signals against the main flow.
4. **Market Structure Shifts (MSS)**: The script automatically plots CHoCH (Change of Character) lines to alert traders when the sequence of Higher Highs or Lower Lows has been broken, often signaling a trend reversal.
**Settings**
* **Pivot Detection**: Adjust the ATR Multiplier to control the sensitivity of pivot detection.
* **Filters**: Toggle specific scoring factors (like Session Logic or HTF Confluence) to customize how strict the Scoring System is.
* **Visuals**: Enable/Disable specific VWAP periods (Weekly, Monthly, Yearly) to keep the chart clean.
**Disclaimer**
This tool is intended for market analysis and educational purposes only. Past performance of these setups does not guarantee future results.
Pine Script®指标
Volatility Adjusted Cloud | Lyro RSThe Volatility Adjusted Cloud (VAD Cloud) is a sophisticated technical analysis tool designed to identify and adapt to shifting market conditions by combining a Variable Index Dynamic Average (VIDYA) baseline with volatility-scaled deviation bands. This indicator employs a dual-layer approach, integrating an adaptive VIDYA midline with asymmetric cloud bands, to provide traders with a dynamic and responsive overlay that adjusts naturally to changes in price momentum and market volatility.
Indicator Components
VIDYA Midline
At the core of the VAD Cloud is a Variable Index Dynamic Average — a self-adjusting moving average that accelerates during trending conditions and slows during consolidation. Rather than using a fixed smoothing constant, VIDYA scales its responsiveness based on the ratio of short-term to long-term standard deviation, making it inherently adaptive to volatility regimes.
The midline is further smoothed with an ALMA pass and rendered with a glow effect for visual clarity, serving as the primary trend reference.
Volatility Adjusted Bands
The upper and lower bands are constructed using a VIDYA-smoothed deviation of price from the midline — a measure of dispersion that is itself adaptive to volatility:
Upper Band = VIDYA Midline + (VIDYA Deviation × Positive Multiplier)
Lower Band = VIDYA Midline − (VIDYA Deviation × Negative Multiplier)
The asymmetric multipliers allow traders to independently tune the sensitivity of each band, accommodating instruments with directional skew or asymmetric volatility profiles. These bands expand during volatile periods and contract during consolidation, clearly delineating breakout and breakdown zones.
Cloud Fill & Signal Coloring
The space between the upper and lower bands is filled with a dynamic cloud that reflects the current trend state. Color transitions occur when:
Price crosses above the upper band → Bullish state (cloud, candles, and midline update to bullish color)
Price crosses below the lower band → Bearish state (cloud, candles, and midline update to bearish color)
The entire visual system — candles, midline, glow, and cloud — updates in unison to reflect the active trend direction at a glance.
Signal Interpretation
A Long signal is generated when price crosses above the upper VAD band, indicating bullish momentum expansion
A Short signal is generated when price crosses below the lower VAD band, signaling bearish pressure dominance
Signals are marked with clearly labeled Long / Short shapes directly on the chart
Trend Confirmation
When price is above the midline with a bullish cloud → conditions favor uptrend continuation
When price is below the midline within a bearish cloud → downside momentum is dominant
The VIDYA midline acts as a dynamic support/resistance reference throughout
Midline-Only Mode
For traders who prefer a cleaner chart, enabling Midline Only hides the bands and cloud fill entirely, displaying only the VIDYA line with a gradient fill between the midline and current price — ideal for use alongside other indicators.
Customization
Four built-in color palettes : Classic, Mystic, Accented, Royal
Full custom color support for both bullish and bearish states
Independently adjustable positive and negative band multipliers
Configurable cloud transparency for visual comfort
⚠️ Disclaimer
This indicator is a technical analysis tool and does not guarantee results. It should be used in conjunction with additional analysis methods and proper risk management strategies. The creators of this indicator are not responsible for any financial decisions made based on its signals.
Pine Script®指标
Log Return Price Change Tanh OscillatorPrice Acceleration Oscillator (Normalized) — Detailed Description
Price Acceleration Oscillator (PAO) is a normalized momentum–acceleration indicator designed to measure how fast price is speeding up or slowing down, rather than simply whether it is going up or down.
Unlike traditional momentum oscillators that react mainly to price direction, PAO focuses on changes in momentum dynamics, making it especially useful for identifying early acceleration, deceleration, and momentum exhaustion phases.
Core Concept
PAO decomposes price movement into two components:
Velocity – the smoothed rate of price change
Acceleration – the change in velocity (momentum increase or decrease)
These components are statistically normalized and blended into a bounded oscillator, allowing consistent interpretation across different assets, timeframes, and volatility regimes.
Calculation Logic (High-Level)
Log Return (Scale-Invariant)
Uses N-bar logarithmic returns instead of raw price changes
Ensures consistency across instruments with different price levels
Velocity
Exponential moving average of log returns
Represents smoothed price speed
Acceleration
First difference of velocity
Measures whether momentum is increasing or fading
Statistical Normalization
Velocity and acceleration are independently normalized using rolling standard deviation
Converts both into dimensionless z-score–like measures
Weighted Blending
User-defined weighting between velocity and acceleration
Allows emphasizing trend persistence or momentum change
Nonlinear Compression (tanh)
Hyperbolic tangent transformation bounds the oscillator to ±100
Prevents extreme spikes while preserving structure
Dead Zone Filtering
Small values near zero are suppressed
Reduces noise and visual clutter in low-momentum conditions
Oscillator Interpretation
Above 0 → Bullish acceleration
Below 0 → Bearish acceleration
Key Zones
±25 → Early acceleration / deceleration
±50 → Strong momentum expansion
±80 → Extreme acceleration (potential exhaustion zones)
The oscillator measures momentum intensity, not trend direction alone.
Signal Line & Histogram
A smoothed EMA signal line is included for:
Momentum confirmation
Acceleration / deceleration transitions
Histogram shows the spread between oscillator and signal, highlighting momentum shifts and convergence/divergence behavior.
Background Regime Coloring
Optional background shading reflects acceleration strength:
Light colors → weak / early momentum
Darker colors → strong or extreme acceleration
This provides fast visual context without relying on signals.
Live Statistics Dashboard
The built-in table displays:
Current market state (Bullish / Bearish)
Momentum strength classification
Oscillator value and intensity
Signal spread and momentum bias
Return measurement context
Designed for decision support, not automated trade execution.
Alerts
Optional alerts are available for:
Zero-line acceleration shifts
Strong acceleration thresholds
Oscillator / signal crossings
Alerts reflect momentum state changes, not buy/sell instructions.
Intended Use
PAO is best used to:
Detect early momentum expansion or loss
Filter low-quality trades during choppy conditions
Complement trend-following or mean-reversion systems
Analyze market regime behavior rather than price direction alone
This indicator is not a standalone trading system and should be used in conjunction with broader market context, risk management, and confirmation tools.
Pine Script®指标






















