3D Money Flow Index [UAlgo]3D Money Flow Index is a visual enhancement of the Money Flow Index that transforms a classic momentum oscillator into a pseudo 3D ribbon rendered inside its own pane. Instead of displaying MFI as only a single flat line, the script builds a front surface, a back surface, connecting edges, and shaded faces, then projects those elements through a camera style transformation using configurable yaw and pitch angles. The result is a depth based MFI visualization that makes momentum shifts, expansion, compression, and reversals much more expressive than a standard oscillator plot.
The indicator runs in a separate pane ( overlay=false ) and combines several components into one visual framework:
A custom MFI style calculation
A 3D ribbon built from projected historical MFI values
Optional dynamic ribbon depth based on volatility
Buy and sell markers when MFI crosses key threshold levels
Regular bullish and bearish divergence detection using MFI pivots versus price pivots
Projected guide levels for 80, 50, and 20
This makes the script useful for traders who want both analysis and presentation. It keeps the familiar MFI logic at the core, but wraps it in a more intuitive spatial display that can help visually separate trend persistence, reversal attempts, and divergence structures.
Educational tool only. Not financial advice.
🔹 Features
🔸 1) 3D Ribbon Style MFI Visualization
The core feature of the script is a pseudo 3D MFI ribbon. For each historical bar inside the selected history length, the indicator creates a front and back layer around the same MFI value, connects those layers with side edges, and fills the face between them. This gives the oscillator a ribbon like body rather than a single thin line.
The ribbon is projected into the pane using time for the horizontal axis and MFI value for the vertical axis, which creates a clean depth illusion without leaving the oscillator panel.
🔸 2) Adjustable Camera Style Projection
The script includes two visual controls that change how the ribbon appears in space:
Yaw Angle changes the left right visual rotation of the ribbon
Pitch Angle changes the vertical tilt of the ribbon
These controls allow the user to choose a flatter, more technical display or a more dramatic perspective oriented look.
🔸 3) Configurable Ribbon Depth
The Ribbon Depth setting controls how thick the 3D body appears along the synthetic Z axis. Lower values create a thinner ribbon, while higher values create a deeper and more dramatic structure.
This is especially useful when adapting the visualization for different screen sizes or preferred chart density.
🔸 4) Optional Dynamic Volatility Based Depth
When enabled, the script automatically scales ribbon depth using current ATR relative to its longer average. This means the visual thickness expands during higher volatility and compresses during quieter periods.
The result is a ribbon that can communicate both oscillator behavior and relative volatility regime at the same time.
🔸 5) Custom Money Flow Index Calculation
Instead of using the built in ta.mfi() , the script calculates its own MFI style series from positive and negative money flow sums derived from price change and volume. This gives the indicator full internal control over the oscillator values used by the 3D engine, divergence logic, and threshold signals.
🔸 6) Buy and Sell Threshold Markers
The script generates event markers when MFI crosses important momentum thresholds:
Buy style event when MFI crosses above 20
Sell style event when MFI crosses below 80
These events are rendered as small 3D boxes attached to the ribbon, which keeps the signal presentation consistent with the indicator’s depth based design.
🔸 7) Regular Divergence Detection
The indicator can detect regular divergence by comparing MFI pivots to price pivots:
Bearish divergence when price makes a higher high but MFI makes a lower high
Bullish divergence when price makes a lower low but MFI makes a higher low
Divergence is optional and can be turned on or off through the settings.
🔸 8) 3D Aligned Divergence Lines
When a divergence is detected, the script draws a thicker line between the two MFI pivot points, positioned on the ribbon’s front face so the divergence appears visually attached to the 3D structure instead of floating away from it.
It also draws dotted connector lines from the divergence line back to the ribbon body, reinforcing the spatial relationship.
🔸 9) Historical Ribbon Length Control
The History Length input limits how many bars of 3D ribbon are drawn. This helps balance visual richness with performance and keeps the pane from becoming overcrowded.
🔸 10) Gradient Color Mapping by MFI Level
The ribbon is colored dynamically using a gradient based on MFI value:
Lower readings lean bearish
Higher readings lean bullish
This means the ribbon itself functions as a live regime map, not just a structural shape.
🔸 11) Projected Guide Levels
The script draws perspective aligned guide levels for:
80
50
20
These are not flat horizontal pane lines. They are projected using the same camera logic as the ribbon, which keeps the entire display visually coherent.
🔸 12) Full Last Bar Redraw for Visual Consistency
All 3D objects are deleted and rebuilt on the last bar. This ensures that the current camera angles, ribbon depth, divergence set, and markers are always rendered consistently with the latest data.
🔸 13) Object Based Design for Maintainability
The script uses several custom types:
Point3D for synthetic 3D coordinates
Point2D for projected time / value coordinates
Camera for projection controls
DivLine for stored divergence events
This makes the visual engine and signal logic more structured and easier to extend.
🔹 Calculations
1) Custom MFI Style Calculation
The script computes money flow using separate positive and negative sums based on the change in the selected source:
float upper = math.sum(volume * (ta.change(src) <= 0 ? 0 : src), length)
float lower = math.sum(volume * (ta.change(src) >= 0 ? 0 : src), length)
Then it computes an MFI style output:
float ratio = lower == 0 ? 0 : upper / lower
100.0 - (100.0 / (1.0 + ratio))
Interpretation:
Positive source changes contribute to the upper flow sum.
Negative source changes contribute to the lower flow sum.
The resulting ratio is converted into an oscillator style value on a 0 to 100 scale.
Important implementation note:
This is a custom MFI style calculation, not the built in PulseWire MFI function. The script uses its own edge case handling when lower == 0 .
2) Volatility Based Depth Scaling
The dynamic depth option uses ATR relative to a longer ATR average:
float atr = ta.atr(14)
float avg_atr = ta.sma(atr, 100)
float depth_scaler = use_dynamic_depth ? math.max(0.5, math.min(2.5, atr / avg_atr)) : 1.0
Interpretation:
If current ATR is above its longer average, the ribbon becomes deeper.
If current ATR is below its longer average, the ribbon becomes thinner.
The multiplier is clamped between 0.5 and 2.5 for stability.
3) 3D Coordinate Model
Each ribbon segment uses synthetic 3D coordinates:
x represents bars back in history
y represents the MFI value
z represents the ribbon depth offset
For each bar, the ribbon creates:
A front point at z = -depth / 2
A back point at z = depth / 2
This creates the geometry needed for the front edge, back edge, side edge, and face fill.
4) Camera Projection Logic
The script projects each 3D point into 2D coordinates using yaw and pitch rotations:
float x1 = p.x * math.cos(rad_yaw) - p.z * math.sin(rad_yaw)
float z1 = p.x * math.sin(rad_yaw) + p.z * math.cos(rad_yaw)
float y1 = p.y * math.cos(rad_pitch) - z1 * math.sin(rad_pitch)
Then it converts the projected coordinates into chart coordinates:
int proj_time = int(ref_time - (x1 * time_step))
float proj_price = y1
Interpretation:
The script does not use true 3D rendering. It uses geometric projection math to simulate depth within normal chart objects.
5) Time Step Mapping
The horizontal spacing of projected points is derived from current chart time:
int dt = time - time
if bar_index == 0
dt := 60000
This lets the projected ribbon stay aligned with the current timeframe interval.
6) Ribbon Segment Construction
For each bar pair in the selected history window, the script creates:
Front line from point A front to point B front
Back line from point A back to point B back
Connector line from point A front to point A back
A filled face polygon between the front and back edges
This produces the actual ribbon body. The fill is created only for recent segments to stay within object limits:
if i < 90
...
polylines.push(polyline.new(points, ... fill_color=face_col ...))
7) Gradient Color Logic for the Ribbon
The ribbon color is mapped from current MFI value:
color base_col = color.from_gradient(val_a, 20, 80, col_bear, col_bull)
Interpretation:
Lower MFI values shift toward the bearish color.
Higher MFI values shift toward the bullish color.
Midrange values naturally blend between the two.
8) Buy and Sell Signal Logic
The script defines simple threshold crossing events:
bool sig_buy = ta.crossover(mfi_val, 20)
bool sig_sell = ta.crossunder(mfi_val, 80)
Interpretation:
Buy event means MFI rises back above the lower threshold, which can suggest recovery from oversold pressure.
Sell event means MFI falls back below the upper threshold, which can suggest rejection from overbought pressure.
These are event markers, not standalone entry guarantees.
9) 3D Marker Drawing
When a buy or sell signal occurs, the script draws a small 3D box marker using the same projection engine as the ribbon. The marker is built from four projected corners and connected with line segments so it appears attached to the ribbon structure.
This keeps the signal styling consistent with the rest of the indicator.
10) Pivot Detection for Divergence
The divergence engine finds pivot highs and lows on the MFI series:
float ph = ta.pivothigh(mfi_val, piv_len, piv_len)
float pl = ta.pivotlow(mfi_val, piv_len, piv_len)
Each pivot is aligned to its true pivot bar using:
int curr_piv_bar = bar_index - piv_len
This ensures divergence anchors are placed at the actual turning points, not the later confirmation bar.
11) Bearish Divergence Logic
When an MFI pivot high is confirmed, the script compares it with the prior MFI pivot high:
bool bear_div = (curr_price_high > last_price_ph) and (curr_piv_val < last_ph_val)
Interpretation:
Price makes a higher high
MFI makes a lower high
If true, a bearish divergence line is stored.
12) Bullish Divergence Logic
When an MFI pivot low is confirmed, the script compares it with the prior MFI pivot low:
bool bull_div = (curr_price_low < last_price_pl) and (curr_piv_val > last_pl_val)
Interpretation:
Price makes a lower low
MFI makes a higher low
If true, a bullish divergence line is stored.
13) Divergence Storage and Cleanup
Detected divergences are stored in an array of DivLine objects. Older divergence entries are removed once they fall too far outside the active visual window:
if (bar_index - divergences.get(0).start_bar) > (history_len + 100)
divergences.shift()
This prevents old divergence structures from accumulating forever.
14) 3D Aligned Divergence Rendering
When a divergence is drawn, the script places it on the front face of the ribbon by using:
float z_offset = -current_depth / 2.0
This is an important visual detail because it keeps the divergence line attached to the ribbon surface rather than offset in empty space.
The script also draws dotted connector lines from the divergence line endpoints back to the ribbon center plane, reinforcing the 3D attachment.
15) Projected Guide Level Rendering
The indicator draws projected guide levels at 80, 50, and 20 using the same projection method:
draw_grid_line(80, color.red)
draw_grid_line(50, color.gray)
draw_grid_line(20, color.green)
This keeps the threshold references visually aligned with the ribbon perspective instead of using flat horizontal lines that would break the illusion.
16) Full Last Bar Rebuild Process
On the last bar, the script:
Deletes all existing lines, polylines, and labels
Recreates the camera
Rebuilds the ribbon over the selected history length
Replots signal markers
Renders divergence lines
Draws guide levels
This full redraw approach ensures visual consistency whenever the latest bar changes, the camera angles change, or volatility depth changes. Indicator

Indicator

SMT Divergence Strength Index [Metrify]This indicator detects SMT-style divergence between the chart symbol and a user-defined reference symbol, then filters those divergence events using a statistical strength condition. The goal is to separate ordinary pivot mismatches from divergence events that occur during unusually large relative movement between the two instruments.
It combines three components in one script: pivot-based divergence detection, Z-score normalization of momentum spread, and a correlation plot for context. The output is an oscillator panel (Z-score columns + correlation line) plus optional SMT labels/lines drawn on the main chart.
SMT divergence logic (structural layer)
The structural part of the script is based on confirmed pivots on the main symbol.
For bearish SMT detection, the script checks whether the main symbol forms a higher high while the reference symbol (evaluated at the same pivot event point) forms a lower high relative to the previous corresponding pivot event. For bullish SMT detection, it checks whether the main symbol forms a lower low while the reference symbol forms a higher low
Reference symbol and inversion
The Reference Symbol (Pairing) input defines the market used for comparison. The usefulness of the divergence output depends heavily on this pairing. The script assumes the comparison is meaningful enough that non-confirmation between the two symbols can be interpreted as a potential imbalance or relative weakness/strength event.
The 'Invert Correlation' option transforms the reference data by using reciprocal values before the divergence and correlation calculations. This can be used when analyzing pairs that are expected to move inversely (like alt to btc in specific event), so the comparison orientation better matches the intended relationship.
Invert Correlation mode (what it does and why it exists)
The Invert Correlation option changes how the reference symbol is transformed before all downstream calculations (pivot comparison, momentum spread, Z-score, and correlation plot). When enabled, the script does not compare the main symbol to the raw reference prices. Instead, it compares against the reciprocal form of the reference series:
reference high is transformed using 1 / low
reference low is transformed using 1 / high
reference close is transformed using 1 / close
This inversion is used so that an inversely related market can be analyzed in the same directional framework as a positively correlated one. In practical terms, it converts an opposite direction relationship into a comparable orientation for SMT logic. After inversion, moves that would normally appear opposite can be interpreted as if they were aligned, allowing the same higher-high / lower-high and lower-low / higher-low SMT structure rules to be applied consistently.
Conceptually, invert mode is useful when your reference asset is expected to move opposite to the main asset and you want the script to evaluate non-confirmation in a unified SMT framework. It does not automatically improve signal quality, but simply changes the orientation of the comparison so the divergence logic matches the relationship you are trying to study.
Use normal mode when the pair is usually expected to move in the same direction.
Use invert mode when the pair is usually expected to move in opposite directions (or when your analysis framework treats one as a risk-off mirror of the other).
Good inversion-pair examples (practical)
1) Risk asset vs Dollar Index (DXY)
This is one of the cleanest concepts for inversion.
BTCUSD vs DXY
ETHUSD vs DXY
OIL VS DXY
NASDAQ (NDX / US100) vs DXY
Gold vs DXY (often inverse, but can break regime)
When DXY rises, risk assets often weaken. Inverting DXY makes the reference move in the same orientation as the risk asset.
2) Equity index vs VIX
Very common inverse relationship idea.
SPX / ES / NQ vs VIX
BTC (sometimes) vs VIX as a broader risk proxy (less direct, more regime dependent)
Why inversion helps: VIX is typically "fear up when equities down". Inverted VIX can be used as a proxy for risk-on alignment.
3) USD-quoted asset vs USD strength proxy
If your main symbol is sensitive to USD strength:
XAUUSD vs DXY
EURUSD vs DXY
GBPUSD vs DXY
AUDUSD vs DXY
These are classic macro pairings where inversion often makes analytical sense.
4) Some commodity currencies vs commodity / dollar drivers (case-by-case)
Examples can work, but are more conditional:
USDCAD vs Oil (WTI) (often inverse-ish relationship via CAD/oil linkage)
AUDUSD vs Copper (sometimes)
NZDUSD vs risk proxy
These are not as stable as DXY/VIX examples, so you need to monitor correlation more carefully.
Trigger conditions in plain terms
A bearish SMT label appears only when all required conditions are satisfied:
a confirmed pivot high exists on the main symbol,
the current main pivot high is higher than the previous main pivot high,
the aligned reference high at the same pivot event is lower than its previous aligned reference high,
and the Z-score condition exceeds the configured threshold.
A bullish SMT label follows the mirrored condition/vice versa.
Display behavior and non-repaint option
The indicator uses confirmed pivots, so signals are known only after pivot confirmation. The Non repaint mode setting controls how labels are displayed:
Enabled: labels are shown on the trigger/confirmation bar (the bar where the pivot is confirmed and the signal becomes true).
Disabled: labels are shifted back to the pivot bar for visual alignment.
This setting affects visualization only. It does not change the underlying pivot confirmation process.
This indicator marks pivot-based intermarket non-confirmation events that occur during statistically elevated relative dislocation.
Pair selection remains a major source of variation in output quality. Weakly related pairs can produce divergence labels that satisfy the script’s rules but are not analytically useful. Indicator

Adaptive Squeeze Momentum Pro [WillyAlgoTrader]Adaptive Squeeze Momentum Pro is a non-overlay oscillator that combines volatility compression detection (squeeze) with an ATR-normalized momentum histogram and built-in divergence scanning — providing three layers of analysis in a single pane: when the market is coiling (squeeze), which direction the energy is building (momentum), and when momentum is diverging from price (divergence warnings).
The classic squeeze momentum concept — Bollinger Bands contracting inside Keltner Channels — has been available on PulseWire for years. What this indicator adds is an entirely different momentum calculation that is ATR-normalized (making it comparable across instruments and timeframes), a 4-state color-coded histogram that distinguishes between momentum acceleration and deceleration in both directions, automated divergence detection with optional HTF trend filtering, and a preset system tuned for different trading styles. The result is a modernized squeeze oscillator designed for practical trading rather than textbook demonstration.
🔍 WHAT MAKES IT ORIGINAL
1. ATR-normalized momentum oscillator. Most squeeze indicators use a raw linear regression value or simple price-minus-midline for their histogram. This makes the oscillator's scale dependent on the instrument's price level — a reading of 5.0 on BTCUSD means something completely different than 5.0 on EURUSD. This indicator solves that by dividing the raw momentum by the current ATR value, producing a dimensionless oscillator that typically ranges between −3 and +3 regardless of instrument or timeframe. The raw momentum itself is calculated as the distance between price and the average of the highest-high/lowest-low midpoint and an EMA — capturing both range-based and trend-based positioning. An optional EMA smoothing layer (configurable, default 3) reduces noise without excessive lag.
2. EMA-based volatility bands instead of standard Bollinger Bands. The squeeze detection uses an EMA (not SMA) as its basis, paired with standard deviation for the band width. EMA reacts faster to recent price changes than SMA, making the squeeze detection more responsive to volatility shifts — particularly useful on crypto and volatile instruments where compression phases can be short-lived. The ATR channel (replacing the traditional Keltner Channel) uses the same EMA basis. The squeeze fires when the volatility band width is less than the ATR channel width (ratio < 1.0).
3. Tiered squeeze intensity. Instead of a binary on/off squeeze state, the indicator classifies the compression into four tiers based on the ratio between the volatility band width and the ATR channel width:
— EXTREME (ratio < 0.5): very tight compression, highest energy buildup
— HIGH (ratio < 0.7): significant compression
— MID (ratio < 0.9): moderate compression
— LOW (ratio < 1.0): mild compression
— NONE (ratio ≥ 1.0): no squeeze
This lets you distinguish between a mild contraction (which may resolve quietly) and an extreme compression (which is more likely to produce a strong directional move).
4. 4-state histogram coloring. The momentum histogram uses four distinct colors to convey both direction and acceleration:
— Bull Strong (bright green): momentum above zero AND rising — bulls are accelerating
— Bull Weak (teal): momentum above zero BUT falling — bulls are decelerating, potential topping
— Bear Strong (bright red): momentum below zero AND falling — bears are accelerating
— Bear Weak (dark red): momentum below zero BUT rising — bears are decelerating, potential bottoming
The transition from Strong to Weak (or vice versa) often precedes a zero-line cross, giving an early visual warning of momentum shifts.
5. Automated divergence detection with two modes. The indicator scans for classic divergences between price pivots and momentum pivots:
— Bullish divergence : price makes a lower low while momentum makes a higher low
— Bearish divergence : price makes a higher high while momentum makes a lower high
Two detection modes are available:
— Early mode (default): divergence is labeled on bar close at the pivot with zero right-side confirmation bars — fastest detection, may occasionally produce false signals
— Confirmed mode : requires N confirmation bars on the right side of the pivot (same as the lookback length) — more reliable, but delayed
Divergence lines are drawn on the oscillator connecting the two momentum pivots, and optional overlay labels are placed directly on the price chart (using force_overlay) so you can spot divergences without switching panes.
6. HTF trend filter for divergences. An optional higher-timeframe filter compares a 21-period EMA to a 50-period EMA on the selected HTF (default 60min). When enabled, bullish divergences are only shown when the HTF trend is bullish (fast EMA > slow EMA), and bearish divergences only when HTF is bearish. The HTF data uses the standard non-repainting pattern ( + lookahead_on). This filter reduces counter-trend signals that divergences often produce.
⚙️ HOW IT WORKS
Squeeze detection:
On each bar, the script calculates two band widths:
— Volatility band width = StdDev(source, length) × multiplier × 2, centered on an EMA
— ATR channel width = ATR(length) × multiplier × 2
The squeeze ratio = volatility width / ATR width. When this ratio falls below 1.0, volatility bands are inside the ATR channel — the market is in a squeeze. The tier is determined by how far below 1.0 the ratio is.
Momentum calculation:
— Midpoint 1: (highest high over N bars + lowest low over N bars) / 2
— Midpoint 2: EMA(source, N)
— Combined midpoint: average of Midpoint 1 and Midpoint 2
— Raw momentum: source − combined midpoint
— Normalized momentum: raw momentum / ATR(N)
— Final momentum: EMA(normalized momentum, smoothing) if smoothing > 1, else raw normalized
This approach blends range-based positioning (where is price within the recent range) with trend-based positioning (where is price relative to the EMA), then normalizes by ATR so the oscillator is instrument-agnostic.
Divergence detection:
The script uses ta.pivotlow() and ta.pivothigh() on both the momentum oscillator and price (low/high). For each new momentum pivot, it compares against the previous stored pivot. A bullish divergence is detected when the current price pivot low is lower than the previous one, but the current momentum pivot low is higher. Bearish divergence is the mirror. In Early mode (rightBars = 0), the pivot is identified at bar close without waiting for right-side confirmation. In Confirmed mode (rightBars = lookback), pivots are only confirmed after N bars pass.
HTF filter:
HTF EMAs are fetched with request.security() using the + lookahead_on non-repainting pattern. When the 21 EMA is above the 50 EMA on the higher timeframe, the HTF trend is bullish; below = bearish.
Squeeze release alert:
The "squeeze fired" alert triggers on the first confirmed bar after the squeeze condition ends (sqzOn transitions from true to false). The alert message includes the momentum direction at release (bullish if momentum > 0, bearish if ≤ 0).
📖 HOW TO USE
Reading the histogram:
— Bright green bars (Bull Strong) = momentum above zero and accelerating — strongest bullish phase
— Teal bars (Bull Weak) = momentum above zero but decelerating — bulls losing steam
— Bright red bars (Bear Strong) = momentum below zero and accelerating — strongest bearish phase
— Dark red bars (Bear Weak) = momentum below zero but decelerating — bears losing steam
— Transition from Strong → Weak = early warning of momentum exhaustion
— Zero-line cross after Weak phase = momentum direction change
Reading the squeeze:
— Orange-tinted background = active squeeze (volatility compression)
— The longer and tighter the squeeze, the more energy is stored
— Watch for the first bar after the background clears (squeeze release) — the momentum direction at that moment often indicates the breakout direction
Reading divergences:
— Green "Div" label below the oscillator / below price = bullish divergence (potential bottom)
— Red "Div" label above the oscillator / above price = bearish divergence (potential top)
— Lines on the oscillator connect the two pivots that form the divergence
— Divergences inside a squeeze are particularly powerful — they suggest the breakout direction before the squeeze releases
Suggested workflow:
— Wait for a squeeze to form (background tint appears)
— Watch for divergences during the squeeze — they hint at breakout direction
— On squeeze release, check momentum direction and histogram color
— Bright green at release = bullish breakout bias; bright red = bearish
— If HTF filter is enabled, only take signals aligned with the higher-timeframe trend
Presets:
— Conservative : length ≥ 25, BB mult ≥ 2.2, ATR mult ≤ 1.2, smoothing ≥ 7 — fewer signals, smoother histogram, suited for 4H–Daily
— Default : uses your manual settings — balanced for 15min crypto
— Aggressive : length ≤ 14, BB mult ≤ 1.6, ATR mult ≥ 1.6, smoothing ≤ 2 — more signals, faster reaction
— Scalping : length ≤ 10, BB mult ≤ 1.4, ATR mult ≥ 1.8, no smoothing — optimized for 1–5min
⚙️ KEY SETTINGS REFERENCE
— Squeeze Length (default 21): shared lookback for EMA, StdDev, and ATR — higher = slower squeeze detection, longer compression phases
— Volatility Band Mult (default 1.8): multiplier for the EMA ± StdDev bands — higher = wider bands, squeeze triggers more easily
— ATR Channel Mult (default 1.6): multiplier for the ATR channel — lower = narrower channel, squeeze triggers less
— Momentum Length (default 20): lookback for highest-high, lowest-low, and momentum EMA
— Momentum Smoothing (default 3): EMA smoothing on the normalized momentum — 1 = raw, higher = smoother
— Divergence Lookback (default 3): pivot detection lookback for divergence scanning
— Early Divergence (default On): label on bar close with no right-side confirmation — faster but less filtered
— Use HTF Trend Filter (default Off): filter divergences by higher-timeframe EMA trend
— Higher Timeframe (default 60): HTF for trend filter — should be 3–5× chart timeframe
🔔 Alerts
Three alert conditions (all bar-close confirmed):
— Squeeze Fire : squeeze releases — includes momentum direction (bullish/bearish)
— Bullish Divergence : price lower low + momentum higher low — includes HTF trend status
— Bearish Divergence : price higher high + momentum lower high — includes HTF trend status
All support standard text and JSON webhook format.
⚠️ IMPORTANT NOTES
— This indicator is a non-overlay oscillator — it appears in a separate pane below the chart. Optional divergence labels can be mirrored on the price chart via the "Show Divergences on Chart" toggle.
— All signals require bar-close confirmation . The HTF filter uses the standard non-repainting security call pattern ( + lookahead_on).
— Early divergence mode (default) labels divergences without waiting for right-side pivot confirmation — this provides faster signals but may occasionally flag a divergence that is later invalidated. Switch to Confirmed mode for higher reliability at the cost of delay.
— A squeeze release indicates that volatility is expanding — it does not guarantee a directional move. False breakouts can and do occur, especially on lower timeframes.
— Divergences signal momentum weakening, not guaranteed reversals. They are most effective as confluence with other analysis, not as standalone signals.
— The ATR normalization makes the oscillator scale-independent, but the absolute readings (e.g. +2.0 vs +1.5) should be compared within the same instrument/timeframe context, not across different ones.
— Works across all asset classes. Volume is not used in any calculation. Indicator

Arbitrage Scanner Pro [Multi-Asset Dashboard]⚡ Arbitrage Scanner Pro
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📌 OVERVIEW
Arbitrage Scanner Pro is a multi-asset monitoring and arbitrage detection system that displays 3 assets simultaneously on one chart. It detects trend divergences between correlated assets, identifies arbitrage opportunities in real-time, and uses speed simulation to make indicators react as if running on sub-minute timeframes (10s, 15s, 30s).
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🧠 HOW IT WORKS
🔹 Speed Simulation Engine
PulseWire's minimum timeframe is 1 minute. This indicator mathematically scales indicator parameters to simulate faster reactions:
• Normal (1m) → Standard indicator behavior
• Simulate 30s → Parameters divided by 2 (2x faster reactions)
• Simulate 15s → Parameters divided by 4 (4x faster reactions)
• Simulate 10s → Parameters divided by 6 (6x faster reactions)
Example in 15s mode: EMA 20 becomes EMA 5, RSI 14 becomes RSI 4, Supertrend Length 5 becomes 1.
🔹 Signal Logic
Each asset runs the same strategy independently using its own price data:
LONG conditions (all must be true):
✅ Supertrend = Bullish (green)
✅ Close > EMA of Highs (breakout above channel)
✅ RSI > 60 (strong momentum)
✅ RSI > RSI Moving Average (momentum accelerating)
✅ Supertrend outside EMA channel (trending, not choppy)
SHORT conditions (all must be true):
✅ Supertrend = Bearish (red)
✅ Close < EMA of Lows (breakdown below channel)
✅ Supertrend outside EMA channel (trending, not choppy)
The "Supertrend outside EMA channel" filter is the key innovation — it eliminates false signals during sideways consolidation by only allowing signals when the market shows a clean directional trend.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 MULTI-ASSET DISPLAY
The indicator creates a stacked 3-panel layout in a single pane:
• Asset A (Main) → Your chart's symbol with overlay indicators
• Asset B (Secondary) → Normalized candles in 0-100 range with full OHLC
• Asset C (Third) → Normalized candles shifted below with adjustable gap
Each secondary asset displays:
📊 Ticker name (e.g., ETHUSDT)
🏛️ Exchange/broker name (e.g., BINANCE) — auto-parsed from symbol
💲 Live price with up to 4 decimal precision
📈 Bar-to-bar percentage change with color coding
Price normalization formula:
Normalized = (Price - 200-bar Low) ÷ (200-bar High - 200-bar Low) × 100
All indicators (EMA channels, Supertrend) are also normalized to the same scale.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 ARBITRAGE DETECTION
The core feature — compares trend directions and signal timing across all 3 assets.
🔹 Signal Divergence (strongest signal):
Fires when two assets generate OPPOSITE signals on the same bar.
Example: Asset A = LONG while Asset B = SHORT → ⚠️ Arbitrage Opportunity
🔹 Trend Divergence (ongoing):
Tracks when assets have different Supertrend directions.
Measured as a Divergence Score from 0/3 (all aligned) to 3/3 (all different).
🔹 Convergence Detection:
Fires when ALL 3 assets trigger the same signal simultaneously.
All LONG → Maximum bullish confirmation.
All SHORT → Maximum bearish confirmation.
🔹 Visual Feedback:
• Yellow background flash → Signal divergence detected
• Green background flash → All assets triggered LONG
• Pink background flash → All assets triggered SHORT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 DASHBOARD
The professional dashboard table shows real-time data for all assets:
• ASSET → Parsed ticker name with emoji identifier
• EXCHANGE → Auto-detected exchange/broker (BINANCE, COINBASE, FX, etc.)
• PRICE → Live close price
• CHANGE → Bar-to-bar % change (green/red)
• TREND → Supertrend direction (▲ BULL / ▼ BEAR)
• SIGNAL → Current state (🚀 LONG! / 🔻 SHORT! / 🟢 Long / 🔴 Short / ⚪ Neutral)
Arbitrage Status Section:
• Overall divergence assessment with descriptive message
• Pair-by-pair comparison (A↔B, A↔C, B↔C) — DIVERGED or ALIGNED
• RSI values for all 3 assets side-by-side
• Divergence score (0/3 to 3/3)
Dashboard size, position, and label sizes are all adjustable.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙️ SETTINGS
🔹 Speed Mode:
Scan Speed → Normal (1m) / Simulate 30s / Simulate 15s / Simulate 10s
🔹 Detection Settings:
Trend Detection Length → Supertrend ATR lookback (default: 5)
Sensitivity Factor → Supertrend ATR multiplier (default: 1.0)
Channel Length → EMA lookback for high/low channel (default: 20)
Momentum Length → RSI period (default: 14)
🔹 Asset Configuration:
Asset B and Asset C can be independently enabled/disabled with custom symbols and candle colors.
🔹 Display Settings:
Show Trend Overlays → Toggle EMA and Supertrend on secondary charts
Signal Style → Labels / Arrows / Both
Gap Between Charts → 80 to 500 (vertical spacing)
Signal Label Offset → Distance of signal labels from candles
🔹 Size Settings:
Dashboard Text Size → Tiny / Small / Normal / Large
Chart Label Size → Tiny / Small / Normal / Large / Huge
Signal Label Size → Tiny / Small / Normal / Large / Huge
Dashboard Position → 9 positions (Top/Mid/Bottom × Left/Center/Right)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔔 ALERTS (12 Total)
Individual (6):
• Asset A LONG / SHORT
• Asset B LONG / SHORT
• Asset C LONG / SHORT
Combined (2):
• ANY asset LONG
• ANY asset SHORT
Arbitrage-Specific (4):
• ⚠️ Signal Divergence detected (opposite signals on same bar)
• 🟢 All 3 assets LONG convergence
• 🔴 All 3 assets SHORT convergence
• 🔶 High divergence score (2+/3)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📈 USE CASES
🔹 Cross-Exchange Arbitrage:
Monitor BTC on BINANCE, COINBASE, and BYBIT simultaneously. When one exchange shows LONG while another shows SHORT, a price discrepancy exists.
🔹 Crypto Correlation Trading:
Watch BTC, ETH, and SOL together. BTC often leads — when BTC triggers LONG first, altcoins typically follow. Enter altcoins on confirmation.
🔹 Forex Multi-Pair Scanning:
Monitor EURUSD, GBPUSD, and USDJPY. When EUR and GBP both show LONG while JPY shows SHORT, it confirms broad USD weakness.
🔹 Index + Sector Rotation:
Track S&P 500 futures alongside QQQ (tech) and XLF (financials). Divergences between sectors reveal which is driving the market.
🔹 News Event Reaction:
Monitor Gold, Dollar Index, and 10-Year Yields during economic releases. The 10s simulation catches reactions within the first minute candle.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ IMPORTANT NOTES
• This uses 1-minute OHLC data — it does NOT create actual sub-minute candles
• Signals fire at bar close, not mid-candle
• The 0-100 normalization can make small moves appear larger
• This is a detection tool — trade execution requires separate infrastructure
• Best used on 1-minute charts where the speed simulation is calibrated
• Always combine with proper risk management
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔧 RECOMMENDED SETTINGS
Crypto (High Volatility): Sim 15s, Length 5, Factor 1.0, Channel 20
Crypto (Low Volatility): Sim 30s, Length 7, Factor 1.5, Channel 25
Forex Majors: Sim 30s, Length 5, Factor 1.5, Channel 20
Stock Indices: Sim 30s, Length 5, Factor 1.0, Channel 15
News Events: Sim 10s, Length 3, Factor 0.5, Channel 10 Indicator

3D RSI [UAlgo]3D RSI is a visual RSI enhancement indicator that transforms the standard RSI line into a dynamic 3D style ribbon inside a separate oscillator pane. Instead of plotting a single line only, the script builds an upper and lower envelope around RSI using a user defined thickness value, then connects and fills those layers bar by bar to create a depth effect. The result is a more expressive RSI display that highlights momentum shifts, overbought and oversold transitions, and local structure in a visually intuitive way.
In addition to the 3D ribbon, the script includes a built in divergence module labeled as 3D Divergence . It detects regular bullish and bearish divergence using RSI pivot highs and lows versus price pivot highs and lows, then draws a bridge style visual in the RSI pane to emphasize the divergence relationship in a depth themed format.
The indicator is designed for traders who want both functionality and presentation. It preserves the standard RSI context through a base RSI plot and common reference levels (70, 50, 30), while adding a layered ribbon, gradient coloring, background zones, live value labeling, and optional divergence annotations.
Educational tool only. Not financial advice.
🔹 Features
🔸 1) 3D RSI Ribbon Visualization
The core feature of the script is a 3D style RSI ribbon built from:
An upper RSI boundary
A lower RSI boundary
A vertical connector on each bar
A filled region between upper and lower boundaries
This creates a depth effect around RSI rather than a flat oscillator line, making momentum expansion and contraction easier to read visually.
🔸 2) User Defined 3D Thickness
The 3D Thickness input controls the distance between the upper and lower ribbon edges around the RSI value. Increasing thickness creates a broader ribbon and a stronger depth effect. Lower values produce a tighter, more precise band around the RSI curve.
🔸 3) Gradient Color Mapping by RSI Level
Ribbon colors are dynamically mapped using a gradient based on RSI value:
Lower RSI values lean toward the Oversold color
Higher RSI values lean toward the Overbought color
This makes the ribbon itself function as a regime heatmap, so you can visually assess oscillator state without reading exact numbers.
🔸 4) Real Time Ribbon Update with Efficient Segment Handling
The script draws new ribbon segments only when a new bar is formed and updates the latest segment while the current bar is still developing. This provides a smooth real time display while controlling object creation and performance.
It also includes cleanup logic that removes older ribbon objects once the stored segment count grows too large.
🔸 5) Built In 3D Divergence Detection (Regular Bullish and Bearish)
When enabled, the indicator detects regular divergence using RSI pivots and price pivots:
Bearish divergence when price makes a higher high while RSI makes a lower high
Bullish divergence when price makes a lower low while RSI makes a higher low
The script uses RSI pivot confirmation with configurable left and right lookback settings, then pairs each new pivot with the most recent prior pivot of the same type.
🔸 6) 3D Divergence Bridge Visualization
Instead of drawing a plain divergence line only, the script creates a bridge style divergence visual in the RSI pane:
An outer edge line (upper for bearish, lower for bullish)
A center line connecting RSI pivot values
Vertical pillar lines at both pivot points
A compact label marking Bull Div or Bear Div
This keeps the divergence presentation consistent with the 3D ribbon concept.
🔸 7) Live RSI Value Label
A dynamic label is placed near the latest RSI point and updates on every bar. The label displays the current RSI value and inherits the same gradient driven color logic as the ribbon, improving readability and quick decision support.
🔸 8) Standard RSI Base Plot Included
The script also plots a classic RSI line in the background with reduced opacity. This is useful for users who want the familiar RSI trace while still benefiting from the 3D ribbon display.
🔸 9) Overbought / Oversold / Mid Reference Levels
The indicator includes standard horizontal reference levels:
70 for overbought
30 for oversold
50 for midpoint
These levels work alongside the ribbon and divergence visuals to preserve standard RSI interpretation workflows.
🔸 10) Background Regime Shading
The script fills the upper (70 to 100) and lower (0 to 30) zones with subtle color shading using the user selected overbought and oversold colors. This helps emphasize extreme zones without overwhelming the pane.
🔸 11) Object Based Internal Design
The script uses custom types for better structure and maintainability:
RSIPoint stores ribbon points (index, RSI, upper, lower)
PivotPoint stores divergence pivots (price and RSI context)
RSI3D stores the engine state, object arrays, labels, and last pivot references
This design supports cleaner extension for future features.
🔹 Calculations
1) RSI Core Calculation
The indicator uses the standard RSI calculation on close:
float rsiVal = ta.rsi(src, LEN)
A second standard RSI calculation is also plotted as a base line for reference:
rsiVal = ta.rsi(close, LEN)
plot(rsiVal, "RSI Base", color=color.new(color.gray, 50), linewidth=1)
2) 3D Ribbon Geometry (Upper and Lower Layers)
For each valid RSI value, the script builds a 3D envelope using the configured thickness:
float upperVal = rsiVal + this.thickness
float lowerVal = rsiVal - this.thickness
These three values define a single RSIPoint :
The center RSI value
The upper ribbon edge
The lower ribbon edge
The ribbon is then drawn by connecting consecutive RSIPoint objects.
3) RSIPoint History Management
The script stores recent ribbon points in an array. If the current bar already exists as the most recent point, it updates that point. Otherwise it appends a new one:
if lastPoint.index == bar_index
this.history.set(this.history.size() - 1, newPoint)
else
this.history.push(newPoint)
History is capped to avoid excessive memory growth:
if this.history.size() > 1000
this.history.shift()
4) Ribbon Segment Drawing Logic
When at least two points exist, the script draws or updates a single segment between the previous and current point:
Upper line between previous upper and current upper
Lower line between previous lower and current lower
Vertical line at current bar connecting upper and lower
Filled region between upper and lower lines
line l_up = line.new(p1.index, p1.upper, p2.index, p2.upper, ...)
line l_dn = line.new(p1.index, p1.lower, p2.index, p2.lower, ...)
line l_v = line.new(p2.index, p2.upper, p2.index, p2.lower, ...)
linefill lf = linefill.new(l_up, l_dn, color=colorFill)
If the bar is still active and no new index exists, the script updates the last segment instead of creating a new one.
5) Gradient Color Calculation for the 3D Ribbon
Ribbon color is derived from the current RSI value using a gradient between the oversold and overbought colors:
color c_curr = color.from_gradient(p2.value, 30, 70, COL_OS, COL_OB)
The script then derives related colors from this base for:
Upper line
Lower line
Fill
Vertical connector
This creates a coherent depth style while preserving the RSI level heatmap effect.
6) Live RSI Label Update
The current value label is updated on each draw cycle:
this.current_label.set_xy(p2.index + 1, p2.value)
this.current_label.set_text(str.tostring(p2.value, "#.0"))
this.current_label.set_textcolor(c_curr)
This keeps the label positioned next to the latest RSI point and colored according to current RSI regime.
7) RSI Pivot Detection for Divergence
The divergence engine uses RSI pivot highs and lows:
float ph_rsi_val = ta.pivothigh(rsiVal, DIV_LB, DIV_RB)
float pl_rsi_val = ta.pivotlow(rsiVal, DIV_LB, DIV_RB)
Pivot index is aligned to the true pivot bar by subtracting the right lookback:
int pivot_idx = bar_index - DIV_RB
This ensures divergence bridges are anchored to the actual pivot points, not the later confirmation bar.
8) Price and RSI Pivot Pair Construction
When an RSI pivot is confirmed, the script creates a PivotPoint using:
Pivot bar index
Price at pivot bar (high for pivot high, low for pivot low)
RSI pivot value
RSI upper and lower ribbon bounds at the pivot
Examples:
float ph_price = high
PivotPoint curr_ph = PivotPoint.new(pivot_idx, ph_price, ph_rsi_val, ph_upper, ph_lower)
float pl_price = low
PivotPoint curr_pl = PivotPoint.new(pivot_idx, pl_price, pl_rsi_val, pl_upper, pl_lower)
9) Bearish Divergence Condition
The script checks regular bearish divergence by comparing the current RSI pivot high to the last stored RSI pivot high:
if curr_ph.price > this.last_ph.price and curr_ph.rsi_val < this.last_ph.rsi_val
draw_bridge(this, this.last_ph, curr_ph, false)
Interpretation:
Price prints a higher high
RSI prints a lower high
This is a classic regular bearish divergence condition.
10) Bullish Divergence Condition
The script checks regular bullish divergence by comparing the current RSI pivot low to the last stored RSI pivot low:
if curr_pl.price < this.last_pl.price and curr_pl.rsi_val > this.last_pl.rsi_val
draw_bridge(this, this.last_pl, curr_pl, true)
Interpretation:
Price prints a lower low
RSI prints a higher low
This is a classic regular bullish divergence condition.
11) 3D Divergence Bridge Construction
When divergence is detected, the script draws a bridge style annotation in the RSI pane:
Outer edge line uses the RSI upper boundary for bearish divergence or RSI lower boundary for bullish divergence
Center line connects the two RSI pivot values
Vertical pillar lines connect outer edge to center at both pivots
A label is placed near the midpoint reading Bull Div or Bear Div
Key logic:
float y1 = is_bullish ? p1.rsi_lower : p1.rsi_upper
float y2 = is_bullish ? p2.rsi_lower : p2.rsi_upper
line.new(p1.index, y1, p2.index, y2, ...)
line.new(p1.index, y1, p1.index, p1.rsi_val, ...)
line.new(p2.index, y2, p2.index, p2.rsi_val, ...)
This gives divergence signals a depth themed appearance that matches the ribbon.
12) Object Cleanup and Performance Controls
To manage chart object limits, the script trims older ribbon objects when the stored ribbon segment count exceeds a threshold:
if this.lines_upper.size() > 480
line.delete(this.lines_upper.shift())
line.delete(this.lines_lower.shift())
line.delete(this.lines_vert.shift())
linefill.delete(this.fills.shift())
This helps maintain performance while preserving a large recent portion of the 3D ribbon.
13) Reference Levels and Background Zones
The script adds standard RSI reference lines:
hline(70, "OB Level", ...)
hline(30, "OS Level", ...)
hline(50, "Mid Level", ...)
It also shades the upper and lower extreme zones with subtle fills:
fill(obLine, plot(100, display=display.none), color=color.new(COL_OB, 95))
fill(osLine, plot(0, display=display.none), color=color.new(COL_OS, 95))
These layers provide familiar RSI context beneath the 3D visuals. Indicator

TTP Universal Divergence DetectorUNIVERSAL DIVERGENCE DETECTOR
═══════════════════════════════════════════════════════════════════════════════
OVERVIEW
The Universal Divergence Detector is a powerful and flexible indicator that identifies divergences between price action and ANY oscillator or indicator of your choice. Unlike traditional divergence indicators that only work with specific oscillators like RSI or MACD, this tool allows you to select any indicator on your chart as the source for divergence detection.
═══════════════════════════════════════════════════════════════════════════════
KEY FEATURES
UNIVERSAL COMPATIBILITY
→ Works with ANY indicator - RSI, MACD, Stochastic, Volume, custom indicators, or any other source
→ Flexible source selection - Choose your preferred indicator from a simple dropdown menu
→ Multi-timeframe capable - Use on any timeframe from 1-minute to monthly charts
COMPLETE DIVERGENCE DETECTION
The indicator detects all four types of divergences:
Regular Divergences (Potential Trend Reversals):
→ Regular Bullish: Price makes lower low, indicator makes higher low → Potential reversal UP
→ Regular Bearish: Price makes higher high, indicator makes lower high → Potential reversal DOWN
Hidden Divergences (Trend Continuation):
→ Hidden Bullish: Price makes higher low, indicator makes lower low → Continuation UP
→ Hidden Bearish: Price makes lower high, indicator makes higher high → Continuation DOWN
DUAL DISPLAY MODES
1. Divergences Only (Default)
→ Beautiful pattern lines connecting pivot points
→ Shows the complete divergence structure
→ WARNING: REPAINTS as new bars form - for analysis only, NOT for trading
2. Signals Only
→ Clean, simple B/S markers (Buy/Sell signals)
→ NON-REPAINTING - what you see is what you get
→ Appears when divergence is confirmed after pivot bars
→ Safe for trading and backtesting
3. Both
→ See the complete picture
→ Divergence lines show the historical pattern
→ Signal markers show exact entry points
BACKTESTING SUPPORT
→ Binary outputs (1/0) for each signal type
→ Non-repainting signals ensure reliable backtest results
→ Compatible with Pine Script strategies - reference the outputs in your own scripts
→ Six separate streams: Regular Bullish, Regular Bearish, Hidden Bullish, Hidden Bearish, Any Bullish, Any Bearish
COMPREHENSIVE ALERTS
→ Individual alerts for each divergence type
→ Combined alerts for any bullish/bearish signals
→ All alerts are NON-REPAINTING (signals only, not divergence patterns)
→ No false alerts from unconfirmed patterns
CUSTOMIZABLE VISUALS
→ Adjustable pivot sensitivity (left/right bars)
→ Customizable lookback range (min/max bars between pivots)
→ Color customization for each divergence type
→ Line width and label size controls
→ Toggle individual divergence types on/off
═══════════════════════════════════════════════════════════════════════════════
HOW TO USE
BASIC SETUP
1. Add the indicator to your chart
Click "Indicators" → Search "Universal Divergence Detector" → Add to chart
2. Select your indicator source
→ Open indicator settings
→ Under "Source Settings", click the "Indicator Source" dropdown
→ Choose ANY indicator already on your chart (e.g., RSI, MACD, Stochastic, etc.)
3. Configure pivot settings (optional)
→ Pivot Left Bars: Number of bars to the left of pivot (default: 5)
→ Pivot Right Bars: Number of bars to the right of pivot (default: 5)
→ Higher values = more reliable but slower signals
→ Signals appear AFTER right bars for confirmation
4. Choose your display mode
→ Divergences Only: Beautiful analysis view (repainting)
→ Signals Only: Clean trade signals (non-repainting)
→ Both: Complete picture
UNDERSTANDING THE DISPLAY
Divergence Lines (when enabled):
→ Solid lines = Regular divergences (potential reversals)
→ Dashed lines = Hidden divergences (trend continuation)
→ Labels: "RB" (Regular Bullish), "HB" (Hidden Bullish), etc.
Signal Markers (when enabled):
→ "B" = Buy signal (below bars)
→ "S" = Sell signal (above bars)
→ Colors:
• Green = Regular Bullish
• Red = Regular Bearish
• Blue = Hidden Bullish
• Orange = Hidden Bearish
TRADING STRATEGY TIPS
For Trend Reversals:
→ Enable Regular Divergences only
→ Use on higher timeframes (4H, Daily) for reliability
→ Wait for signal confirmation (B/S markers)
→ Combine with support/resistance levels
For Trend Continuation:
→ Enable Hidden Divergences only
→ Use in strong trending markets
→ Enter on pullbacks when hidden divergence appears
For Backtesting:
→ Enable "Backtesting Outputs" in settings
→ Use "Signals Only" display mode
→ Reference the binary outputs in your Pine Script strategy
→ Available outputs:
• BT: Regular Bullish Signal
• BT: Regular Bearish Signal
• BT: Hidden Bullish Signal
• BT: Hidden Bearish Signal
• BT: Any Bullish Signal
• BT: Any Bearish Signal
═══════════════════════════════════════════════════════════════════════════════
SETTINGS GUIDE
SOURCE SETTINGS
→ Indicator Source: Select which indicator to use for divergence detection
PIVOT SETTINGS
→ Pivot Left Bars (1-∞): Bars to the left of pivot point (default: 5)
→ Pivot Right Bars (1-∞): Bars to the right of pivot point (default: 5)
DIVERGENCE TYPES
Toggle each type individually:
→ Regular Bullish
→ Regular Bearish
→ Hidden Bullish
→ Hidden Bearish
DISPLAY SETTINGS
→ Display Mode: Divergences Only / Signals Only / Both
DETECTION SETTINGS
→ Max Lookback Bars (10-500): Maximum bars to search for divergence patterns (default: 60)
→ Min Lookback Bars (1-100): Minimum bars between pivots (default: 5)
BACKTESTING
→ Enable Backtesting Outputs: Turns on binary (1/0) plot streams for strategy development
VISUAL SETTINGS
→ Line Width (1-5): Thickness of divergence lines
→ Label Size: tiny / small / normal / large
COLORS
Customize colors for each divergence type:
→ Regular Bullish (default: Green)
→ Regular Bearish (default: Red)
→ Hidden Bullish (default: Blue)
→ Hidden Bearish (default: Orange)
═══════════════════════════════════════════════════════════════════════════════
IMPORTANT CONSIDERATIONS
REPAINTING VS NON-REPAINTING
DIVERGENCE LINES (Repainting):
→ Show beautiful historical patterns
→ Update as new bars form
→ Great for learning and analysis
→ NOT suitable for trading decisions
→ NOT suitable for backtesting
SIGNALS (Non-Repainting):
→ Appear on current bar when confirmed
→ What you see is what you get
→ Safe for trading
→ Reliable for backtesting
→ Appear AFTER pivot right bars (e.g., 5 bars delay with default settings)
This is why the indicator has two display modes - so you can see the pattern AND know exactly when you could have entered!
SIGNAL TIMING
With default settings (Pivot Right Bars = 5):
1. Price forms a pivot low at bar 100
2. Bars 101, 102, 103, 104, 105 form (5 bars of confirmation)
3. At bar 105, if divergence conditions are met, signal triggers
4. You enter your trade on bar 105 (the current bar)
The signal appears exactly when the divergence is mathematically confirmed - no earlier, no later.
BEST PRACTICES
DO:
→ Use signals for actual trading decisions
→ Combine with other analysis (support/resistance, trend lines)
→ Test different pivot settings for your timeframe
→ Use divergence lines for learning and pattern recognition
→ Enable backtesting outputs when developing strategies
DO NOT:
→ Trade based on divergence lines (they repaint)
→ Use very small pivot values (increases false signals)
→ Ignore the broader market context
→ Rely solely on divergences without confirmation
═══════════════════════════════════════════════════════════════════════════════
EXAMPLES
Example 1: RSI Divergence on Bitcoin
1. Add RSI indicator to your BTC chart
2. Add Universal Divergence Detector
3. Set source to RSI
4. Switch to "Both" display mode
5. Watch for regular bullish divergences at support levels
Example 2: MACD Divergence on Stocks
1. Add MACD indicator to your stock chart
2. Add Universal Divergence Detector
3. Set source to MACD (usually the MACD line, not signal line)
4. Enable only Regular divergences
5. Use on daily timeframe for swing trades
Example 3: Custom Indicator Divergence
1. Add your custom indicator (e.g., volume-weighted RSI)
2. Add Universal Divergence Detector
3. Set source to your custom indicator
4. Now you have divergence detection on your unique indicator!
═══════════════════════════════════════════════════════════════════════════════
TECHNICAL DETAILS
→ Pine Script Version: v6
→ Overlay: Yes (plots on price chart)
→ Max Labels: 500
→ Max Lines: 500
→ Calculation Method: Pivot-based using ta.pivothigh() and ta.pivotlow()
PERFORMANCE NOTES
→ Memory Efficient: Arrays limited to 100 pivots maximum
→ Calculation Speed: Optimized loops with configurable max lookback
→ Visual Performance: Toggle off unused divergence types for cleaner charts
═══════════════════════════════════════════════════════════════════════════════
TROUBLESHOOTING
No divergences showing?
→ Check that your selected source is actually plotted on the chart
→ Reduce Min Lookback Bars or increase Max Lookback Bars
→ Decrease Pivot Left/Right Bars for more sensitivity
Too many signals?
→ Increase Pivot Left/Right Bars for more selective detection
→ Increase Min Lookback Bars
→ Disable divergence types you don't need
Signals appear too late?
→ This is by design - signals need confirmation
→ Reduce Pivot Right Bars (but this increases false signals)
→ Remember: reliable signals require confirmation time
═══════════════════════════════════════════════════════════════════════════════
EDUCATIONAL RESOURCES
What is Divergence?
Divergence occurs when price action and an indicator move in opposite directions, suggesting potential momentum shifts.
Types of Divergences:
Regular Divergences suggest trend reversals:
→ Price continues in one direction
→ Indicator shows weakening momentum
→ Often occurs at major support/resistance
Hidden Divergences suggest trend continuation:
→ Price pulls back against the trend
→ Indicator shows momentum still strong
→ Often occurs during healthy pullbacks in trends
LEARNING MODE
To learn divergence patterns:
1. Set Display Mode to "Both"
2. Study historical charts
3. Notice how divergence lines show the pattern
4. See how signals appear after confirmation
5. Practice identifying divergences manually
6. Then switch to "Signals Only" for trading
═══════════════════════════════════════════════════════════════════════════════
FUTURE ENHANCEMENT IDEAS
Users can modify this open-source script to add:
→ Divergence strength scoring
→ Confluence with other indicators
→ Auto entry/exit strategy development
→ Multi-timeframe divergence detection
→ Volume-weighted divergence signals
═══════════════════════════════════════════════════════════════════════════════
Happy Trading!
Remember: The best indicator is the one you understand. Take time to learn how divergences work before incorporating them into your trading strategy.
═══════════════════════════════════════════════════════════════════════════════
Indicator

CVD Divergence & Absorption [UAlgo]CVD Divergence & Absorption is a dual context indicator that combines a cumulative volume delta (CVD) oscillator with price pivot structure to detect three important signal classes: Regular Divergence, Hidden Divergence, and Absorption. The script is designed to help traders compare price movement against directional volume participation and identify moments where price and CVD disagree, or where price stalls at similar levels while CVD continues to expand or contract.
The indicator runs in a separate pane ( overlay=false ) and plots a continuous CVD line, while signal labels and price side connecting lines are projected onto the main chart using force_overlay=true . This gives a clean workflow where you can monitor the CVD series in its own panel and still see exact divergence locations directly on price.
A key strength of this script is its lower timeframe volume decomposition. Instead of assigning the full chart bar volume to a single direction, it samples lower timeframe candles through request.security_lower_tf() , classifies each sub candle as up volume or down volume based on its close versus open, and aggregates the result into a bar level delta. That delta is then accumulated into the running CVD value. This approach is practical, efficient, and more granular than a simple chart timeframe approximation.
The script also includes quality controls for signal validation:
Pivot based comparisons for both price and CVD
Minimum and maximum bar distance filters between pivot comparisons
Equal price tolerance for absorption detection
A line of sight filter that rejects visually obstructed divergences where intervening candles violate the connecting path
The result is a professional divergence framework focused on cleaner, more interpretable signals rather than high frequency marking of every pivot mismatch.
Educational tool only. Not financial advice.
🔹 Features
🔸 1) Lower Timeframe CVD Construction (LTF Volume Decomposition)
The script builds CVD using lower timeframe candles selected by the user through the Lower Timeframe (LTF) input. For each chart bar, it retrieves arrays of lower timeframe open, close, and volume values and computes a signed delta:
Up LTF candle (close > open) adds volume
Down LTF candle (close < open) subtracts volume
Neutral LTF candle contributes zero
This produces a more refined bar delta than a single bar directional assumption and makes the CVD line more responsive to intrabar rotation.
🔸 2) Pivot Based Signal Engine for Price and CVD
Signal generation is anchored to confirmed price pivots using user defined left and right pivot bars. A signal candidate is considered only when:
A price pivot high/low is confirmed by ta.pivothigh or ta.pivotlow
The CVD value at that pivot location also behaves like a local high/low (simple local extremum check)
This means the script does not compare arbitrary points. It compares structurally meaningful swing locations.
🔸 3) Regular Divergence Detection (Bullish and Bearish)
The indicator supports classic regular divergence logic:
Bullish Regular Divergence: price makes a lower low while CVD makes a higher low
Bearish Regular Divergence: price makes a higher high while CVD makes a lower high
These signals can indicate weakening trend continuation pressure and potential reversal behavior, depending on context.
🔸 4) Hidden Divergence Detection (Bullish and Bearish)
The script also detects hidden divergence, which many traders use as continuation style confirmation:
Bullish Hidden Divergence: price makes a higher low while CVD makes a lower low
Bearish Hidden Divergence: price makes a lower high while CVD makes a higher high
Hidden divergence is optional and can be toggled independently from regular divergence.
🔸 5) Absorption Detection with Equal Price Tolerance
Absorption logic is included to capture situations where price prints near equal pivots, but CVD continues moving in a direction that suggests aggressive participation is being absorbed at the level:
Bearish Absorption (at highs): price is approximately equal high, but CVD is higher
Bullish Absorption (at lows): price is approximately equal low, but CVD is lower
The Equal Price Tolerance % input allows the script to treat two pivots as "equal" within a configurable percentage band. This makes absorption detection adaptable across instruments with different volatility profiles.
🔸 6) Minimum / Maximum Pivot Distance Filters
To avoid weak or overly stale comparisons, the script enforces:
A minimum number of bars between pivots
A maximum lookback distance for valid pivot pairing
This helps reduce noisy signals from pivots that are too close together and prevents pairing pivots that are too far apart to be contextually useful.
🔸 7) Line of Sight Validation (Signal Quality Filter)
Before accepting a pivot comparison, the script checks whether the straight line connecting the two price pivots is "clear" from intervening candle violations:
For bearish (high based) comparisons, intervening highs must not cross above the connecting line
For bullish (low based) comparisons, intervening lows must not cross below the connecting line
This is a strong visual integrity filter. It avoids many cluttered or ambiguous divergence lines that would look invalid once drawn on the chart.
🔸 8) Dual Visualization on Price and CVD
When a signal is detected, the script draws:
A label on price ("Reg", "Hid", or "Abs")
A line connecting the two relevant price pivots on the main chart
A line connecting the corresponding CVD pivot values in the CVD pane
Line styles are used to distinguish signal types:
Solid for Regular Divergence
Dashed for Hidden Divergence
Dotted for Absorption
This synchronized plotting makes it easy to verify the signal logic visually.
🔸 9) Conflict Handling for Cleaner Labels
Absorption labels are intentionally suppressed when a Hidden Divergence signal is already active on the same side in the same event block:
bullAbs and not bullHidDiv
bearAbs and not bearHidDiv
This prevents duplicate labels on the same pivot and improves chart readability.
🔸 10) Lightweight Pivot Memory Management
The script stores historical pivot comparison points in separate arrays for highs and lows and caps them using a helper method ( maxSize = 15 ). This keeps the logic efficient while preserving enough recent history for valid comparisons.
🔹 Calculations
1) Lower Timeframe Delta Aggregation
The script retrieves lower timeframe OHLCV arrays and computes bar delta by summing signed volume from each LTF candle:
array ltf_open = request.security_lower_tf(syminfo.tickerid, i_ltf, open)
array ltf_close = request.security_lower_tf(syminfo.tickerid, i_ltf, close)
array ltf_volume = request.security_lower_tf(syminfo.tickerid, i_ltf, volume)
if ltf_c > ltf_o
totalDelta += ltf_v
else if ltf_c < ltf_o
totalDelta -= ltf_v
Interpretation:
The script uses candle direction as a proxy for buying/selling pressure inside each chart bar.
This is an estimated delta model based on candle body direction, not true bid/ask tape delta.
2) CVD Accumulation
Bar delta is added into a running cumulative value stored inside a custom tracker object:
method update_cvd(CVD_Tracker this, float delta) =>
this.currentCVD += delta
this.currentCVD
The tracker persists across bars using:
var CVD_Tracker tracker = CVD_Tracker.new(0.0, array.new(), array.new())
This design keeps both the CVD value and pivot histories in one structured container.
3) Price Pivot Detection
Price pivots are confirmed using standard left/right pivot logic:
float ph = ta.pivothigh(high, i_left, i_right)
float pl = ta.pivotlow(low, i_left, i_right)
Because pivot confirmation occurs after i_right bars, signal labels and lines are placed at:
bar_index - i_right
This aligns the plotted signal with the actual pivot bar, not the confirmation bar.
4) CVD Pivot Confirmation at the Same Pivot Location
The script requires CVD to form a local extremum at the price pivot location using a simple 3-point comparison around currentCVD :
bool cvdIsPh = currentCVD > currentCVD and currentCVD > currentCVD
bool cvdIsPl = currentCVD < currentCVD and currentCVD < currentCVD
Then:
bool isPh = not na(ph) and cvdIsPh
bool isPl = not na(pl) and cvdIsPl
This ensures price and CVD are compared on synchronized pivot events rather than unrelated timestamps.
5) Pivot Pair Selection with Distance Constraints
When a new pivot is confirmed, the script scans prior pivots of the same type (highs with highs, lows with lows) and applies:
i_min_bars as the minimum spacing
i_max_bars as the maximum valid distance
if barsBetween < minBars
continue
if barsBetween > maxBars
break
This keeps comparisons within a user defined structural window.
6) Line of Sight Filter (Price Geometry Validation)
Before checking divergence conditions, the script verifies that the connecting price line is not invalidated by intervening candles.
For highs:
if barsBack >= 0 and high >= lineY
clear := false
For lows:
if barsBack >= 0 and low <= lineY
clear := false
Interpretation:
Bearish comparisons require a clean descending/ascending line between highs without intermediate highs breaking above it.
Bullish comparisons require a clean line between lows without intermediate lows breaking below it.
This is one of the script’s strongest anti-noise mechanisms.
7) Equal Price Tolerance for Absorption
The script calculates percentage difference between pivot prices and treats them as equal if the difference is within the tolerance:
float priceDiffPct = math.abs(newPivot.priceVal - histPivot.priceVal) / histPivot.priceVal * 100
bool isEqual = priceDiffPct <= eqTol
This enables absorption logic to work with approximate equal highs/lows instead of requiring perfect price matches, which are rare in live markets.
8) Bearish Signal Logic (Regular, Hidden, Absorption)
For pivot highs, the script compares a new pivot high against a historical pivot high after passing distance and line of sight checks.
Bearish Regular Divergence
newPivot.priceVal > histPivot.priceVal and not isEqual and newPivot.cvdVal < histPivot.cvdVal
Meaning:
Price makes a higher high
CVD makes a lower high
Bearish Hidden Divergence
newPivot.priceVal < histPivot.priceVal and not isEqual and newPivot.cvdVal > histPivot.cvdVal
Meaning:
Price makes a lower high
CVD makes a higher high
Bearish Absorption
isEqual and newPivot.cvdVal > histPivot.cvdVal
Meaning:
Price prints an approximately equal high
CVD pushes higher, suggesting buying effort is absorbed near the same price zone
9) Bullish Signal Logic (Regular, Hidden, Absorption)
For pivot lows, the script compares a new pivot low against a historical pivot low after passing distance and line of sight checks.
Bullish Regular Divergence
newPivot.priceVal < histPivot.priceVal and not isEqual and newPivot.cvdVal > histPivot.cvdVal
Meaning:
Price makes a lower low
CVD makes a higher low
Bullish Hidden Divergence
newPivot.priceVal > histPivot.priceVal and not isEqual and newPivot.cvdVal < histPivot.cvdVal
Meaning:
Price makes a higher low
CVD makes a lower low
Bullish Absorption
isEqual and newPivot.cvdVal < histPivot.cvdVal
Meaning:
Price prints an approximately equal low
CVD pushes lower, suggesting selling effort is absorbed near the same price zone
10) Signal Plotting and Visual Encoding
When a condition is confirmed, the script plots both price side and CVD side lines between the historical pivot and the new pivot, plus a compact label at the new pivot location.
Examples:
label.new(bar_index - i_right, low , text="Reg", ...)
line.new(bullLastPivot.loc, bullLastPivot.priceVal, bullNewPivot.loc, bullNewPivot.priceVal, ..., force_overlay=true)
line.new(bullLastPivot.loc, bullLastPivot.cvdVal, bullNewPivot.loc, bullNewPivot.cvdVal, ..., force_overlay=false)
Style mapping:
line.style_solid for Regular Divergence
line.style_dashed for Hidden Divergence
line.style_dotted for Absorption
11) Pivot History Storage and Capacity Control
Each confirmed pivot is stored in a side specific array (highs or lows) using a helper method:
method add_pivot(array this, Pivot p, int maxSize = 15) =>
this.push(p)
if this.size() > maxSize
this.shift()
This preserves recent structural history for future comparisons while keeping memory usage controlled. Indicator

Flow EngineFlow Engine
Most indicators tell you which direction price is moving. Flow Engine tells you whether to trust it . It does this by combining momentum, volume, trend, and a higher timeframe check all into one pane, plus it draws divergence signals directly on your price chart so you never have to look away.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHAT'S ON THE SCREEN
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Histogram (the bars)
This is the main thing. The height of each bar shows how strong the momentum is. The color tells you the direction — cyan for up, red for down.
The part that makes this different is the opacity . If a bar is bright and vivid, it means big volume is behind that move. If a bar looks faded or ghosted, the move happened on low volume and probably won't last. You can see this instantly without checking a separate volume pane.
Tall vivid cyan bar = strong upward move with real volume behind it
Tall faded cyan bar = price went up but nobody really showed up
Same logic applies on the red side
The OB/OS Line
This line tells you when things are getting stretched too far in one direction.
When it goes above +70 — the move is getting overdone on the upside.
When it drops below -70 — the selloff is getting overdone.
In between — cyan means leaning bullish, red means leaning bearish
The Trend Line
A slow moving line that tells you what the overall structure looks like on your current timeframe.
Lime green above zero — uptrend
Soft red below zero — downtrend
Think of it as the background context. When this line is green, you want to be looking for longs. When it's red, be careful going long or look for shorts instead.
The Background Tint (HTF Bias)
A very subtle color behind everything that comes from a higher timeframe — by default the Daily chart.
Cyan tint — the daily trend is bullish
Red tint — the daily trend is bearish
No tint — daily is mixed, no clear direction
This is the big picture check. If you are trading a 15 minute chart and the background is red, you know you are going against the daily trend. That doesn't mean you can't trade, but you should be more careful.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DIVERGENCE SIGNALS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Divergence is when price and momentum stop agreeing with each other. It usually means the current move is running out of steam.
Bearish divergence — price made a higher high but the histogram made a lower high. The rally is weakening. Orange triangle appears above the candle on your price chart.
Bullish divergence — price made a lower low but the histogram made a higher low. The selloff is weakening. Green triangle appears below the candle on your price chart.
You also get a dashed line drawn on the Flow Engine pane connecting the two points so you can see exactly where the divergence happened.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SETTINGS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Momentum Length (14) — how many bars the momentum calculation looks back. Lower number reacts quicker but gives more false signals. Higher number is slower but cleaner.
Volume MA Length (20) — the average used to judge whether current volume is high or low. Leave this at default unless you have a reason to change it.
Overbought Level (70) — where the OB/OS line turns orange. Lower this if you want earlier warnings.
Oversold Level (-70) — where the OB/OS line turns green. Change this together with the overbought level.
Trend Length (50) — how slow the trend line moves. Higher number = smoother line.
Pivot Lookback Left & Right (5) — controls how strict the divergence detection is. Raise both to 8 or 10 if you are getting too many signals. Lower to 3 if you want more.
HTF Timeframe (D) — the higher timeframe for the background tint. Set this one step above whatever chart you are on. D = Daily, W = Weekly, 240 = 4 Hour.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW TO USE IT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Every time you look at the indicator, go through it top to bottom:
Check the background tint — what is the daily (or higher TF) saying?
Check the trend line — is the current chart agreeing with that?
Check the OB/OS line — are we stretched? If yes, don't chase.
Check the histogram — is momentum vivid (real) or faded (weak)?
The best setup looks like this:
Background is cyan + trend line above zero + OB/OS line near oversold + bullish divergence triangle on the chart + histogram bars turning bright cyan
When all of that lines up, the move has multiple things confirming it at the same time. That's when you pay attention.
A quick tip on the faded bars: Don't get excited about a tall bar if it's faded. Price can move fast on thin volume and snap right back. The vivid bars are the ones that tend to follow through.
Which timeframe to set HTF to:
Trading 1m or 5m → set HTF to 1H or 4H
Trading 15m or 1H → keep HTF on Daily
Trading 4H or Daily → set HTF to Weekly
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
GOOD TO KNOW
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Does not repaint — signals are based on confirmed bars only
Divergence signals show up a few bars after the actual pivot
Looks best on a dark theme
Indicator

Indicator

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. Indicator

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.
Indicator

Indicator

Indicator

Market Force Oscillator Elite ProMarket Force Oscillator Elite Pro is a single-pane oscillator that combines acceleration, volume-weighted force, trend alignment, divergence logic, and multi-method cycle diagnostics.
How components work together:
- Force engine estimates buy/sell pressure from candle position, relative volume weighting, and optional momentum factor.
- Oscillator core combines acceleration with force and normalizes using robust scale logic (stdev with MAD fallback when stdev is unstable).
- Dynamic levels compute adaptive OB/OS using ATR percent with timeframe-aware auto calibration and a soft-cap transform.
- Trend filter compares LTF and HTF EMA direction before allowing directional signals.
- Signal quality gate combines oscillator magnitude, relative volume, and optional alignment weighting.
- Divergence module uses confirmed pivots with one-shot/cooldown modes.
- Cycle module computes Original Ehlers, Zero-Crossing, Peak-to-Peak, Autocorrelation, and Composite estimates.
What is new/original in this version (from current code):
- Multi-method cycle detector with Composite mode.
- Timeframe-aware ATR auto calibration for dynamic OB/OS behavior.
- ATR soft-cap compression to avoid overly wide bands on higher timeframes.
- Robust oscillator normalization with MAD fallback when stdev becomes outlier-like.
- Oscillator-pane marker anchoring (`location.absolute`) to prevent autoscale distortion from price-anchored shapes.
How to Use quickstart
1. Add the script to chart and start with `Preset = Balanced`.
2. Set `Cycle Detector Mode = Composite` for combined cycle diagnostics.
3. Enable `Show Detected Cycle (data window)` to inspect cycle outputs.
4. Enable advanced settings only if you need to tune quality gates, trend filter, and cooldowns.
5. Configure alerts from the 5 built-in alert conditions after threshold tuning.
Indicator

Precision Pivot Confluence Engine [JOAT]Precision Pivot Confluence Engine
Introduction
The Precision Pivot Confluence Engine is an open-source technical indicator that combines Central Pivot Range (CPR) analysis with Smart Money Concepts (SMC), multi-oscillator divergence detection, and institutional order flow patterns. This mashup integrates multiple proven methodologies into a unified confluence system designed to identify high-probability trading zones where institutional and retail liquidity intersect.
The indicator is built for traders who understand that no single signal provides consistent edge, but multiple confirming factors working together can significantly improve trade selection. By synthesizing CPR levels, Fair Value Gaps, Order Blocks, liquidity sweeps, and divergence patterns, this tool helps identify structural market inflection points.
Chart showing CPR levels, FVG zones, Order Blocks, and divergence signals on 4H timeframe
Why This Mashup Exists
This indicator combines five distinct analytical frameworks that complement each other:
CPR Analysis: Identifies key pivot levels where institutional algorithms and retail traders make decisions
Smart Money Concepts: Tracks Fair Value Gaps, Order Blocks, and Breaker Blocks showing institutional positioning
Divergence Detection: Uses RSI, MACD, and Stochastic RSI to identify momentum exhaustion
Liquidity Analysis: Detects liquidity sweeps where stop hunts occur before reversals
Volume Confirmation: Validates moves with volume analysis and delta calculations
Each component addresses a different aspect of market structure. CPR provides static reference levels, SMC reveals dynamic institutional behavior, divergences show momentum shifts, liquidity sweeps identify stop hunts, and volume confirms genuine moves versus noise. Together, they create a multi-dimensional view of market conditions.
Core Components Explained
1. Enhanced CPR System
The Central Pivot Range system calculates Daily and Weekly pivot levels using the formula:
Pivot = (High + Low + Close) / 3
BC (Bottom Central) = (High + Low) / 2
TC (Top Central) = (Pivot - BC) + Pivot
The indicator analyzes CPR width to determine market regime:
Narrow CPR (width < 0.5%): Indicates compression and potential breakout conditions
Wide CPR (width > 1.5%): Suggests ranging market with less directional conviction
Price position relative to CPR: Above both Daily and Weekly pivots = bullish structure, below = bearish structure
CPR levels act as magnetic zones where price tends to react. The indicator tracks distance from pivots to identify overextension and mean reversion opportunities.
2. Smart Money Concepts Integration
Fair Value Gaps (FVG):
Bullish FVG occurs when current low > high from 2 bars ago, leaving an unfilled gap
Bearish FVG occurs when current high < low from 2 bars ago
The indicator calculates FVG size as percentage of price and filters for significant gaps (> 0.3%) to avoid noise. FVGs represent inefficient price delivery where institutions moved price quickly, often returning to fill these gaps later.
Order Blocks (OB):
Bullish OB: Two consecutive bearish candles followed by strong bullish candle with high volume
Bearish OB: Two consecutive bullish candles followed by strong bearish candle with high volume
Order Blocks mark the last opposite-direction move before a strong impulse, indicating where institutions accumulated or distributed positions.
Breaker Blocks:
Failed Order Blocks that get violated become Breaker Blocks, signaling potential trend reversal. The indicator tracks the last bullish and bearish OB levels and alerts when price breaks through them.
Liquidity Sweeps:
The indicator identifies when price briefly exceeds recent highs/lows (20-bar lookback) but closes back inside the range. These "stop hunts" often precede reversals as institutions trigger retail stops before moving price in the intended direction.
Example showing FVG zones, Order Blocks, and liquidity sweep markers
3. Multi-Oscillator Divergence System
The indicator simultaneously tracks divergences across three oscillators:
RSI Divergence:
Bullish: Price makes lower low, RSI makes higher low (momentum improving despite price weakness)
Bearish: Price makes higher high, RSI makes lower high (momentum deteriorating despite price strength)
MACD Divergence:
Tracks histogram divergences using the same pivot-based logic
Stochastic RSI Divergence:
More sensitive than RSI, catches early momentum shifts
The indicator uses a 5-bar pivot lookback to identify swing highs/lows and compares current pivots with previous pivots to detect divergences. When multiple oscillators show divergence simultaneously, it signals strong momentum exhaustion.
4. Volume Analysis Engine
Volume MA Comparison: Identifies high volume (> 1.5x MA) and climax volume (> 3x MA)
Volume Delta: Cumulative difference between buying volume (green candles) and selling volume (red candles)
Delta Trend: Compares current delta to 20-period MA to identify institutional accumulation or distribution
Volume Confirmation: Validates bullish moves with high volume + rising delta, bearish moves with high volume + falling delta
5. Confluence Scoring System
The indicator calculates a real-time confluence score (0-100) by weighting each component:
Confluence Score Components:
- CPR Position: Up to 15 points (bullish above pivots, bearish below)
- SMC Signals: Up to 10 points (FVG + OB + Breaker + Liquidity Sweeps)
- Divergence: Up to 10 points (single oscillator = 5, multiple = 10)
- Volume: Up to 10 points (confirmed volume = 7, climax = additional 3)
- Trend Alignment: Up to 5 points (price vs key MAs)
Scores above 70 indicate strong confluence for potential trades. The dashboard displays individual component scores for transparency.
Visual Elements
CPR Lines: Daily Pivot (yellow), TC/BC (yellow transparent), Weekly Pivot (yellow circles)
FVG Boxes: Green boxes for bullish FVGs, red boxes for bearish FVGs
Order Block Boxes: Solid green/red boxes marking institutional zones
Breaker Block Labels: "BB" markers when Order Blocks fail
Liquidity Sweep Labels: "LIQ" and "STRONG LIQ" positioned at sweep tips
Divergence Labels: "D" markers at divergence pivot points
Dashboard: Top-right table showing confluence score and component breakdown
How Components Work Together
The mashup creates a layered analysis approach:
Layer 1 - Structure: CPR levels define key zones where reactions are likely
Layer 2 - Institutional Behavior: SMC concepts show where smart money is positioned
Layer 3 - Momentum: Divergences indicate when current trend is losing steam
Layer 4 - Confirmation: Volume validates whether moves are genuine or false
Layer 5 - Synthesis: Confluence score combines all factors into actionable signal
Example scenario: Price approaches Daily Pivot (Layer 1) where a bullish Order Block exists (Layer 2), RSI shows bullish divergence (Layer 3), and volume delta is rising (Layer 4). The confluence score jumps to 85 (Layer 5), signaling high-probability long setup.
Input Parameters
CPR Settings:
Show Daily CPR: Toggle daily pivot levels (default: enabled)
Show Weekly CPR: Toggle weekly pivot levels (default: enabled)
CPR Width Threshold: Defines narrow vs wide CPR (default: 0.5% / 1.5%)
Smart Money Concepts:
Show FVG: Display Fair Value Gap boxes (default: enabled)
Show Order Blocks: Display Order Block boxes (default: enabled)
Show Breaker Blocks: Display Breaker Block labels (default: enabled)
Show Liquidity Sweeps: Display liquidity sweep markers (default: enabled)
FVG Min Size: Minimum gap size to display (default: 0.3%)
Lookback Bars: Bars to scan for liquidity levels (default: 20)
Divergence Detection:
Show Divergences: Toggle divergence labels (default: enabled)
RSI Length: Period for RSI calculation (default: 14)
Pivot Lookback: Bars for pivot detection (default: 5)
Volume Analysis:
Show Volume Analysis: Toggle volume indicators (default: enabled)
Volume MA Length: Period for volume moving average (default: 20)
High Volume Multiplier: Threshold for high volume (default: 1.5x)
Climax Volume Multiplier: Threshold for climax volume (default: 3.0x)
Display Options:
Show Dashboard: Toggle confluence score table (default: enabled)
Max FVG Boxes: Limit displayed FVG boxes (default: 20)
Max OB Boxes: Limit displayed Order Block boxes (default: 15)
Label Spacing: Minimum bars between labels to prevent overlap (default: 10-15)
How to Use This Indicator
Step 1: Identify Market Structure
Check CPR position and width. Narrow CPR suggests breakout potential, wide CPR suggests range-bound conditions.
Step 2: Look for SMC Confluence
Identify FVGs, Order Blocks, and recent liquidity sweeps. These zones often provide high-probability entry areas.
Step 3: Check for Divergences
Look for divergence labels at swing points. Multiple oscillator divergences increase signal strength.
Step 4: Confirm with Volume
Ensure volume supports the move. Rising delta + high volume confirms bullish moves, falling delta + high volume confirms bearish moves.
Step 5: Review Confluence Score
Check the dashboard. Scores above 70 indicate strong confluence. Individual component scores show which factors are contributing.
Step 6: Wait for Price Action Confirmation
The indicator identifies zones and conditions, but wait for price action confirmation (candlestick patterns, breakouts, etc.) before entering trades.
Best Practices
Use on 15-minute to 4-hour timeframes for optimal signal quality
Combine with proper risk management - indicator shows zones, not exact entries
Pay attention to confluence score - higher scores generally indicate better setups
Watch for FVG fills and Order Block retests as entry triggers
Liquidity sweeps followed by reversal often provide excellent risk:reward entries
Divergences work best when combined with SMC zones or CPR levels
Volume confirmation is critical - avoid low-volume signals
Indicator Limitations
Does not provide exact entry/exit signals - requires trader interpretation
Can generate false signals in choppy, low-volume conditions
Multiple visual elements may clutter chart - adjust display settings as needed
Divergences can persist longer than expected - price can continue trending despite divergence
FVGs and Order Blocks don't always get retested - not every zone provides entry opportunity
Confluence score is a guide, not a guarantee - high scores can still result in losing trades
Requires understanding of SMC concepts and CPR analysis for effective use
Performance varies across different markets and timeframes
Technical Implementation
Built with Pine Script v6 using:
Custom CPR calculations with width analysis
Box and label management with anti-overlap logic
Persistent variables for tracking Order Blocks and Breaker Blocks
Pivot-based divergence detection across multiple oscillators
Volume delta calculation with cumulative tracking
Real-time confluence scoring system
Dynamic dashboard with component breakdown
The code is fully open-source and can be modified to suit individual trading styles and preferences.
Originality Statement
This indicator is original in its integration approach. While individual components (CPR, FVG, Order Blocks, RSI divergence, volume analysis) are established concepts, this mashup is justified because:
It synthesizes five distinct methodologies that address different market aspects
The confluence scoring system provides quantitative measurement of setup quality
Anti-overlap logic and timeframe-adaptive filtering reduce visual clutter
Component integration creates layered analysis not available in individual indicators
The combination helps identify zones where multiple institutional and technical factors align
Each component contributes unique information: CPR provides static structure, SMC reveals dynamic institutional behavior, divergences show momentum shifts, liquidity analysis identifies stop hunts, and volume confirms genuine moves. The mashup's value lies in presenting these complementary perspectives simultaneously with a unified scoring system.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss and is not suitable for all investors.
Technical indicators are tools for analysis, not crystal balls. Past performance and backtested results do not guarantee future performance. Market conditions change, and strategies that worked historically may not work in the future.
The confluence score is a mathematical calculation based on current market data, not a prediction of future price movement. High confluence scores do not guarantee profitable trades. Users must conduct their own analysis and risk assessment before making trading decisions.
Always use proper risk management, including stop losses and position sizing appropriate for your account size and risk tolerance. Never risk more than you can afford to lose. Consider consulting with a qualified financial advisor before making investment decisions.
The author is not responsible for any losses incurred from using this indicator. Users assume full responsibility for all trading decisions made using this tool.
-Made with passion by officialjackofalltrades Indicator

Relative Strength Regime Meter (SPY/QQQ/Peer Auto)RS Dash v2 is a relative strength (RS) dashboard designed to quickly answer one question:
Is this asset leading or lagging vs (1) the market, (2) Nasdaq/growth, and (3) its peer group?
What it measures
For the current chart symbol, it calculates RS ratios:
RS vs SPY (market baseline)
RS vs QQQ (Nasdaq / growth baseline)
RS vs PEER ETF (sector/industry baseline)
RS ratio is simply:
RS = Symbol Close / Benchmark Close
Then it compares each RS ratio to its moving average (MA):
✅ if RS > RS_MA
Optional stricter rule: ✅ only if RS > RS_MA and RS_MA is rising
Peer ETF: Manual or Auto
You can pick the peer ETF in two ways:
MANUAL mode
Choose from labeled options like:
XLK – TECH, XLE – ENERGY, SMH – SEMIS, etc.
AUTO mode (default)
The script selects the peer ETF whose returns have the highest correlation to the symbol over a lookback window, with guardrails:
Min correlation threshold: if correlation is too low, it falls back to your chosen fallback peer.
Sticky switching: it only changes peer when the new best peer is better by a set margin (reduces “flicker”).
The table shows what AUTO picked, and it also prints the correlation as a trust meter.
Dashboard + Score
A table (bottom-left) shows:
SPY ✅/❌
QQQ ✅/❌
PEER ✅/❌ (with chosen peer name)
Total score 0–3
Interpretation:
3/3 = strong leadership (outperforming market + Nasdaq + peers)
2/3 = mixed leadership
0–1/3 = weak / lagging regime
Plot modes (solves scaling issues)
Because raw RS ratios can be on very different numeric scales, there are three plot modes:
Signal (% vs RS MA) (recommended)
Plots each RS as % above/below its RS MA where 0 = neutral.
Indexed (Base 100)
Normalizes each RS to start at 100 so you can compare “performance curves.”
Raw (single)
Shows only one RS ratio at a time (SPY / QQQ / PEER) for inspection.
Leadership line (Regime meter)
The Leadership line is a step line that visualizes the 0–3 score as a regime meter (it only has 4 states, by design). It helps you spot regime shifts without reading the table.
Divergences (optional)
Optional bullish/bearish divergence markers compare price pivots vs RS pivots on your chosen benchmark (SPY/QQQ/PEER). These are confirmation tools, not signals by themselves.
What this indicator is NOT
It does not predict tops/bottoms.
It does not replace fundamentals or risk management.
“AUTO peer” is correlation-based; in unusual regimes it can pick a peer that’s statistically close but not conceptually perfect — override with MANUAL when needed.
Suggested workflow
Keep plot mode on Signal (% vs RS MA)
Use AUTO peer for speed; flip to MANUAL if the chosen peer doesn’t make sense.
Use score changes + divergences as context, then use your main price/volume system for entries/exits.
Open-source, modify as you like.
Shorter description
RS Dash v2 compares the current symbol’s relative strength vs SPY, QQQ, and a Peer ETF (manual or auto-selected).
Each benchmark gets a ✅/❌ based on whether RS > RS_MA (optional: MA rising). The dashboard shows a 0–3 score and a Leadership step line that visualizes regime shifts.
Includes 3 plot modes to fix scaling: Signal (% vs MA), Indexed Base 100, and Raw single. Optional RS divergences.
Settings explanation
RS MA length: smoothing for RS trend. Higher = slower, fewer flips.
Auto return length / correlation lookback: controls how AUTO chooses the peer. Higher = more stable but slower to adapt.
Min corr / switch delta: guardrails to prevent nonsense picks and rapid switching.
Plot mode: choose Signal for decision clarity, Indexed for comparison curves, Raw for inspection.
Blunt “professional honesty” note
Correlation-based peer selection is a statistical best guess, not a fundamental sector classifier. That’s why the indicator is transparent: it shows the selected peer and correlation so users can override. Indicator

Strategy

Tanh Clamped Momentum Oscillator [Alpha Extract]A sophisticated momentum measurement system that combines dual EMA trend analysis with volatility-weighted pressure calculations, applying hyperbolic tangent normalization for bounded oscillator output with adaptive signal generation. Utilizing ATR-based volatility regime detection and candle pressure metrics, this indicator delivers institutional-grade momentum assessment with multi-tiered band structure and pulse-based envelope visualization. The system's tanh clamping methodology prevents extreme outliers while maintaining sensitivity to genuine momentum shifts, combined with histogram divergence detection and comprehensive alert framework for high-probability reversal and continuation signals.
🔶 Advanced Dual-Component Momentum Engine
Implements hybrid calculation combining EMA trend differential with candle pressure analysis, weighted by volatility regime assessment for context-aware momentum measurement. The system calculates fast and slow EMA difference normalized by ATR, measures intrabar pressure as close-open relative to range, applies volatility-based weighting between trend and pressure components, and produces composite raw momentum capturing both directional bias and internal candle dynamics.
// Core Momentum Framework
EMA_Fast = ta.ema(src, Fast_Length)
EMA_Slow = ta.ema(src, Slow_Length)
Trend = EMA_Fast - EMA_Slow
// Volatility Regime Detection
ATR_Short = ta.atr(ATR_Length)
ATR_Long = ta.atr(ATR_Length * 2)
Vol_Ratio = ATR_Short / ATR_Long
Vol_Weight = clamp((Vol_Ratio - 0.5) / 1.0, 0, 1)
// Pressure Component
Pressure = (close - open) / (high - low)
// Composite Momentum
Raw = Trend_Normalized * Vol_Weight + Pressure_Scaled * (1 - Vol_Weight)
🔶 Hyperbolic Tangent Normalization Framework
Features sophisticated tanh transformation that clamps raw momentum into bounded range while preserving proportional sensitivity across varying market conditions. The system applies safe exponential calculations with input capping to prevent overflow, computes hyperbolic tangent to compress extreme values while maintaining linearity near zero, and scales output by configurable factor creating oscillator with enhanced dynamic range and reduced outlier distortion.
// Tanh Clamping Logic
tanh(x) =>
x_clamped = clamp(x, -5.0, 5.0)
e = exp(2.0 * x_clamped)
(e - 1.0) / (e + 1.0)
Oscillator = tanh(Smoothed_Momentum / Clamp_Factor) * Scale
🔶 Volatility Regime Weighting System
Implements intelligent volatility assessment comparing short-term and long-term ATR to determine market regime, dynamically adjusting weight between trend and pressure components. The system calculates ATR ratio, normalizes to 0-1 range, and uses this weight factor to emphasize trend component during high-volatility regimes and pressure component during low-volatility consolidations, creating adaptive momentum sensitive to market microstructure.
🔶 Multi-Tiered Band Architecture
Provides comprehensive threshold structure with soft, hard, and maximum bands marking progressive momentum extremes for graduated overbought/oversold assessment. The system establishes configurable levels at soft zones (initial caution), hard zones (strong extreme), and maximum zones (critical overextension) with visual differentiation through line styles and background highlighting, enabling nuanced interpretation beyond binary extreme detection.
🔶 Pulse Envelope Visualization
Features dynamic envelope bands calculated from exponential moving average of absolute oscillator value, creating adaptive boundary that expands during momentum acceleration and contracts during deceleration. The system applies configurable length and width multiplier to pulse calculation, fills area between positive and negative pulse bounds with gradient coloring matching oscillator direction, providing visual context for momentum magnitude relative to recent activity.
🔶 Signal Line Integration Framework
Implements dual-mode signal line supporting both EMA and SMA smoothing of primary oscillator for crossover-based swing detection. The system calculates configurable-length moving average, generates histogram differential between oscillator and signal, applies additional smoothing to histogram for noise reduction, and uses crossovers/crossunders as momentum swing indicators distinguishing bullish and bearish momentum shifts.
🔶 Histogram Divergence Display
Creates column-style histogram visualization showing oscillator-signal differential with intensity-based coloring reflecting momentum acceleration or deceleration. The system plots histogram bars in bright colors when expanding (accelerating momentum) and faded colors when contracting (decelerating momentum), enabling instant visual identification of momentum divergences and convergences without numerical analysis.
🔶 Advanced Reversion Signal Logic
Generates overbought/oversold signals requiring both signal line crossover and extreme threshold breach for high-conviction reversal identification. The system triggers oversold when oscillator crosses above signal while below negative reversion level, triggers overbought when crossing below signal while above positive reversion level, and plots small circle markers at signal locations for clear visual confirmation of setup conditions.
🔶 Comprehensive Alert Framework
Provides six distinct alert conditions covering overbought/oversold reversions, midline trend changes, and oscillator-signal swings with configurable notification preferences. The system includes alerts for extreme reversions (OB/OS), zero-line crossovers (trend changes), and signal line crossovers (momentum swings), enabling traders to monitor critical oscillator events across multiple signal types without constant chart observation.
🔶 Adaptive Bar Coloring System
Implements four coloring modes including midline cross (trend direction), extremities (threshold breach), reversions (OB/OS signals), and slope (oscillator vs signal) for customizable visual integration. The system applies selected color scheme to candles providing chart-level momentum feedback, with option to disable coloring for minimal visual interference while maintaining oscillator pane analysis.
🔶 Performance Optimization Architecture
Utilizes efficient tanh calculation with safe clamping, streamlined EMA computations, and optimized ATR ratio processing for smooth real-time updates. The system includes intelligent null handling, minimal recalculation overhead through smart smoothing application, and configurable display toggles allowing users to disable unused visual elements for enhanced performance during extended historical analysis.
🔶 Why Choose Tanh-Clamped Momentum Oscillator ?
This indicator delivers sophisticated momentum analysis through hybrid trend-pressure calculation with volatility-adaptive weighting and hyperbolic tangent normalization. Unlike traditional momentum oscillators susceptible to extreme outlier distortion, the tanh clamping ensures bounded output while preserving sensitivity to genuine momentum shifts. The system's dual-component architecture combining directional trend with intrabar pressure, weighted by volatility regime assessment, creates context-aware momentum measurement that adapts to market microstructure. The multi-tiered band structure, pulse envelope visualization, and comprehensive signal framework make it essential for traders seeking nuanced momentum analysis with graduated extreme detection and high-probability reversal signals across cryptocurrency, forex, and equity markets. Indicator

Volume Weighted LR Z ScoreThis indicator calculates the Volume Weighted Linear Regression
Z-Score (VWLRZS). Unlike a standard Z-Score which measures
deviation from a static mean, this oscillator measures the
statistical distance of price from a dynamic Volume-Weighted
Linear Regression Line (Analysis of Residuals).
Key Features:
1. **Volatility Decomposition:** The indicator separates volatility
based on the 'Estimate Bar Statistics' option.
- **Standard Mode (`Estimate Bar Statistics` = OFF):** Calculates
standard Regression Residuals using the selected `Source`
for both the regression line (baseline) and the signal.
- **Decomposition Mode (`Estimate Bar Statistics` = ON):**
Uses a hybrid statistical approach:
a) **The Model (Baseline):** Uses an estimator to calculate
the 'within-bar' mean and fits the Linear Regression
through these statistical centers. This creates a
stable, trend-following expectation model.
b) **The Signal (Observation):** Compares the actual `Source`
(e.g., Close) against this regression line.
(Result: A Z-Score that measures deviations from the current
trend slope rather than a flat average).
2. **Visual Decomposition Logic:** Total Standard Deviation (of
Residuals) is the primary metric displayed. Since Standard
Deviations are not linearly additive (sqrt(a+b) != sqrt(a)+sqrt(b)),
this indicator calculates the *exact* Total Z-Score and partitions
the area underneath based on the Variance Ratio. This ensures the
displayed total volatility remains mathematically accurate while
showing relative composition.
3. **Normalization (Exponential Regression):** Includes an optional
'Normalize' mode. When enabled, the indicator calculates the
Linear Regression on logarithmic data. Mathematically, this
transforms the baseline into an **Exponential Regression Curve**,
making it ideal for analyzing assets with compounding growth
characteristics (constant percentage trend).
4. **Full Divergence Suite (Class A, B, C):** The indicator's
primary feature is its integrated divergence engine. It
automatically detects and plots all three major divergence
classes between price and the Z-Score:
- Regular (A): Signals potential trend exhaustion and reversals.
- Hidden (B): Signals potential trend continuations during pullbacks.
- Exaggerated (C): Signals weakness at double tops/bottoms.
5. **Divergence Filtering and Visualization:**
- **Price Tolerance Filter:** Divergence detection is enhanced
with a percentage-based price tolerance (`pivPrcTol`) to
filter out insignificant market noise, leading to more
robust signals.
- **Persistent Visualization:** Divergence markers are plotted
for the entire duration of the signal and are visually
anchored to the oscillator level of the confirming pivot.
- **Flexible Pivot Algorithms:** Supports various underlying
mathematical models for pivot detection provided by the
core library
6. **Note on Confirmation (Lag):** Divergence signals rely on a
pivot confirmation method to ensure they do not repaint.
- The **Start** of a divergence is only detected *after* the
confirming pivot is fully formed (a delay based on
`Pivot Right Bars`).
- The **End** of a divergence is detected either instantly
(if the signal is invalidated by price action) or with
a delay (when a new, non-divergent pivot is confirmed).
7. **Multi-Timeframe (MTF) Capability:**
- **MTF Calculation:** The Z-Score line *itself* can be calculated on a
higher timeframe, with standard options to handle gaps
(`Fill Gaps`) and prevent repainting (`Wait for...`).
- **Limitation:** The Divergence detection engine (`pivDiv`)
is designed for the active timeframe. Using it in MTF mode
is not recommended as step-data can lead to inaccurate
pivot detection.
8. **Integrated Alerts:** Includes a comprehensive set of built-in
alerts for the Z-Score crossing the neutral line, the configured
Threshold levels, and the start/end of all divergence types.
---
**DISCLAIMER**
1. **For Informational/Educational Use Only:** This indicator is
provided for informational and educational purposes only. It does
not constitute financial, investment, or trading advice, nor is
it a recommendation to buy or sell any asset.
2. **Use at Your Own Risk:** All trading decisions you make based on
the information or signals generated by this indicator are made
solely at your own risk.
3. **No Guarantee of Performance:** Past performance is not an
indicator of future results. The author makes no guarantee
regarding the accuracy of the signals or future profitability.
4. **No Liability:** The author shall not be held liable for any
financial losses or damages incurred directly or indirectly from
the use of this indicator.
5. **Signals Are Not Recommendations:** The alerts and visual signals
(e.g., crossovers) generated by this tool are not direct
recommendations to buy or sell. They are technical observations
for your own analysis and consideration. Indicator

Volume Weighted Z ScoreThis indicator calculates the Volume Weighted Z-Score (VWZS), a
statistical oscillator that measures the number of standard deviations
the price is removed from its mean. It combines robust volatility
decomposition with advanced divergence detection.
Key Features:
1. **Volatility Decomposition:** The indicator separates volatility
based on the 'Estimate Bar Statistics' option.
- **Standard Mode (`Estimate Bar Statistics` = OFF):** Calculates
a simple (Volume-Weighted) Standard Deviation using the
selected `Source` for both the baseline and the signal.
- **Decomposition Mode (`Estimate Bar Statistics` = ON):**
Uses a hybrid statistical approach:
a) **The Model (Baseline):** Uses an estimator to calculate
the 'within-bar' mean and volatility. This creates a
stable, mathematically idealized expectation value (mu).
b) **The Signal (Observation):** Compares the actual `Source`
(e.g., Close) against this statistical baseline.
(Result: A Z-Score that combines a noise-filtered trend
baseline with a highly reactive price signal).
2. **Visual Decomposition Logic:** Total Standard Deviation is the
primary metric displayed. Since Standard Deviations are not
linearly additive (sqrt(a+b) != sqrt(a)+sqrt(b)), this indicator
plots the *exact* Total StdDev and partitions the area underneath
based on the Variance Ratio. This ensures the displayed total
volatility remains mathematically accurate while showing relative
composition.
3. **Normalization (Geometric Average):** Includes an optional
'Normalize' mode. When enabled, the indicator uses a
Geometric Moving Average (GMA) as its baseline and applies a
statistical correction for the log-normal distribution
ensuring symmetry between upside and downside movements.
4. **Full Divergence Suite (Class A, B, C):** The indicator's
primary feature is its integrated divergence engine. It
automatically detects and plots all three major divergence
classes between price and the Z-Score:
- Regular (A): Signals potential trend exhaustion and reversals.
- Hidden (B): Signals potential trend continuations during pullbacks.
- Exaggerated (C): Signals weakness at double tops/bottoms.
5. **Divergence Filtering and Visualization:**
- **Price Tolerance Filter:** Divergence detection is enhanced
with a percentage-based price tolerance (`pivPrcTol`) to
filter out insignificant market noise, leading to more
robust signals.
- **Persistent Visualization:** Divergence markers are plotted
for the entire duration of the signal and are visually
anchored to the oscillator level of the confirming pivot.
- **Flexible Pivot Algorithms:** Supports various underlying
mathematical models for pivot detection provided by the
core library
6. **Note on Confirmation (Lag):** Divergence signals rely on a
pivot confirmation method to ensure they do not repaint.
- The **Start** of a divergence is only detected *after* the
confirming pivot is fully formed (a delay based on
`Pivot Right Bars`).
- The **End** of a divergence is detected either instantly
(if the signal is invalidated by price action) or with
a delay (when a new, non-divergent pivot is confirmed).
7. **Multi-Timeframe (MTF) Capability:**
- **MTF Calculation:** The Z-Score line *itself* can be calculated on a
higher timeframe, with standard options to handle gaps
(`Fill Gaps`) and prevent repainting (`Wait for...`).
- **Limitation:** The Divergence detection engine (`pivDiv`)
is designed for the active timeframe. Using it in MTF mode
is not recommended as step-data can lead to inaccurate
pivot detection.
8. **Integrated Alerts:** Includes a comprehensive set of built-in
alerts for the Z-Score crossing the neutral line, the configured
Threshold levels, and the start/end of all divergence types.
---
**DISCLAIMER**
1. **For Informational/Educational Use Only:** This indicator is
provided for informational and educational purposes only. It does
not constitute financial, investment, or trading advice, nor is
it a recommendation to buy or sell any asset.
2. **Use at Your Own Risk:** All trading decisions you make based on
the information or signals generated by this indicator are made
solely at your own risk.
3. **No Guarantee of Performance:** Past performance is not an
indicator of future results. The author makes no guarantee
regarding the accuracy of the signals or future profitability.
4. **No Liability:** The author shall not be held liable for any
financial losses or damages incurred directly or indirectly from
the use of this indicator.
5. **Signals Are Not Recommendations:** The alerts and visual signals
(e.g., crossovers) generated by this tool are not direct
recommendations to buy or sell. They are technical observations
for your own analysis and consideration. Indicator

Ease of MovementThis indicator provides an implementation of the Ease of Movement
(EOM) indicator, enhanced with a built-in divergence detection
engine.
The EOM highlights the relationship between volume and price change.
High positive values indicate that the price is increasing with
low resistance (ease), while low negative values indicate the
price is dropping with ease.
Key Features:
1. **Full Divergence Suite (Class A, B, C):** The primary feature
is the integrated divergence engine. It automatically
detects and plots all three major types of divergences:
- Regular (A): Signals potential trend reversals (e.g., price
rising but "ease" of movement is diminishing).
- Hidden (B): Signals potential trend continuations.
- Exaggerated (C): Signals weakness at double tops/bottoms.
2. **Divergence Filtering and Visualization:**
- **Price Tolerance Filter:** Divergence detection is enhanced
with a percentage-based price tolerance (`pivPrcTol`) to
filter out insignificant market noise, leading to more
robust signals.
- **Persistent Visualization:** Divergence markers are plotted
for the entire duration of the signal and are visually
anchored to the EOM level of the confirming pivot.
- **Flexible Pivot Algorithms:** Supports various underlying
mathematical models for pivot detection provided by the
core library
3. **Customizable Signal Line:** Includes an optional moving average
of the EOM, which serves as a signal line. The type of
MA (`Signal Smoothing`) and its length can be customized.
This signal line can also be optionally volume-weighted
(`Volume weighted`).
4. **Note on Confirmation (Lag):** Divergence signals rely on a
pivot confirmation method to ensure they do not repaint.
- The **Start** of a divergence is only detected *after* the
confirming pivot is fully formed (a delay based on
`Pivot Right Bars`).
- The **End** of a divergence is detected either instantly
(if the signal is invalidated by price action) or with
a delay (when a new, non-divergent pivot is confirmed).
5. **Multi-Timeframe (MTF) Capability:**
- **MTF EOM & Signal Lines:** The EOM and its signal line
can be calculated on a higher timeframe, with standard
options to handle gaps (`Fill Gaps`) and prevent
repainting (`Wait for...`).
- **Limitation:** The Divergence detection engine (`pivDiv`)
is **disabled** if a timeframe other than the chart's
timeframe is selected. Divergences are only calculated
on the active chart timeframe.
6. **Integrated Alerts:** Includes comprehensive alerts for:
- The *start* and *end* of all divergence types.
- The EOM crossing its signal line.
- The EOM crossing the zero line.
---
**DISCLAIMER**
1. **For Informational/Educational Use Only:** This indicator is
provided for informational and educational purposes only. It does
not constitute financial, investment, or trading advice, nor is
it a recommendation to buy or sell any asset.
2. **Use at Your Own Risk:** All trading decisions you make based on
the information or signals generated by this indicator are made
solely at your own risk.
3. **No Guarantee of Performance:** Past performance is not an
indicator of future results. The author makes no guarantee
regarding the accuracy of the signals or future profitability.
4. **No Liability:** The author shall not be held liable for any
financial losses or damages incurred directly or indirectly from
the use of this indicator.
5. **Signals Are Not Recommendations:** The alerts and visual signals
(e.g., crossovers) generated by this tool are not direct
recommendations to buy or sell. They are technical observations
for your own analysis and consideration. Indicator

Volume Price TrendThis indicator provides an implementation of the Volume Price
Trend (VPT) momentum indicator, enhanced with a built-in
divergence detection engine.
Key Features:
1. **Full Divergence Suite (Class A, B, C):** The primary feature
is the integrated divergence engine. It automatically
detects and plots all three major types of divergences:
- Regular (A): Signals potential trend reversals.
- Hidden (B): Signals potential trend continuations.
- Exaggerated (C): Signals weakness at double tops/bottoms.
2. **Divergence Filtering and Visualization:**
- **Price Tolerance Filter:** Divergence detection is enhanced
with a percentage-based price tolerance (`pivPrcTol`) to
filter out insignificant market noise, leading to more
robust signals.
- **Persistent Visualization:** Divergence markers are plotted
for the entire duration of the signal and are visually
anchored to the VPT level of the confirming pivot.
- **Flexible Pivot Algorithms:** Supports various underlying
mathematical models for pivot detection provided by the
core library
3. **Note on Confirmation (Lag):** Divergence signals rely on a
pivot confirmation method to ensure they do not repaint.
- The **Start** of a divergence is only detected *after* the
confirming pivot is fully formed (a delay based on
`Pivot Right Bars`).
- The **End** of a divergence is detected either instantly
(if the signal is invalidated by price action) or with
a delay (when a new, non-divergent pivot is confirmed).
4. **Multi-Timeframe (MTF) Capability:**
- **MTF VPT Line:** The VPT line *itself* can be calculated on a
higher timeframe, with standard options to handle gaps
(`Fill Gaps`) and prevent repainting (`Wait for...`).
- **Limitation:** The Divergence detection engine (`pivDiv`)
is **disabled** if a timeframe other than the chart's
timeframe is selected. Divergences are only calculated
on the active chart timeframe.
5. **Integrated Alerts:** Includes comprehensive alerts that
trigger on the *start* and *end* of all divergence types
(e.g., "Regular Bullish Started", "Regular Bullish Ended").
---
**DISCLAIMER**
1. **For Informational/Educational Use Only:** This indicator is
provided for informational and educational purposes only. It does
not constitute financial, investment, or trading advice, nor is
it a recommendation to buy or sell any asset.
2. **Use at Your Own Risk:** All trading decisions you make based on
the information or signals generated by this indicator are made
solely at your own risk.
3. **No Guarantee of Performance:** Past performance is not an
indicator of future results. The author makes no guarantee
regarding the accuracy of the signals or future profitability.
4. **No Liability:** The author shall not be held liable for any
financial losses or damages incurred directly or indirectly from
the use of this indicator.
5. **Signals Are Not Recommendations:** The alerts and visual signals
(e.g., crossovers) generated by this tool are not direct
recommendations to buy or sell. They are technical observations
for your own analysis and consideration. Indicator
