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

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

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

Divergence Detector [TradingFinder] RSI + MACD + AO Oscillator 🔵 Introduction
🟣 Understanding Divergence
As mentioned, divergence occurs in technical analysis when a stock's price behaves contrary to indicators on the price chart. Divergence can signify either a reversal of the stock's trend or a continuation of the previous trend correction.
Divergences can act as reversal patterns or continuation patterns. Moreover, divergences can be utilized to identify potential support and resistance levels.
For instance, when an indicator is trending upwards and positive, but the price is declining and trending downwards, divergence occurs. Divergence in a stock indicates trader indecision in buying and selling and warns traders to reconsider their decisions regarding buying or holding the stock.
Divergence aids analysts in identifying critical price points. In indicator divergences, it serves as a potent signal in the realm of technical analysis.
🟣 Types of Divergence
1.Regular Divergence
o Positive Regular Divergence (RD+)
o Negative Regular Divergence (RD-)
2.Hidden Divergence
o Positive Hidden Divergence (HD+)
o Negative Hidden Divergence (HD-)
3.Time Divergence
Key Note : This indicator is specifically designed to identify "Regular Divergence" only. Therefore, the following explanation pertains to this type of divergence.
🔵 Regular Divergence/Convergence
Regular Divergence(Convergence) occurs due to conflicting behavior between the indicator and the price chart, typically at the end of a trend. Recognizing Regular Divergence suggests an anticipation of a trend reversal or a pattern resembling a reversal.
🟣 Positive Regular Divergence (RD+)
In contrast to negative divergence, positive Regular Divergence occurs at the end of a downtrend and between two price lows. It manifests when the price forms a new low on the price chart, but the indicator fails to recognize it.
Positive Regular Divergence indicates strong buying pressure and weak selling pressure. Following the identification of positive divergence on the chart, one can anticipate a price increase for the examined stock.
🟣 Negative Regular Divergence (RD-)
This type of Regular Divergence emerges between two price highs during an uptrend. A new high is formed on the price chart, but the indicator fails to acknowledge it. This scenario indicates negative Regular Divergence.
The likelihood of a subsequent market downturn is high. Negative divergence signifies strong selling pressure and weak buying pressure, suggesting an unfavorable future for the stock.
🔵 How to use
By utilizing the "Fractal Period" input, you can specify your desired periods for identifying divergences.
Additionally, through the "Divergence Detect Method" feature, you can choose which oscillators (MACD, RSI, or AO) to base divergence identification on.
Divergence in MACD Oscillator :
Divergence in the MACD indicator occurs when the price chart and the MACD line form a noticeable opposing pattern, meaning the price moves contrary to the MACD line. In this scenario, one expects a reversal in price direction.
Divergence in RSI Oscillator :
If divergence occurs during a downtrend on the price chart (two consecutive lows, with the second low being lower) and on the corresponding RSI point (two consecutive lows, with the second low being higher), it signifies positive Regular Divergence and implies a buying signal.
Conversely, if divergence occurs during an uptrend on the price chart (two consecutive highs, with the second high being higher) and on the corresponding RSI point (two consecutive highs, with the second high being lower), it indicates negative Regular Divergence, signaling a selling opportunity.
Divergence in AO Oscillator :
The AO indicator calculates histograms similar to the AO base. It calculates the difference between the simple moving averages of 5 and 34 periods based on the median of each bar. Then, it plots the bars based on the difference.
It then compares the histograms to detect peaks and troughs in the AO histograms and compares the identified peaks and troughs to the price. Whenever divergence is detected, it plots lines and arrows.
🔵 Table
The table contains information on the functional features of this oscillator that you can utilize. Four categories of information are presented in the table: "Exist," "Consecutive," "Divergence Quality," and "Change Phase Indicator."
Exist :
If divergence exists, you'll see "+" in this row.
Consecutive :
Divergences may occur consecutively. If same-type divergences form within short intervals, you can observe the count in this row.
Divergence Quality : Based on the number of consecutive divergences, their quality can be evaluated. If one divergence exists, its quality is considered "Normal." If two divergences exist, the quality is "Good," and if three or more divergences exist, the quality is considered "Strong."
Change Phase Indicator : If a phase change occurs between two oscillation peaks formed based on divergence, this change is identified and displayed in this row.
Indicator

Divergence for Many Indicators v4Hello Traders,
Here is my new year gift for the community, Digergence for Many Indicators v4 . I tried to make it modular and readable as much as I can. Thanks to Pine Team for improving Pine Platform all the time!
How it works?
- On each candle it checks divergences between current and any of last 16 Pivot Points for the indicators.
- it search divergence on choisen indicators => RSI , MACD , MACD Histogram, Stochastic , CCI , Momentum, OBV, VWMACD, CMF and any External Indicator !
- it checks following divergences for 16 pivot points that is in last 100 bars for each Indicator.
--> Regular Positive Digergences
--> Regular Negative Digergences
--> Hidden Positive Digergences
--> Hidden Negative Digergences
- for positive divergences first it checks if closing price is higher than last closing price and indicator value is higher than perious value, then start searching divergence
- for negative divergences first it checks if closing price is lower than last closing price and indicator value is lower than perious value, then start searching divergence
Some Options:
Pivot Period: you set Pivot Period as you wish. you can see Pivot Points using "Show Pivot Points" option
Source for Pivot Points: you can use Close or High/Low as source
Divergence Type: you can choose Divergence type to be shown => "Regular", "Hidden", "Regular/Hidden"
Show Indicator Names: you have different options to show indicator names => "Full", "First Letter", "Don't Show"
Show Divergence Number: option to see number of indicators which has Divergence
Show Only Last Divergence : if you enable this option then it shows only last Positive and Negative Divergences
you can include any External Indicator to see if there is divergence
- enable "Check External Indicator"
- and then choose External indicator name in the list, "External Indicator"
- External indicator name is shown as Extrn
- related external indicator must be added before enabling this option
Coloring, line width and line style options for different type of divergences.
Following Alerts added:
- Positive Regular Divergence Detected
- Negative Regular Divergence Detected
- Positive Hidden Divergence Detected
- Negative Hidden Divergence Detected
Now lets see some examples:
Hidden Divergences:
Regular and Hidden Divergences together:
Showing first letters of indicators:
You can see only the number of indicators which has divergence:
You can see only divergence lines without indicators names and numbers:
option to used different label/line/text colors:
You have option to see only last divergences:
You can change Pivot Period, in following example Pivot Period = 15:
You can use Close or High/Low as Source for Divergence
You can include external indicators and get divergences on it:
Wish you all a happy new year!
Enjoy! Indicator

Indicator

Indicator

Indicator

Divergences for many indicators v2.0A gift from me to all.
This script is developed to find Divergences for many indicators. it analyses divergences and then draws line on the graph. red for negatif, lime for positive divergences.
Currently script checks divergence for RSI, MACD, MACD Histogram, Stochastic, CCI, Momentum, OBV, Diosc, VWMACD and CMF indicators. You can use some or all of these indicators to check divergences as you wish by choosing them on the menu. Also you can add/remove many other indicators to the script to check if there is divergence.
The script first calculates tops/bottoms by using higher time frame zig zag and then finds divergences.
Higher Time Frames are
if currend period 1 min => HTF = 5 mins
if currend period 3 mins => HTF = 15 mins
if currend period 5 mins => HTF = 15 mins
if currend period 15 mins => HTF = 1 hour
if currend period 30 mins => HTF = 1 hour
if currend period 45 mins => HTF = 1 hour
if currend period 1 hour => HTF = 4 hours
if currend period 2 hours => HTF = 4 hours
if currend period 3 hours => HTF = 4 hours
if currend period 4 hours => HTF = 1 day
if currend period 1 day => HTF = 1 week
if currend period 1 week => HTF = 1 week
future plan : script finds regular divergences, soon I will add hidden divergences and also I plan to add alert ;)
Indicator

Indicator
