Auto Play Ping/Pong [UAlgo]Auto Play Ping/Pong is a fully self running arcade style mini game built entirely in Pine Script and rendered directly on the chart. Instead of analyzing price, this script turns the chart area into a compact game field where two AI controlled paddles rally a moving ball from one side to the other while the score updates in real time.
The script is designed as a visual and technical showcase of what Pine Script can do with custom objects such as boxes, lines, labels, arrays, and user defined types. It demonstrates persistent state handling, frame by frame physics updates, collision detection, automatic paddle control, scoring logic, and motion trail rendering, all inside a chart overlay.
The left and right paddles are both controlled by simple AI logic. Each paddle reacts to the vertical position of the ball and tries to align itself for the next return. The ball bounces off the top and bottom boundaries, changes direction when it touches a paddle, and resets to the center when one side misses. A trail effect is also added to make movement easier to follow and visually more dynamic.
What makes this script interesting is that it is not simply drawing static shapes. It maintains a persistent game state across updates, modifies that state on every bar, and redraws the field using live object coordinates. This makes it a playful but technically instructive example of animation and object control in Pine Script.
In practical terms, this script is a creative visual project rather than a trading tool. It is useful for demonstrating real time state management, chart object animation, and game style logic inside PulseWire.
🔹 Features
🔸 Fully Automated Gameplay
Both paddles are controlled automatically. The script continuously tracks the ball position and moves each paddle vertically to intercept the ball without user input.
🔸 Persistent Game State
The script uses a dedicated game state object to store ball position, paddle positions, scores, trail points, and drawing references. This allows the whole game to evolve smoothly over time.
🔸 Ball Physics and Collision Logic
The ball moves with its own horizontal and vertical velocity, bounces off the top and bottom walls, reacts to paddle contact, and changes its vertical angle depending on where it hits the paddle.
🔸 Score Tracking
If one paddle misses the ball, the opposing side scores a point. The ball then resets to the center and starts a fresh rally with directional variation.
🔸 Paddle AI With Speed Limits
Each paddle follows the ball using its own maximum movement speed. This gives the game a natural chase behavior and prevents instant teleport style motion.
🔸 Motion Trail Effect
The ball leaves a fading trail behind it using a sequence of stored points and prebuilt lines. This improves visual clarity and gives the movement a smoother arcade feel.
🔸 Custom Game Field Rendering
The play area is drawn with a background box, two paddle lines, a circular ball label, a score label, and trail segments. Everything is positioned relative to the current bar index.
🔸 Chart Overlay Animation
The game is drawn directly over the chart with overlay=true , which turns the chart into a moving visual canvas.
🔹 Calculations
1) Defining the Game Geometry and Core Constants
var int GAME_WIDTH = 80
var float GAME_HEIGHT = 100.0
var float PADDLE_H = 20.0
var float BALL_SPD_X = 1.8
var float BALL_SPD_Y = 1.2
var int TRAIL_LEN = 10
var float AI_SPEED_1 = 1.1
var float AI_SPEED_2 = 1.2
This block defines the full physical layout and motion parameters of the game.
GAME_WIDTH sets the horizontal size of the play area.
GAME_HEIGHT sets the vertical size.
PADDLE_H defines paddle height.
BALL_SPD_X and BALL_SPD_Y define the initial ball speed.
TRAIL_LEN defines how many trail segments are stored.
AI_SPEED_1 and AI_SPEED_2 define how quickly each paddle can move.
So before any gameplay starts, the script already establishes the dimensions and motion rules of the whole arena.
2) Defining the Point and Game State Objects
type Point
float x
float y
type GameState
float ball_x
float ball_y
float ball_vx
float ball_vy
float p1_y
float p2_y
int p1_score
int p2_score
box bg_box
line p1_line
line p2_line
label ball_lbl
label score_lbl
array trail_pts
array trail_lines
This is the structural foundation of the script.
The Point type stores one coordinate pair. It is used for the trail system.
The GameState type stores the full live state of the game:
the ball position,
the ball velocity,
the vertical positions of both paddles,
both scores,
the main drawing objects,
and the trail arrays.
This design is important because the script is not just drawing shapes independently. It is managing a complete game world through one persistent object.
3) Creating the Visual Objects on the First Bar
method init_drawings(GameState state) =>
state.bg_box := box.new(na, na, na, na, border_color=color.new(color.gray, 60), border_width=1, bgcolor=C_BG)
state.p1_line := line.new(na, na, na, na, color=C_P1, width=4)
state.p2_line := line.new(na, na, na, na, color=C_P2, width=4)
state.ball_lbl := label.new(na, na, "", color=C_BALL, style=label.style_circle, size=size.small)
state.score_lbl := label.new(na, na, "0 - 0", color=color.new(color.white, 100), textcolor=color.silver, style=label.style_none, size=size.large)
This method creates the core objects that will later be updated every frame.
The script builds:
a background box for the game field,
a line for the left paddle,
a line for the right paddle,
a circular label for the ball,
and a score label.
These are created only once, then reused and repositioned as the game evolves. This is much more efficient than deleting and recreating everything on every update.
4) Preparing the Ball Trail System
for i = 0 to TRAIL_LEN - 1
color fade_color = color.new(C_BALL, 100 - int((TRAIL_LEN - i) * 100 / TRAIL_LEN))
state.trail_lines.push(line.new(na, na, na, na, color=fade_color, width=2))
state.trail_pts.push(Point.new(state.ball_x, state.ball_y))
This loop initializes the trail effect.
For each trail slot, the script creates:
a line object with progressively changing transparency,
and a point initialized at the current ball position.
The idea is simple. The newest trail segments remain more visible, while older trail segments fade away. This creates the illusion of motion persistence behind the ball.
So the trail is not a single effect. It is a chain of stored points and lines that move along with the ball.
5) Updating Ball Position Each Frame
method update_physics(GameState state) =>
state.ball_x += state.ball_vx
state.ball_y += state.ball_vy
This is the first step of the physics engine.
On every update, the ball position is advanced by its horizontal and vertical velocity values. This is the basic motion rule of the game.
If nothing else happened, the ball would keep moving in a straight line forever. The rest of the physics method exists to modify that path through AI movement, wall bounces, paddle collisions, and scoring resets.
6) Left Paddle AI Logic
if state.ball_vx < 0
if state.p1_y + PADDLE_H/2 < state.ball_y
state.p1_y += math.min(AI_SPEED_1, state.ball_y - (state.p1_y + PADDLE_H/2))
else if state.p1_y - PADDLE_H/2 > state.ball_y
state.p1_y -= math.min(AI_SPEED_1, (state.p1_y - PADDLE_H/2) - state.ball_y)
This block controls the left paddle.
The paddle only reacts when the ball is moving toward the left side, which is why the script first checks:
state.ball_vx < 0
Then it compares the ball’s vertical position to the top and bottom edges of the paddle. If the ball is above the paddle center zone, the paddle moves upward. If the ball is below it, the paddle moves downward.
The amount of movement is limited by AI_SPEED_1 , which prevents the paddle from moving instantly.
So the left paddle behaves like a simple tracking AI that tries to align itself with incoming ball position.
7) Right Paddle AI Logic
if state.ball_vx > 0
if state.p2_y + PADDLE_H/2 < state.ball_y
state.p2_y += math.min(AI_SPEED_2, state.ball_y - (state.p2_y + PADDLE_H/2))
else if state.p2_y - PADDLE_H/2 > state.ball_y
state.p2_y -= math.min(AI_SPEED_2, (state.p2_y - PADDLE_H/2) - state.ball_y)
This is the mirror logic for the right paddle.
It only moves when the ball is traveling toward the right side. It uses the same tracking idea as the left paddle, but its maximum speed is set independently by AI_SPEED_2 .
That means each side can have slightly different behavior and difficulty characteristics.
8) Keeping Paddles Inside the Arena
state.p1_y := math.max(PADDLE_H/2, math.min(GAME_HEIGHT - PADDLE_H/2, state.p1_y))
state.p2_y := math.max(PADDLE_H/2, math.min(GAME_HEIGHT - PADDLE_H/2, state.p2_y))
After paddle movement is updated, the script clamps both paddles so they cannot leave the top or bottom of the field.
The center of each paddle must remain between:
PADDLE_H/2
and
GAME_HEIGHT - PADDLE_H/2
This ensures that the visible paddle body never extends outside the game frame.
9) Ball Bounce on Top and Bottom Walls
if state.ball_y >= GAME_HEIGHT
state.ball_y := GAME_HEIGHT
state.ball_vy := -state.ball_vy
else if state.ball_y <= 0
state.ball_y := 0
state.ball_vy := -state.ball_vy
This block handles vertical wall collisions.
If the ball reaches or exceeds the top boundary, its vertical position is snapped to the top edge and its vertical velocity is reversed.
If the ball reaches or drops below the bottom boundary, the same thing happens at the lower edge.
This creates a classic arcade bounce effect where the ball reflects off the horizontal walls and stays inside the arena.
10) Left Side Paddle Collision and Right Side Scoring
if state.ball_x <= 0
if math.abs(state.ball_y - state.p1_y) <= PADDLE_H/2 + 3
state.ball_x := 0
state.ball_vx := -state.ball_vx
state.ball_vy += (state.ball_y - state.p1_y) * 0.15
state.ball_vy := math.max(-4.0, math.min(4.0, state.ball_vy))
else
state.p2_score += 1
state.ball_x := GAME_WIDTH / 2
state.ball_y := GAME_HEIGHT / 2
state.ball_vx := BALL_SPD_X
state.ball_vy := BALL_SPD_Y * (state.p2_score % 2 == 0 ? 1 : -1)
This is one of the main gameplay blocks.
When the ball reaches the left boundary, the script checks whether the ball is close enough to the left paddle vertically. If yes, it counts as a successful return.
On a successful return:
the ball is snapped to the left edge,
its horizontal velocity is reversed,
and its vertical velocity is modified based on where it hit the paddle.
This extra adjustment is important because it creates angled returns rather than perfectly repetitive motion. The farther from the paddle center the hit occurs, the more the vertical speed is changed.
The vertical speed is then clamped between negative four and positive four to keep the game stable.
If the left paddle misses, the right side scores a point. The ball resets to the center, moves back toward the right, and gets a vertical direction that alternates based on score parity.
11) Right Side Paddle Collision and Left Side Scoring
else if state.ball_x >= GAME_WIDTH
if math.abs(state.ball_y - state.p2_y) <= PADDLE_H/2 + 3
state.ball_x := GAME_WIDTH
state.ball_vx := -state.ball_vx
state.ball_vy += (state.ball_y - state.p2_y) * 0.15
state.ball_vy := math.max(-4.0, math.min(4.0, state.ball_vy))
else
state.p1_score += 1
state.ball_x := GAME_WIDTH / 2
state.ball_y := GAME_HEIGHT / 2
state.ball_vx := -BALL_SPD_X
state.ball_vy := BALL_SPD_Y * (state.p1_score % 2 == 0 ? 1 : -1)
This is the mirror version of the left side logic.
When the ball reaches the right boundary, the script tests whether the right paddle is in position. If it is, the ball bounces back left and its vertical speed changes according to impact location. If not, the left player scores and the ball resets to center.
Together, the left and right boundary blocks define the full rally and scoring logic of the game.
12) Updating the Trail Memory
state.trail_pts.unshift(Point.new(state.ball_x, state.ball_y))
state.trail_pts.pop()
After the new ball position is resolved, the script stores it at the front of the trail point array. Then it removes the oldest stored point from the end.
This gives the script a rolling history of recent ball positions. Those points are later used to position each trail segment.
So the trail always follows the newest motion path while keeping a fixed length.
13) Converting Game Coordinates Into Chart Coordinates
method draw_frame(GameState state, int base_x) =>
int right_x = base_x + 5
int left_x = right_x - GAME_WIDTH
This method begins the rendering step.
The game is not drawn in a separate graphics window. It is projected directly onto chart coordinates. The current bar index acts as the base anchor, and the script defines a right edge slightly ahead of it. From that right edge, it subtracts the game width to get the left edge.
So the whole game field is mapped into a section of chart space that moves with the current bar position.
14) Drawing the Background and Paddles
state.bg_box.set_lefttop(left_x, GAME_HEIGHT)
state.bg_box.set_rightbottom(right_x, 0)
state.p1_line.set_xy1(left_x, state.p1_y + PADDLE_H/2)
state.p1_line.set_xy2(left_x, state.p1_y - PADDLE_H/2)
state.p2_line.set_xy1(right_x, state.p2_y + PADDLE_H/2)
state.p2_line.set_xy2(right_x, state.p2_y - PADDLE_H/2)
This block updates the main field and the paddle drawings.
The background box spans from the left edge to the right edge and from zero to the full game height.
The left paddle is drawn as a vertical line on the left boundary.
The right paddle is drawn as a vertical line on the right boundary.
Each paddle extends above and below its center position by half the paddle height. That makes the paddle length consistent and easy to manage mathematically.
15) Drawing the Ball and the Score
state.ball_lbl.set_xy(left_x + int(math.round(state.ball_x)), state.ball_y)
state.score_lbl.set_xy(left_x + GAME_WIDTH/2, GAME_HEIGHT - 10)
state.score_lbl.set_text(str.tostring(state.p1_score) + " - " + str.tostring(state.p2_score))
This block positions the moving ball and updates the scoreboard.
The ball label is placed by adding the ball’s internal game x coordinate to the left boundary of the field. Its y coordinate is the current ball height.
The score label is placed near the top center of the arena and updated with the current left and right scores.
So every frame, the game communicates both live motion and match progress.
16) Drawing the Motion Trail
for i = 0 to TRAIL_LEN - 1
Point p1 = state.trail_pts.get(i)
Point p2 = i + 1 < TRAIL_LEN ? state.trail_pts.get(i + 1) : p1
line l = state.trail_lines.get(i)
l.set_xy1(left_x + int(math.round(p1.x)), p1.y)
l.set_xy2(left_x + int(math.round(p2.x)), p2.y)
This loop converts stored trail points into visible trail segments.
For each trail slot, the script reads one point and the next point after it. Then it updates the corresponding trail line so it connects those two positions.
Because the trail lines were created with different transparency levels earlier, the newest segments appear stronger and older segments fade out.
This gives the ball a continuous motion streak that makes gameplay easier to follow visually.
17) Persistent State Initialization
varip GameState state = GameState.new(
ball_x = GAME_WIDTH / 2,
ball_y = GAME_HEIGHT / 2,
ball_vx = BALL_SPD_X,
ball_vy = BALL_SPD_Y,
p1_y = GAME_HEIGHT / 2,
p2_y = GAME_HEIGHT / 2,
p1_score = 0,
p2_score = 0,
trail_pts = array.new(),
trail_lines = array.new()
)
This block creates the persistent live game state.
The ball starts in the center of the arena.
Both paddles start in the vertical center.
Both scores start at zero.
Empty arrays are prepared for the trail points and trail lines.
The use of varip is important here because it keeps the game state persistent as the script updates, allowing the game to evolve continuously rather than resetting each time.
18) First Bar Initialization and Main Update Loop
if barstate.isfirst
state.init_drawings()
state.update_physics()
state.draw_frame(bar_index)
This is the main execution flow.
On the very first bar, the script creates all required drawings through init_drawings() .
After that, every update performs two steps:
first the game physics are advanced,
then the new state is rendered onto the chart.
This is the standard game loop pattern:
update state,
then draw state.
19) Invisible Plot Anchors
plot(100, color=color.new(color.white, 100))
plot(0, color=color.new(color.white, 100))
These invisible plots help stabilize the vertical scale for the game area.
Because the whole arena is designed between zero and one hundred on the y axis, plotting hidden values at those levels ensures the script keeps a consistent vertical drawing space.
This is a subtle but important implementation detail. Without it, the game objects could be compressed or mispositioned by automatic scaling behavior.
20) Practical Interpretation
Auto Play Ping/Pong is best understood as a Pine Script animation and state management demo rather than as a market analysis indicator. Its real value comes from showing how chart objects, arrays, persistent state, and update logic can be combined to create a living visual system inside PulseWire.
The script demonstrates:
state persistence,
object reuse,
basic game physics,
simple AI motion,
collision handling,
score management,
and visual effects such as motion trails.
That makes it a strong example for anyone exploring creative Pine development, chart animation, or non traditional overlay design. Indicator

Volatility-Adjusted Rate of Change [QuantAlgo]🟢 Overview
The Volatility-Adjusted Rate of Change (VA-ROC) is a momentum oscillator that normalizes price changes against current market volatility, helping traders identify meaningful momentum shifts, spot overbought/oversold extremes, and filter out noise caused by changing volatility regimes. By measuring how large a price move is relative to what's normal for the instrument, this indicator reveals genuine directional pressure that raw momentum readings often obscure.
🟢 How It Works
The indicator begins by calculating the single-bar price change and dividing it by the Average True Range over a configurable lookback period. This normalization step ensures that the same oscillator reading carries equal significance whether applied to a low-volatility blue chip or a highly volatile cryptocurrency, a concept absent from traditional rate of change indicators.
price_momentum = ta.change(close) / ta.atr(atr_length)
When price rises by an amount that is large relative to recent volatility, the normalized momentum produces a strong positive reading. Conversely, a decline that is modest in absolute terms but significant relative to the current ATR environment will register appropriately. This volatility-adjustment prevents the oscillator from generating inflated signals during high-volatility regimes or muted signals during quiet markets.
A sensitivity multiplier then scales the normalized value, allowing traders to compress or amplify the oscillator's range to suit their instrument and timeframe:
va_roc = calc_ma(price_momentum * sensitivity, ma_length, ma_type)
The scaled momentum is then smoothed using a configurable moving average (supporting SMA, EMA, WMA, RMA, HMA, VWMA, DEMA, and TEMA), which filters bar-to-bar noise while preserving the shape of genuine momentum waves. The smoothed output is the final VA-ROC value, plotted against a system of four threshold levels that define bullish, bearish, neutral, and extreme zones.
Momentum state is determined by the oscillator's position relative to these thresholds:
is_bullish = va_roc > upper_threshold
is_bearish = va_roc < lower_threshold
Crossings into bullish or bearish territory, zero-line crosses, and entries into extreme zones each generate distinct signals and corresponding alerts.
🟢 Key Features
The indicator is built around a threshold-based momentum framework with gradient-colored visualization, preset configurations, and a full alert system, all designed to give traders immediate clarity on momentum conditions without manual tuning.
1. Volatility Normalization: Unlike traditional ROC or momentum oscillators that produce raw price differences, VA-ROC divides every price change by the ATR, creating a dimensionless reading that remains consistent across instruments, timeframes, and volatility regimes. A reading of +1.0 always means "price moved one ATR's worth in a single bar", whether you're trading forex, equities, or crypto. This eliminates the need to recalibrate threshold levels when switching between assets.
2. Adaptive Threshold Zones: Four configurable levels (Upper Extreme, Upper Threshold, Lower Threshold, and Lower Extreme) divide the oscillator into five distinct momentum zones. The neutral zone between the upper and lower thresholds represents normal market fluctuation. Crossings above the upper threshold confirm bullish momentum, while crossings below the lower threshold confirm bearish momentum. The extreme levels mark climactic conditions where momentum is unusually powerful, often coinciding with exhaustion points or the early stages of a strong trend continuation.
3. Preset Configurations: Three built-in presets automatically optimize the sensitivity, ATR lookback, MA type, and smoothing length for different trading styles. Default provides balanced readings suited for swing trading on 4H and daily charts. Fast Response amplifies small moves with minimal smoothing for intraday scalping. Smooth Trend compresses the oscillator and applies heavier smoothing to highlight only significant directional moves for position trading.
4. Built-in Alert System: Comprehensive alerts covering all key momentum events, including bullish and bearish momentum confirmation, zero-line crossovers in both directions, and entries into upper and lower extreme zones. A combined momentum direction change alert is also included. All alerts carry exchange, ticker, and interval placeholders for seamless integration with notification workflows.
5. Visual Customization: Choose from 5 color presets (Classic, Aqua, Cosmic, Cyber, Neon) or create a fully custom color scheme using individual bullish, bearish, and neutral color pickers. Optional price bar coloring overlays the oscillator's momentum colors directly onto your main chart candles, tinting bars bullish or bearish based on the current threshold state while leaving neutral bars uncolored, providing instant trend confirmation without switching panels.
Indicator

3D Volume Profile [UAlgo]3D Volume Profile is a chart based volume profile indicator that takes a classic horizontal profile concept and presents it as a pseudo 3D structure directly on price. Instead of drawing flat histogram bars only, the script renders each profile row as a shaded 3D block with a front face, a side face, and a top face, which creates a stronger visual sense of depth and distribution.
The indicator runs on price ( overlay=true ) and builds a rolling volume profile over a user defined lookback window. It divides the recent price range into fixed bins, distributes candle volume across those bins, identifies the Point of Control and the Value Area, and then draws the result on the right side of the chart. Each row is color coded by dominant flow direction, which means the profile can show whether a bin was more buy dominated or sell dominated in addition to showing how much total volume accumulated there.
This makes the tool useful for traders who want more than a basic profile display. It combines:
A rolling horizontal volume profile
Buy versus sell dominance shading
Point of Control and Value Area detection
A forward projected 3D style histogram
Clear POC, VAH, and VAL reference lines on the chart
The final result is a visually rich profile tool designed for fast structural reading, especially when identifying acceptance zones, thin areas, and dominant participation regions.
🔹 Features
🔸 1) Rolling Volume Profile Over a Recent Window
The script builds a rolling profile from the most recent user selected number of bars. This means the profile continuously adapts as new bars come in, making it more useful for current market structure analysis than a fixed session only approach.
🔸 2) 3D Style Histogram Rendering
Each volume row is drawn as a pseudo 3D block rather than a flat rectangle. The script creates:
A front face
A side face
A top face
The side and top faces are shaded versions of the main color, which gives the profile a depth effect and makes the structure easier to read visually.
🔸 3) Customizable 3D Depth in X and Y
The 3D effect is controlled with two settings:
3D Depth X , which controls how far the rear face is shifted horizontally in bars
3D Depth Y , which controls how far the rear face is shifted vertically as a percentage of row height
This allows the user to make the profile look flatter or more pronounced depending on preference.
🔸 4) Buy and Sell Volume Dominance Coloring
Each bin tracks both buy volume and sell volume. If buy volume is greater than or equal to sell volume, the row uses the bullish color. If sell volume dominates, the row uses the bearish color.
This means the profile is not only a measure of total activity. It also adds directional context to each price zone.
🔸 5) Point of Control Detection
The script identifies the row with the highest total volume and marks it as the Point of Control. The POC is highlighted with its own dedicated color and is visually distinct from the rest of the profile.
This gives traders an immediate reference for the most active price zone in the rolling range.
🔸 6) Value Area Calculation
The indicator calculates a Value Area around the Point of Control based on the user selected percentage. Bins inside the Value Area are marked and recolored with the Value Area color, which makes the high participation region easy to identify.
🔸 7) Forward Projected Profile Layout
The profile is drawn to the right of current price using a configurable offset. This keeps the active candle area readable while still placing the profile in a clear and accessible location.
🔸 8) Adjustable Resolution and Width
Users can control:
The lookback length
The number of profile rows
The maximum width of the histogram
The right side offset
This makes the indicator suitable for both coarse structural analysis and more detailed profile inspection.
🔸 9) POC, VAH, and VAL Reference Lines
After the profile is built, the script calculates the POC, Value Area High, and Value Area Low, then projects horizontal reference lines across the chart. Labels are placed to the right so the key levels are clearly marked.
🔸 10) Row by Row Dominance and Acceptance Reading
Because each row stores total volume, buy volume, sell volume, Value Area membership, and POC status, the indicator gives a layered view of the market:
Where the most activity occurred
Which zones were accepted
Which zones were dominated by buyers
Which zones were dominated by sellers
🔸 11) Premium Visual Presentation
The script uses shaded faces, dedicated POC highlighting, Value Area recoloring, and clean right side labels. This makes it more presentation focused than a basic flat profile and improves chart readability for manual analysis.
🔹 Calculations
1) Profile Range Detection
The script first finds the highest high and lowest low inside the active lookback window. This defines the full vertical range of the volume profile. Only the most recent bars inside that window are used for profile construction.
2) Bin Initialization
Once the recent range is known, the script divides that price range into the chosen number of bins. Each bin stores:
Top boundary
Bottom boundary
Total volume
Buy volume
Sell volume
Flags for Value Area and POC
The bin size is calculated by dividing the total price range by the number of rows.
3) Volume Distribution Across Price Bins
For each candle, the script determines which bins the candle spans. It then spreads that candle’s volume evenly across all touched bins.
This is important because the script does not place the full candle volume into a single price level. Instead, it allocates the candle volume across the portion of the profile that candle covers.
Important implementation note:
This script uses equal distribution across the spanned bins, not proportional overlap weighting. That means each touched row receives the same share of the candle’s volume.
4) Buy Versus Sell Volume Classification
The script classifies each candle as buy dominated or sell dominated using candle direction:
If close is greater than or equal to open, the candle is treated as buy volume
If close is below open, the candle is treated as sell volume
That candle’s allocated volume is then added to either volBuy or volSell inside each touched bin.
This is a practical directional approximation, not true bid ask tape volume.
5) Total Volume and POC Detection
After all candles are processed, the script scans every bin and calculates:
The total volume across the profile
The maximum single bin volume
The POC index
The POC is the bin with the highest total volume. That bin is marked as both isPOC and isVA before Value Area expansion begins.
6) Value Area Expansion Logic
The Value Area is built around the POC by expanding upward and downward until the selected percentage of total profile volume is included.
The script compares the next bin above and the next bin below the current Value Area. It adds whichever side has greater volume first. This continues until cumulative included volume reaches the target Value Area percentage.
This creates a standard profile style Value Area centered on the highest participation region.
7) Histogram Width Normalization
Each row’s width is scaled relative to the maximum volume row:
The row with the most volume becomes the widest
Smaller rows are scaled proportionally
This means width directly communicates relative participation at each price zone.
8) Color Selection Logic
For each bin, the script first determines whether buy volume or sell volume dominates:
If buy volume is greater than or equal to sell volume, it uses the bullish color
Otherwise it uses the bearish color
Then the script overrides that base direction color if needed:
If the row is the POC, it uses the POC color
If the row is inside the Value Area, it uses the Value Area color
This gives the profile a clear visual hierarchy:
POC first
Value Area second
Directional dominance otherwise
9) 3D Face Construction
Each row is rendered as a pseudo 3D object using:
A front rectangle
A shifted back edge using the X and Y depth settings
A side face when horizontal depth is visible
A top or bottom face depending on vertical depth direction
The script shades the side face darker and the top face brighter than the base color to create a depth illusion.
This is a visual projection technique, not a true 3D engine, but it produces a convincing 3D profile effect on the chart.
10) Rendering Order Logic
The script changes draw order depending on the sign of the Y depth:
If vertical depth is positive, rows are drawn from bottom to top
If vertical depth is negative, rows are drawn from top to bottom
This helps the 3D faces stack more cleanly and reduces visual overlap issues.
11) POC, VAH, and VAL Price Calculation
After the profile is complete:
The POC price is the midpoint of the POC bin
VAH is the highest top boundary among all Value Area bins
VAL is the lowest bottom boundary among all Value Area bins
These levels are then drawn as horizontal lines extending from the left side of the lookback window toward the right side label area.
12) Label Placement
The labels for POC, VAH, and VAL are placed slightly to the right of the profile. This keeps them readable and avoids overlap with the 3D bars themselves. Indicator

Indicator

Volatility-Gated Trend Oscillator [QuantAlgo]🟢 Overview
The Volatility-Gated Trend Oscillator identifies statistically significant trend conditions by measuring price deviation from a dynamic baseline and filtering out normal market noise through an adaptive volatility floor. It calculates a moving average of the chosen type as a baseline, then measures how far price has deviated from it relative to average absolute deviation to define a noise threshold. Only when price breaks decisively beyond this threshold is a trend state confirmed, helping traders distinguish genuine momentum from random noise across different timeframes and markets.
🟢 How It Works
The indicator's core methodology lies in its dual-layer approach combining deviation measurement with volatility-gated filtering, where trend confirmation requires price movement to exceed statistically meaningful thresholds.
First, a configurable moving average is calculated to establish a dynamic baseline reflecting the underlying trend at the chosen sensitivity level:
baseline = get_ma(src, sensitivity, ma_type)
raw_diff = src - baseline
Then, the average absolute deviation from the baseline is measured over the same period and scaled by a user-defined multiplier to construct an adaptive noise floor, which is the minimum price deviation required to confirm a trend signal:
noise_floor = ta.sma(math.abs(raw_diff), sensitivity) * noise_mult
The trend state is then determined by comparing raw deviation against this noise floor, with a decay mechanism applied when price re-enters the neutral zone to avoid abrupt reversals:
if raw_diff > noise_floor
trend_state := 1
locked_val := raw_diff
else if raw_diff < -noise_floor
trend_state := -1
locked_val := raw_diff
else
locked_val := locked_val * 0.9
The locked deviation value is then normalized by ATR to make the oscillator comparable across instruments and volatility regimes, and smoothed with a short WMA to reduce micro-fluctuations in the final output:
normalized_val = locked_val / ta.atr(sensitivity)
final_osc = ta.wma(normalized_val, 5)
This creates a robust momentum oscillator that only registers trend conditions when price makes structurally significant moves beyond typical noise, while the ATR normalization ensures readings remain meaningful and consistent regardless of the underlying instrument's price scale or volatility level.
🟢 Signal Interpretation
▶ Bullish Trend (Oscillator Rising Above Zero with Bullish Color): When price deviation breaks above the positive noise floor, the oscillator enters bullish mode with green/bullish coloring across all visual elements = Confirmed upward momentum signal for trend-following long positions. The trend remains bullish until price deviation falls below the negative noise floor, allowing traders to stay positioned through normal consolidations without premature exits on minor pullbacks that remain within the noise boundary.
▶ Bearish Trend (Oscillator Falling Below Zero with Bearish Color): When price deviation breaks below the negative noise floor, the oscillator enters bearish mode with red/bearish coloring across all visual elements = Confirmed downward momentum signal for short positions or long exit signals. The trend remains bearish until deviation exceeds the positive noise floor, enabling traders to maintain directional bias through corrective bounces that stay within the threshold boundaries.
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets tailored for different trading styles and timeframes. "Default" delivers balanced trend detection for swing trading on 4-hour and daily charts, filtering minor noise while remaining responsive to meaningful momentum shifts. "Fast Response" uses a reactive EMA baseline with a tighter noise floor for intraday and scalping timeframes, generating earlier signals suited to active traders on 5-minute to 1-hour charts. "Smooth Trend" applies a smooth, lag-reduced HMA baseline with a demanding noise threshold for position trading on daily and weekly charts, confirming only major directional shifts with minimal false positives.
▶ Built-in Alerts: Three alert conditions enable automated monitoring of trend transitions without constant chart observation. "Bullish Trend Signal" triggers when the oscillator first enters a confirmed bullish state, alerting for potential long entries. "Bearish Trend Signal" activates when the oscillator first enters a confirmed bearish state, signaling potential short entries or long exits. "Trend Direction Changed" provides a combined alert for any trend transition regardless of direction, allowing traders to monitor both bullish and bearish opportunities through a single alert setup.
▶ Visual Customization: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) accommodate different chart themes and aesthetic preferences, with coordinated bullish and bearish color schemes applied consistently across all indicator elements. A layered luminance fill system creates graduated visual depth around the main oscillator line using four fill zones at progressively increasing transparency, making trend strength and direction immediately readable at a glance. Optional bar coloring tints price bars with the active trend color during confirmed bullish and bearish periods, providing instant overhead visual confirmation of trend state without requiring direct reference to the oscillator panel below.
Indicator

Self-Playing Snake (For Fun) [UAlgo]Self Playing Snake is a lightweight mini game built entirely in Pine Script for entertainment and UI experimentation. It renders a 15 by 15 grid using PulseWire tables, spawns a snake and a food item, then drives the snake automatically with a simple path selection algorithm. The game updates on the last bar, so it behaves like a small live widget on the chart while keeping the price chart itself visually clean.
The script is intentionally simple and fun. It demonstrates how Pine can be used for stateful simulations, table based rendering, and basic decision making logic without requiring external inputs or manual controls. The snake continuously tries to reach food, grows when it eats, tracks score and high score, and resets automatically when it can no longer make a valid move.
🔹 Features
1) Table Rendered Game Board
The game board is drawn using a table with fixed dimensions. Each cell represents a coordinate on the grid, and the script updates cell background color and emoji text to visualize the snake body, the snake head, and the food.
This makes the game visible directly on the chart without using traditional plotting.
2) Persistent Game State with Custom Types
The script uses two custom types:
Point stores integer x and y coordinates.
GameState stores the snake body as an array of Points, the food position, grid size, score, high score, and a game over flag.
A single persistent GameState variable holds the full game memory across bars.
3) Automatic Food Spawning with Collision Avoidance
Food spawns at a random grid coordinate. The script prevents food from spawning on the snake body by retrying up to 100 times. This keeps gameplay consistent as the snake grows and occupies more space.
4) Greedy AI Movement Logic
Each tick, the snake evaluates four possible moves: up, down, left, right. It rejects moves that would collide with walls or the snake’s body, then chooses the valid move that minimizes Manhattan distance to the food.
This creates a simple, deterministic style of behavior that looks intelligent in open space while still being vulnerable to self trapping as the snake becomes long.
5) Game Loop with Growth and Scoring
On each update step:
A new head point is added to the front of the snake.
If the head reaches the food, score increases and the snake grows by keeping its tail.
If the head does not reach the food, the tail is removed so snake length stays constant.
High score is updated whenever a new best is reached.
6) Automatic Reset on Game Over
If no valid move exists, the state is marked game over. On the next tick, the game resets automatically by restoring the initial snake shape, resetting score, and spawning new food. This keeps the widget running indefinitely without user interaction.
7) Minimal Chart Impact
The script does not draw traditional overlays on the price chart. It includes a fully transparent plot call only to satisfy indicator output requirements while keeping the chart clean.
🔹 Calculations
1) Board Representation and Coordinates
The grid uses integer coordinates from 0 to gridSize minus 1 in both x and y directions. Each Point represents one cell:
type Point
int x
int y
The board is rendered by looping through all cells and deciding what to draw in each position.
2) Snake Body Membership Check
The script checks whether a coordinate is occupied by the snake by scanning the snake array:
method isBody(GameState state, int x, int y) =>
bool found = false
if not na(state.snake) and state.snake.size() > 0
for i = 0 to state.snake.size() - 1
p = state.snake.get(i)
if p.x == x and p.y == y
found := true
break
found
This method is used both for collision checks and for rendering.
3) Manhattan Distance for AI Scoring
The AI uses Manhattan distance to estimate how close a candidate move is to food:
method dist(Point p1, Point p2) =>
math.abs(p1.x - p2.x) + math.abs(p1.y - p2.y)
This favors direct horizontal or vertical progress toward the target.
4) Food Spawning Logic
Food spawns randomly inside the grid, retrying if it lands on the snake:
int newX = int(math.random(0, state.gridSize - 1))
int newY = int(math.random(0, state.gridSize - 1))
int attempts = 0
while state.isBody(newX, newY) and attempts < 100
newX := int(math.random(0, state.gridSize - 1))
newY := int(math.random(0, state.gridSize - 1))
attempts += 1
state.food := Point.new(newX, newY)
5) Reset Initialization
The reset routine clears the snake and creates a small starting body, resets score, clears game over, and spawns food:
state.snake.clear()
state.snake.push(Point.new(7, 7))
state.snake.push(Point.new(7, 8))
state.score := 0
state.isGameOver := false
state.spawnFood()
6) AI Next Move Selection
The AI evaluates four directional moves. It rejects collisions with walls or body and chooses the valid move with the smallest distance:
Point head = state.snake.first()
array directions = array.from(
Point.new(0, -1),
Point.new(0, 1),
Point.new(-1, 0),
Point.new(1, 0)
)
float minDistance = 1000.0
Point bestMove = na
for i = 0 to directions.size() - 1
Point dir = directions.get(i)
int nextX = head.x + dir.x
int nextY = head.y + dir.y
bool isWallHit = nextX < 0 or nextX >= state.gridSize or nextY < 0 or nextY >= state.gridSize
bool isBodyHit = state.isBody(nextX, nextY)
if not isWallHit and not isBodyHit
Point potentialMove = Point.new(nextX, nextY)
float d = potentialMove.dist(state.food)
if d < minDistance
minDistance := d
bestMove := potentialMove
If bestMove remains na, there is no safe move and the game ends.
7) Tick Update Rules
The tick method controls the game loop:
If game over, reset.
Else decide next move.
If no move, set game over.
Else add head, then check food:
If food eaten, increment score, update high score, and spawn new food.
If not eaten, remove tail.
8) Rendering Logic with Tables
On the last bar, the script renders each cell:
Food cell draws an apple emoji and red tint.
Snake body draws a green square emoji.
Snake head draws a different emoji and brighter tint.
It also renders a small UI table that displays the current score and best score.
The script updates continuously on the last bar, making it behave like a live widget. Indicator

Adaptive Entropy Trend [QuantAlgo]🟢 Overview
Adaptive Entropy Trend is a trend-following indicator built on Shannon information theory rather than conventional price averaging. It quantifies the statistical disorder of recent log returns to determine whether the market is in a directional regime or a random one, then feeds this entropy reading into every layer of the system simultaneously, helping traders identify directional shifts that are validated by both low-entropy momentum conditions and genuine volatility expansion across different timeframes and markets.
🟢 How It Works
The foundation of the indicator is a per-bar entropy calculation built from the distribution of log returns over the lookback window. Log returns are computed and their range is divided into equal-width histogram bins:
logReturn = math.log(close / close )
minReturn = ta.lowest(logReturn, lookbackLen)
maxReturn = ta.highest(logReturn, lookbackLen)
returnRange = maxReturn - minReturn
Each historical return within the lookback is assigned to a bin, building a frequency distribution. Shannon entropy is then calculated from the probability of each bin, measuring how uniformly returns are spread across the range:
probability = array.get(binCounts, i) / lookbackLen
if probability > 0
entropy := entropy - probability * math.log(probability) / math.log(2)
A uniform distribution produces maximum entropy, reflecting a chaotic, non-directional market. A concentrated distribution produces low entropy, reflecting a market where returns are clustering in a consistent direction. The raw entropy is normalized against the theoretical maximum for the bin count to produce a stable 0-1 score:
normalizedEntropy = maxEntropy > 0 ? entropy / maxEntropy : 0.5
This score is then wired directly into the EMA smoothing factor. Higher entropy lengthens the effective period of the EMA, insulating it from noise. Lower entropy shortens it, allowing the EMA to track price closely during genuine trends:
adaptiveAlpha = 2.0 / (lookbackLen * (0.3 + normalizedEntropy * 1.4) + 1.0)
adaptiveEma := na(adaptiveEma) ? close : adaptiveEma + adaptiveAlpha * (close - adaptiveEma)
The same entropy reading drives band width through an inverted trend strength factor. Unlike volatility-based bands that widen during noise, these bands widen specifically during trending conditions and tighten during choppy ones:
trendStrength = 1.0 - normalizedEntropy
fastBandWidth = atr * fastMultiplier * (0.5 + trendStrength)
slowBandWidth = atr * slowMultiplier * (0.5 + trendStrength)
Finally, trend state is determined when price breaks beyond the inner bands, and transitions are tracked for alert conditions:
if close > innerUpper
trendDirection := 1
else if close < innerLower
trendDirection := -1
trendTurnedBullish = trendDirection == 1 and trendDirection != 1
trendTurnedBearish = trendDirection == -1 and trendDirection != -1
This creates a self-regulating trend system where the EMA baseline, the trigger threshold, and the visual envelope all adapt together from the same entropy source, rather than using a fixed center with adaptive edges or vice versa.
🟢 Signal Interpretation
▶ Bullish Trend (Price Above Inner Upper Band, Green): When price closes above the inner upper band, the indicator switches to bullish mode with bullish coloring across all visual elements = Confirmed uptrend signal for trend-following long positions. Because the inner band expands in low-entropy trending conditions, a bullish confirmation in a genuinely directional market requires a more meaningful breakout than in a noisy one. The trend remains bullish until price breaks below the inner lower band, allowing traders to stay positioned through normal pullbacks that remain within the band range.
▶ Bearish Trend (Price Below Inner Lower Band, Red): When price closes below the inner lower band, the indicator switches to bearish mode with bearish coloring throughout all visual elements = Confirmed downtrend signal for short positions or long exit signals. The adaptive band floor ensures the trigger threshold in choppy, high-entropy markets is tighter, reducing the risk of false breakdowns on thin directional moves. The trend remains bearish until price breaks above the inner upper band.
▶ Neutral Zone (Price Between Inner Bands): When price trades between the inner upper and lower bands, the indicator holds its previous trend direction = Continuation of existing trend during consolidation or normal volatility retracements. This prevents whipsaws during sideways action by requiring price to make a statistically meaningful move beyond the entropy-scaled band boundaries rather than reacting to minor crosses of the adaptive EMA centerline.
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets for different trading approaches and timeframes. "Default" provides balanced trend detection for swing trading on 4-hour and daily charts, "Fast Response" delivers quicker trend signals for intraday trading on 1-minute to 1-hour charts, and "Smooth Trend" focuses on major trend changes for position trading on daily to weekly timeframes.
▶ Built-in Alerts: Three alert conditions enable automated monitoring of trend changes without constant chart watching. "Bullish Trend Signal" triggers when the indicator switches to bullish mode after price breaks above the inner upper band, alerting for potential long entries. "Bearish Trend Signal" activates when the indicator switches to bearish mode after price breaks below the inner lower band, signaling potential short entries or long exits. "Trend Direction Changed" provides a combined alert for any trend transition regardless of direction, allowing traders to monitor both bullish and bearish opportunities with a single alert setup.
▶ Visual Customization: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) accommodate different chart backgrounds and aesthetic preferences, with coordinated bullish, bearish, and neutral color schemes applied across all indicator elements. Inner and outer band fills create a two-layer gradient envelope around the adaptive EMA, with the inner zone between the two bands rendered slightly more transparent than the outer zone to preserve natural depth, both controlled by a single fill transparency input (0-100%) so the visual weight of the envelope can be adjusted without disrupting the gradient relationship. Optional bar coloring tints price bars with trend-appropriate colors during bullish and bearish periods, enabling instant visual confirmation of trend state across multiple timeframes without switching between chart and indicator panels.
Indicator

Indicator

Indicator

Indicator

Relative Valuation Oscillator [QuantAlgo]🟢 Overview
The Relative Valuation Oscillator identifies statistical price deviations from fair value using logarithmic price analysis and standard deviation bands. It calculates how far current price has deviated from its mean on a logarithmic scale, normalized by volatility, to generate a centered oscillator that highlights periods when price is statistically stretched above or below its historical average, helping traders identify potential mean reversion opportunities and extreme valuation conditions across different timeframes and markets.
🟢 How It Works
The indicator's core methodology lies in its statistical approach to price valuation, where deviations are measured using logarithmic returns and normalized by standard deviation:
log_price = math.log(close)
mean_log_price = ta.sma(log_price, lookback_period)
standard_deviation = ta.stdev(log_price, lookback_period)
valuation_score = (log_price - mean_log_price) / standard_deviation
First, the script converts price to logarithmic form to account for percentage-based price movements rather than absolute dollar changes, ensuring the indicator works consistently across different price levels and asset classes.
Then, it calculates the mean log price over the specified lookback period to establish a baseline fair value reference:
mean_log_price = ta.sma(log_price, lookback_period)
Next, standard deviation measurement quantifies the typical volatility of log price around this mean, providing a statistical framework for defining normal versus extreme price behavior:
standard_deviation = ta.stdev(log_price, lookback_period)
The valuation score is then derived by measuring how many standard deviations the current log price sits from its mean, creating a normalized oscillator that fluctuates around zero:
valuation_score = (log_price - mean_log_price) / standard_deviation
Finally, threshold-based signal detection identifies extreme conditions when the valuation score exceeds user-defined standard deviation multiples:
is_overvalued = valuation_score > threshold_mult
is_undervalued = valuation_score < -threshold_mult
This creates a statistical mean reversion system that identifies when price has deviated significantly from its historical average on a volatility-adjusted basis, providing traders with objective measurements of relative over or undervaluation.
🟢 Signal Interpretation
▶ Undervalued Zone (Below Negative Threshold): Oscillator falling below the negative threshold line indicates price has deviated significantly below its statistical mean = Potential long/buy opportunities for mean reversion strategies
▶ Overvalued Zone (Above Positive Threshold): Oscillator rising above the positive threshold line indicates price has deviated significantly above its statistical mean = Potential short/sell or profit-taking opportunities
▶ Fair Value Range (Between Thresholds): Oscillator remaining between positive and negative threshold lines indicates price is trading within normal statistical bounds. Within this range, the zero line acts as a directional filter: oscillator above zero but below the upper threshold suggests bullish trend/momentum with price trading above its statistical mean = Trend-following long positions can be maintained; oscillator below zero but above the lower threshold suggests bearish trend/momentum with price trading below its statistical mean = Trend-following short positions can be maintained. The oscillator can remain in these directional zones during sustained trends until mean reversion occurs, signaled by crosses back toward zero or transitions to the opposite extreme threshold.
▶ Zero Line Crosses: Oscillator crossing above zero indicates transition from below-average to above-average valuation, confirming shift to bullish momentum = Potential trend-following long entry; crossing below zero indicates transition from above-average to below-average valuation, confirming shift to bearish momentum = Potential trend-following short entry or long exit. These crosses can signal both the start of directional trends and early mean reversion from extreme conditions.
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets for different trading approaches and timeframes. "Default" provides balanced sensitivity for swing trading on 4-hour and daily charts, generating signals at statistically significant deviations. "Fast Response" delivers more frequent signals for intraday trading on 5-minute to 1-hour charts, reacting quickly to short-term deviations with increased signal frequency. "Smooth Trend" focuses on major extremes for position trading on daily to weekly timeframes, filtering noise to identify only the most significant statistical outliers.
▶ Built-in Alerts: Five alert conditions enable automated monitoring of valuation extremes and transitions. "Overvalued Threshold Crossed" triggers when the oscillator crosses above the positive threshold, signaling potential overvaluation. "Undervalued Threshold Crossed" activates when the oscillator crosses below the negative threshold, signaling potential undervaluation. "Crossed Above Fair Value (0)" and "Crossed Below Fair Value (0)" provide alerts for zero line transitions, indicating shifts between above-average and below-average valuation. "Any Extreme Valuation" offers a combined alert for any threshold breach regardless of direction, allowing traders to monitor both extremes with a single alert setup.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, with distinct colors for overvalued, undervalued, and fair value conditions. Optional background highlighting with adjustable transparency (0-100%) tints the main chart background during extreme valuation periods, providing immediate visual context without requiring continuous oscillator monitoring. Optional overlay signals display small circle markers directly on the price chart above bars during overvaluation and below bars during undervaluation, allowing correlation of statistical extremes with specific price levels and candlestick patterns.
Indicator

Adaptive Kinetic Ribbon [QuantAlgo]🟢 Overview
The Adaptive Kinetic Ribbon indicator synthesizes price velocity and volatility dynamics to identify trend direction, momentum strength, and acceleration phases across varying market conditions. It combines velocity-based momentum measurement, adaptive volatility weighting, dual-speed ribbon analysis, and acceleration-deceleration detection into a unified visual system that quantifies periods of sustained directional movement and momentum shifts, helping traders and investors identify trend continuation and reversal signals across various timeframes and asset classes.
🟢 How It Works
The indicator's core methodology lies in its adaptive kinetic approach, where velocity and volatility components are calculated dynamically and then smoothed through an adaptive alpha mechanism.
First, Velocity is measured to capture raw directional momentum by calculating the net price change over the lookback period:
velocity = source - source
This creates a momentum vector that quantifies how far and in which direction price has moved, providing the foundation for understanding trend strength and establishing whether the market is in a sustained directional phase.
Then, Volatility is computed to evaluate price variability and market noise by analyzing the standard deviation of bar-to-bar price changes:
volatility = ta.stdev(source - source , length) * mult
The volatility sensitivity multiplier allows traders to adjust how responsive the indicator is to market noise, with higher values creating faster adaptation during volatile periods and lower values maintaining stability during choppy conditions.
Next, Adaptive Alpha is calculated to create a dynamic smoothing coefficient that automatically adjusts based on the relationship between velocity and volatility:
adaptive_alpha = math.abs(velocity) / (math.abs(velocity) + volatility)
This alpha value ranges from 0 to 1, where values closer to 1 indicate strong, clear directional movement (high velocity relative to volatility), causing the indicator to respond quickly, while values closer to 0 indicate noisy, range-bound conditions (high volatility relative to velocity), causing the indicator to smooth more heavily and filter out false signals.
Following this, the Kinetic Line is constructed using exponential smoothing with the adaptive alpha coefficient:
var float kinetic_line = na
kinetic_line := na(kinetic_line ) ? source : kinetic_line + adaptive_alpha * (source - kinetic_line )
This creates an adaptive moving average that automatically adjusts its responsiveness: during strong trends with clear velocity, it tracks price closely like a fast EMA; during choppy, volatile periods, it smooths heavily like a slow SMA, providing optimal trend identification across varying market regimes without manual parameter adjustment.
Then, Ribbon Lines are generated by applying additional moving average smoothing to the kinetic line at two different speeds:
ribbon_fast = ma(kinetic_line, ribbon_fast_length, ma_type)
ribbon_slow = ma(kinetic_line, ribbon_slow_length, ma_type)
The dual-ribbon structure creates a visual envelope around the kinetic line, where the fast ribbon responds quickly to kinetic changes while the slow ribbon provides trend confirmation, with crossovers between these ribbons generating primary trend reversal signals.
Finally, Trend State and Acceleration are determined by analyzing the relative positioning and directional movement of the ribbon lines:
trend_up = ribbon_fast > ribbon_slow
acceleration = ribbon_fast > ribbon_fast
ribbonColor = trend_up ?
acceleration ? bullAccel : bullDecel :
not acceleration ? bearAccel : bearDecel
This creates a four-state classification system that distinguishes between bullish acceleration (uptrend strengthening), bullish deceleration (uptrend weakening), bearish acceleration (downtrend strengthening), and bearish deceleration (downtrend weakening), providing traders with nuanced momentum insights beyond simple bullish/bearish binary signals.
🟢 Signal Interpretation
▶ Bullish Acceleration (Bright Green): Fast ribbon above slow ribbon AND fast ribbon rising, indicating confirmed uptrend with building momentum = Strongest bullish condition, ideal for new long entries, adding to positions, or holding existing longs with confidence
▶ Bullish Deceleration (Dark Green): Fast ribbon above slow ribbon BUT fast ribbon falling, indicating uptrend intact but momentum weakening = Caution signal for longs, potential trend exhaustion developing, consider tightening stops or taking partial profits
▶ Bearish Acceleration (Bright Red): Fast ribbon below slow ribbon AND fast ribbon falling, indicating confirmed downtrend with building momentum = Strongest bearish condition, ideal for new short entries, exiting longs, or maintaining defensive positioning
▶ Bearish Deceleration (Dark Red): Fast ribbon below slow ribbon BUT fast ribbon rising, indicating downtrend intact but momentum weakening = Caution signal for shorts, potential trend exhaustion developing, prepare for possible reversal or consolidation
▶ Bullish Crossover: Fast ribbon crosses above slow ribbon, signaling trend reversal from bearish to bullish and initiation of new upward momentum phase = Primary buy signal, entry opportunity for trend-following strategies, exit signal for short positions
▶ Bearish Crossover: Fast ribbon crosses below slow ribbon, signaling trend reversal from bullish to bearish and initiation of new downward momentum phase = Primary sell signal, entry opportunity for short strategies, exit signal for long positions
▶ Ribbon Spread Width: Distance between fast and slow ribbons indicates trend strength and conviction, where wider spreads suggest strong, sustained directional movement with low reversal probability, while tight or converging ribbons indicate weak trends, consolidation, or impending reversal conditions
▶ Bar Color Alignment: When bar coloring is enabled, candlestick colors mirror the ribbon state providing immediate visual confirmation of momentum conditions directly on price action, eliminating the need to reference the indicator separately and enabling faster decision-making during active trading
🟢 Features
▶ Preconfigured Presets: Three optimized parameter configurations accommodate different trading styles, timeframes, and market analysis approaches: "Default" provides balanced trend identification suitable for swing trading on 4-hour and daily charts, "Fast Response" delivers heightened sensitivity optimized for intraday trading and scalping on 5-minute to 1-hour charts, and "Smooth Trend" offers conservative trend identification ideal for position trading and long-term analysis on daily to weekly charts.
▶ Built-in Alerts: Three alert conditions enable comprehensive automated monitoring of trend reversals and momentum transitions. "Bullish Crossover" triggers when the fast ribbon crosses above the slow ribbon, signaling the shift from downtrend to uptrend and the beginning of bullish momentum building. "Bearish Crossover" activates when the fast ribbon crosses below the slow ribbon, signaling the shift from uptrend to downtrend and the beginning of bearish momentum building. "Any Ribbon Crossover" provides a combined notification for either bullish or bearish crossover regardless of direction, useful for general trend reversal monitoring and ensuring no momentum shift goes unnoticed.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, ensuring optimal contrast and immediate identification of acceleration versus deceleration states across various devices and screen sizes. Each preset uses distinct colors for the four momentum states (bullish acceleration, bullish deceleration, bearish acceleration, bearish deceleration) with proper visual hierarchy. Optional bar coloring with adjustable transparency provides instant visual context of current momentum state and trend direction without switching between the price pane and indicator pane, enabling traders and investors to immediately assess trend positioning and acceleration dynamics while analyzing price action patterns and support/resistance levels.
Indicator

Indicator

Pinescript Custom Performance BoostThis small script is a custom function that works similarly to the built-in calc_bars_count and max_bars_back functions, but can be used far more flexibly and significantly reduces the required computation time of Pine Script scripts.
The advantages over calc_bars_count are substantial.
The standard function works with a fixed value, e.g. calc_bars_count = 20000. The custom function, on the other hand, works on a percentage basis, e.g. with 20% of the total available chart bars.
In addition, calc_bars_count always affects the entire code, while the custom function can be applied selectively to specific parts of the script.
These two differences enable a much more flexible and efficient usage.
Fixed number of bars vs. percentage-based limitation:
The number of available bars varies greatly, not only depending on the ticker and timeframe used, but also on the PulseWire subscription (approx. 5,000–40,000 historical bars).
For example, when using calc_bars_count = 20000, only charts that have more than 20,000 candles benefit. If the available number of bars is lower, there is no performance benefit at all until the value is changed after the first slow calculation.
When using the custom function with, for example, 50%, only 50% of the available bars are always calculated, regardless of how many bars are available. This results in a performance gain with shorter calculation times regardless of the chart.
Entire code vs. partial code sections:
calc_bars_count = 20000 affects the entire code globally, meaning the script processes data from only those 20,000 bars.
The custom function, however, can be used selectively for specific sections of the code. This makes it possible to continue accessing certain values across all available bars, while limiting only the truly computation-intensive parts of the script to a percentage-based range.
In this way, computation time can be drastically reduced without restricting the overall size of the data sets.
It is also possible to imitate max_bars_back and selectively limit specific values instead of limiting all of them.
I hope this is useful to some of you. Have fun with it! Indicator

ATR ZLEMA [QuantAlgo]🟢 Overview
The ATR ZLEMA indicator identifies trend direction and reversal points using a Zero Lag Exponential Moving Average (ZLEMA) combined with volatility-adjusted dynamic trailing stops. It eliminates the inherent lag of traditional moving averages while incorporating Average True Range (ATR) volatility measurement to create adaptive support and resistance levels that automatically adjust to market conditions, with optional noise filtering to reduce whipsaws in choppy markets, helping traders and investors identify trend changes, maintain positions during trending markets, and exit when momentum shifts across multiple timeframes and asset classes.
🟢 How It Works
The indicator's core methodology lies in its zero-lag trend detection system combined with volatility-adaptive trailing stops, where the ZLEMA eliminates moving average lag while ATR-based bands provide dynamic support and resistance levels:
lag = math.floor((zlemaLength - 1) / 2)
rawZlema = ta.ema(source + (source - source ), zlemaLength)
The Zero Lag EMA calculation uses lag reduction through data compensation, adding the difference between current price and lagged price to eliminate the delay inherent in traditional exponential moving averages, providing faster response to trend changes while maintaining smoothness.
The script incorporates an optional ATR-based noise filter that prevents the ZLEMA from updating during insignificant price movements, helping to reduce false signals in choppy, range-bound markets:
if enableNoiseFilter
noiseThreshold = atr * noiseFilter
priceChange = math.abs(rawZlema - zlema)
if priceChange > noiseThreshold
zlema := rawZlema
First, the indicator calculates the Average True Range to measure current market volatility, then applies a user-defined multiplier to determine the distance of the trailing stop from the ZLEMA:
atr = ta.rma(ta.tr(true), atrLength)
atrBand = atr * atrMultiplier
Next, dynamic trend detection occurs through a state-based system where the indicator tracks whether the ZLEMA is above or below the ATR trailing line, automatically adjusting the trailing stop position:
if trend == 1
if zlema < zlemaATR
trend := -1
zlemaATR := zlema + atrBand
else
zlemaATR := math.max(zlemaATR, zlema - atrBand)
The ATR trailing line acts as a volatility-adjusted stop that follows the ZLEMA during trends but never moves against the trend direction. It ratchets upward with the ZLEMA in uptrends and ratchets downward in downtrends, creating a protective barrier that adapts to market volatility.
Finally, trend reversal signals are generated when the ZLEMA crosses the ATR trailing line, indicating a shift in market momentum:
bullSignal = trend == 1 and trend == -1
bearSignal = trend == -1 and trend == 1
This creates a volatility-adaptive trend-following system that combines ZLEMA with dynamic support/resistance levels and optional noise filtering, providing traders with responsive directional signals and automatic stop-loss levels that adjust to both price momentum and market volatility conditions.
🟢 Signal Interpretation
▶ Bullish Trend (Green): ZLEMA trading above ATR trailing line with indicator showing bullish color, indicating established upward momentum with zero-lag confirmation = Long/Buy opportunities
▶ Bearish Trend (Red): ZLEMA trading below ATR trailing line with indicator showing bearish color, indicating established downward momentum with zero-lag confirmation = Short/Sell opportunities
▶ ATR Trailing Line as Dynamic Support: In uptrends, the trailing line acts as volatility-adjusted support level that rises with ZLEMA, never declining = Use as potential stop-loss reference for long positions = ZLEMA holding above indicates trend strength and momentum continuation
▶ ATR Trailing Line as Dynamic Resistance: In downtrends, the trailing line acts as volatility-adjusted resistance level that falls with ZLEMA, never rising = Use as potential stop-loss reference for short positions = ZLEMA holding below indicates trend weakness and momentum continuation
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets for different trading styles and market conditions. "Default" provides balanced configuration suitable for swing trading on daily and 4-hour charts with standard ZLEMA and ATR periods, moderate multiplier, and moderate noise filtering that works across most market conditions. "Fast Response" delivers aggressive configuration designed for intraday trading and scalping on 5-minute to 1-hour charts with shorter ZLEMA period for quick trend detection, reduced ATR period for rapid volatility adaptation, tighter multiplier for early entries/exits, and minimal noise filtering for maximum responsiveness. This is ideal for active traders monitoring positions closely but expect more frequent signals and potential whipsaws in choppy conditions. "Smooth Trend" focuses on conservative configuration for position trading and long-term trend following on daily to weekly charts with extended ZLEMA period for smoother trend identification, longer ATR period for stable volatility measurement, wide multiplier to filter minor corrections, and aggressive noise filtering to ensure only strong sustained trends trigger signals. This is best for patient traders focused on major trend moves with fewer reversals.
▶ Built-in Alerts: Three alert conditions enable comprehensive automated monitoring of trend changes and zero-lag momentum shifts. "Bullish Trend" triggers when the ZLEMA crosses above the ATR trailing line and trend state changes from bearish to bullish, signaling potential long entry opportunities with lag-eliminated confirmation. "Bearish Trend" activates when the ZLEMA crosses below the ATR trailing line and trend state changes from bullish to bearish, signaling potential short entry or long exit points with immediate momentum detection. "Any Trend Change" provides a combined alert for any trend reversal regardless of direction, allowing traders to be notified of all zero-lag momentum shifts without setting up separate alerts. These notifications enable traders to capitalize on trend changes and protect positions without continuous chart monitoring, leveraging the indicator's zero-lag technology for faster trend change alerts.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, ensuring optimal contrast for identifying bullish versus bearish trends across various trading environments. The adjustable cloud fill transparency control (0-100%) allows fine-tuning of the gradient area prominence between the ATR trailing line and ZLEMA, with higher transparency values (70-95) creating subtle background context without overwhelming the chart while lower values (20-40) produce bold, prominent trend zone emphasis for instant recognition. Optional bar coloring with adjustable transparency (0-100%) extends the trend color directly to the price bars themselves based on ZLEMA trend state, providing immediate visual reinforcement of current trend direction without requiring reference to the indicator lines.
Indicator

Educational Market Structure & Trend Context🔍 Overview
This time-limited indicator is designed for educational and analytical purposes only. It helps users visually study price structure behavior and trend context by marking key structural points on the chart and overlaying a trend reference line. The indicator does not generate trading signals, predictions, or recommendations.
⚙️ How the Indicator Works
The script analyzes price action over a user-defined lookback period to identify local structural points:
Higher Highs within the selected range
Lower Lows within the selected range
These points are plotted as simple visual markers to help users understand how price is evolving over time.
In addition, a moving average is applied to provide broader trend context.
🟢 Green Markers (Structure Strength)
Appear when price forms a local higher high within the lookback window
Represent relative strength in price structure
They are not buy signals and do not indicate future movement
🔴 Red Markers (Structure Weakness)
Appear when price forms a local lower low within the lookback window
Represent relative weakness in price structure
They are not sell signals and do not indicate reversals
➖ Grey Line (Trend Context Line)
This line is a moving average calculated over a fixed period
It provides trend context only, helping users visually distinguish between upward and downward environments
It does not act as support, resistance, or entry guidance
🎨 Background Shading (Optional Context)
A subtle background color may appear depending on price position relative to the trend line
This shading is purely visual context, not a signal or confirmation
🎯 Purpose & Benefits
Helps users study market structure in a clean and simple way
Encourages price-action awareness instead of signal dependency
Supports manual analysis, learning, and chart reading skills
Keeps the chart minimal, non-predictive, and professional
⚠️ Important Notes
This indicator does not provide buy/sell signals
No targets, stop levels, or profit expectations are included
Past structure points do not predict future outcomes
Users should apply their own analysis and risk management Indicator

Smart Money Flow Signals [QuantAlgo]🟢 Overview
The Smart Money Flow Signals indicator synthesizes significant volume-price dynamics through multi-component analysis to identify potential accumulation and distribution phases driven by substantial market participants. It combines Money Flow Index momentum, Chaikin Money Flow accumulation patterns, volume-weighted price momentum, and buying/selling pressure metrics into a unified composite oscillator that quantifies periods of concentrated capital movement, helping traders and investors identify conditions where significant volume participants may be actively positioning across multiple market conditions and timeframes.
🟢 How It Works
The indicator's core methodology lies in its weighted composite approach, where multiple volume-price components are calculated sequentially and then integrated to create a comprehensive significant flow activity signal.
First, the Money Flow Index (MFI) is calculated to measure buying and selling pressure by incorporating volume into price momentum analysis:
raw_money_flow = source * volume
positive_flow = source >= source ? raw_money_flow : 0
negative_flow = source < source ? raw_money_flow : 0
positive_money_flow = math.sum(positive_flow, mfi_period)
negative_money_flow = math.sum(negative_flow, mfi_period)
money_flow_index = 100 - 100 / (1 + positive_money_flow / negative_money_flow)
This creates an RSI-style momentum indicator that tracks whether money (price × volume) is flowing into or out of the asset, with values ranging from 0 to 100 where readings above 50 suggest buying pressure dominance.
Then, Chaikin Money Flow (CMF) is computed to evaluate accumulation and distribution by analyzing where prices close within each bar's range, weighted by volume:
money_flow_multiplier = high != low ? (close - low - (high - close)) / (high - low) : 0
money_flow_volume = money_flow_multiplier * volume
volume_sma = ta.sma(volume, trend_period)
chaikin_money_flow = volume_sma != 0 ? ta.sma(money_flow_volume, trend_period) / volume_sma : 0
Positive CMF values indicate accumulation (closes near the high of the range), while negative values indicate distribution (closes near the low of the range), with volume weighting emphasizing periods of significant participation.
Next, Volume Analysis is performed to quantify current volume intensity relative to historical averages:
volume_average = ta.sma(volume, trend_period)
volume_strength = volume_average != 0 ? volume / volume_average : 1
volume_weight = math.log(volume_strength + 1)
The logarithmic transformation creates a volume weight that amplifies signals during high-volume periods while preventing extreme volume spikes from overwhelming the composite calculation.
Following this, Buy/Sell Pressure is quantified by comparing cumulative volume during bullish versus bearish candles:
buying_pressure = math.sum(volume * (close >= open ? 1 : 0), trend_period)
selling_pressure = math.sum(volume * (close < open ? 1 : 0), trend_period)
pressure_ratio = (buying_pressure - selling_pressure) / (buying_pressure + selling_pressure) * 100
This creates a directional pressure ratio that reveals whether significant participants are predominantly buying or selling, expressed as a percentage between -100 (all selling) and +100 (all buying).
Then, Volume-Weighted Momentum is calculated through an exponential smoothing channel that adjusts price deviation based on volume intensity:
exponential_smooth_average = ta.ema(source, momentum_channel_period)
deviation = ta.ema(math.abs(source - exponential_smooth_average), momentum_channel_period)
channel_index = deviation != 0 ? (source - exponential_smooth_average) / (0.015 * deviation) * (1 + volume_weight * 0.5) : 0
This channel index measures how far price has deviated from its exponential average relative to typical deviation, with the volume weight multiplier (1 + volume_weight * 0.5) amplifying the signal when significant volume accompanies the price movement.
Finally, the Composite Wave is constructed by combining all components with specific weighting to create the final oscillator:
momentum_wave = ta.ema(channel_index, trend_period)
money_flow_wave = (money_flow_index - 50) * 1.2
chaikin_flow_wave = chaikin_money_flow * 100
composite_wave = momentum_wave * 0.5 + chaikin_flow_wave * 0.3 + money_flow_wave * 0.2
smoothed_wave = ta.sma(composite_wave, signal_smoothing)
This creates a multi-dimensional volume flow oscillator that combines price-volume momentum, accumulation-distribution patterns, and buying-selling pressure into a single signal, providing traders with probabilistic insights into periods of concentrated market activity and directional bias based on weighted component convergence.
🟢 Signal Interpretation
▶ Positive Values (Above Zero, Green): Composite money flow above equilibrium indicating net accumulation pressure, positive buying volume dominance, and bullish volume-price alignment = Favorable conditions for long positions, significant capital flowing into the asset = Buy/hold opportunities
▶ Negative Values (Below Zero, Red): Composite money flow below equilibrium indicating net distribution pressure, negative selling volume dominance, and bearish volume-price alignment = Unfavorable conditions for long positions, significant capital flowing out of the asset = Sell/short opportunities
▶ Extreme Overbought Zone: Excessive bullish money flow indicating potential accumulation exhaustion, where buying pressure may have reached unsustainable levels with elevated reversal risk = Caution on new longs, potential distribution phase beginning, profit-taking zone for existing positions
▶ Extreme Oversold Zone: Excessive bearish money flow indicating potential distribution exhaustion, where selling pressure may have reached unsustainable levels with elevated reversal risk = Caution on new shorts, potential accumulation phase beginning, buying opportunity zone for contrarian entries
▶ Smoothed Trend Line (White) Alignment: When the smoothed trend line confirms the composite wave direction, it validates the underlying volume-price trend and filters false signals caused by short-term noise
▶ Volume Intensity Correlation: Gradient intensity (color saturation) reflects combined wave strength, volume participation, and directional alignment, where darker/more saturated colors indicate stronger concentrated activity and higher-probability directional moves
🟢 Features
▶ Preconfigured Presets: Three optimized parameter configurations accommodate different trading styles, timeframes, and market analysis approaches.
1. "Default" provides balanced volume flow measurement suitable for swing trading on 4-hour and daily charts, offering moderate responsiveness to money flow shifts with standard RSI-equivalent MFI period and moderate smoothing for most market conditions.
2. "Fast Response" delivers heightened sensitivity optimized for active intraday trading and scalping on 1-minute to 1-hour charts, using compressed calculation periods across all components and minimal smoothing to capture rapid volume flow changes and quick trend shifts as they develop, ideal for early entry/exit opportunities with acceptance of increased signal frequency during consolidation.
3. "Smooth Trend" offers conservative extreme identification ideal for position trading and long-term analysis on daily to weekly charts, employing extended periods across all money flow components with substantial smoothing to filter short-term noise and isolate only strong, sustained accumulation and distribution phases driven by significant volume participants.
▶ Built-in Alerts: Seven alert conditions enable comprehensive automated monitoring of significant money flow transitions and extreme market states.
1. "Bullish Flow" triggers when the composite wave crosses above zero, signaling the shift from distribution to accumulation and concentrated buying activity beginning.
2. "Bearish Flow" activates when the composite wave crosses below zero, signaling the shift from accumulation to distribution and concentrated selling activity starting.
3. "Any Flow Direction Change" provides a combined notification for either bullish or bearish crossover regardless of direction, useful for general money flow momentum shifts.
4. "Extreme Overbought" alerts when the composite wave reaches or exceeds the overbought threshold (default +60), indicating excessive buying pressure and potential exhaustion.
5. "Extreme Oversold" notifies when the composite wave reaches or falls below the oversold threshold (default -60), indicating excessive selling pressure and potential capitulation.
6. "Overbought Reversal" triggers specifically when the wave crosses back down through the overbought level after being extended, signaling the beginning of distribution from extreme levels.
7. "Oversold Reversal" activates when the wave crosses back up through the oversold level after being extended, signaling the beginning of accumulation from extreme levels.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, ensuring optimal contrast and immediate identification of bullish versus bearish volume flow conditions across various devices and screen sizes. Optional bar coloring provides instant visual context of current significant volume activity intensity and direction without switching between the price pane and indicator pane, enabling traders and investors to immediately assess volume-price positioning dynamics while analyzing price action.
Indicator

ATR Supertrend [QuantAlgo]🟢 Overview
The ATR Supertrend indicator identifies trend direction and reversal points using volatility-adjusted dynamic support and resistance levels. It combines Average True Range (ATR) volatility measurement with adaptive price bands and EMA smoothing to create trailing stop levels that automatically adjust to market conditions, helping traders and investors identify trend changes, maintain positions during trending markets, and exit when momentum shifts across multiple timeframes and asset classes.
🟢 How It Works
The indicator's core methodology lies in its volatility-adaptive band system, where dynamic support and resistance levels are calculated based on market volatility and price movement:
smoothedSource = ta.ema(source, smoothingPeriod)
atr = ta.rma(ta.tr(true), atrLength) * atrMultiplier
The script uses ATR-based bands that expand and contract with market volatility, ensuring the indicator adapts to different market conditions rather than using fixed price distances:
if trend == 1
supertrend := math.max(supertrend, smoothedSource - atr)
else
supertrend := math.min(supertrend, smoothedSource + atr)
First, it applies optional EMA smoothing to the price source to reduce noise and filter out minor price fluctuations that could trigger premature trend changes, allowing traders to focus on genuine momentum shifts.
Then, the ATR calculation measures market volatility using the Average True Range over the specified lookback period, multiplied by the user-defined factor to set the band distance:
atr = ta.rma(ta.tr(true), atrLength) * atrMultiplier
Next, dynamic trend detection occurs through a state-based system where the indicator tracks whether price is in an uptrend or downtrend, automatically adjusting the Supertrend line position:
if trend == 1
if smoothedSource < supertrend
trend := -1
supertrend := smoothedSource + atr
The Supertrend line can act as a trailing stop that follows price during trends but never moves against the trend direction, i.e., it ratchets upward with price in uptrends and ratchets downward with price in downtrends.
Finally, trend reversal signals are generated when price crosses the Supertrend line, indicating a shift in market momentum:
bullSignal = trend == 1 and trend == -1
bearSignal = trend == -1 and trend == 1
This creates a volatility-adaptive trend-following system that combines dynamic support/resistance levels with momentum confirmation, providing traders with clear directional signals and automatic stop-loss levels that adjust to changing market conditions.
🟢 Signal Interpretation
▶ Bullish Trend (Green): Price trading above Supertrend line with indicator showing bullish color, indicating established upward momentum = Long/Buy opportunities
▶ Bearish Trend (Red): Price trading below Supertrend line with indicator showing bearish color, indicating established downward momentum = Short/Sell opportunities
▶ Supertrend Line as Dynamic Support: In uptrends, the Supertrend line can act as trailing support level that rises with price, never declining = Use as potential stop-loss reference for long positions = Price holding above indicates trend strength
▶ Supertrend Line as Dynamic Resistance: In downtrends, the Supertrend line can act as trailing resistance level that falls with price, never rising = Use as potential stop-loss reference for short positions = Price holding below indicates trend weakness
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets for different trading approaches. "Default" provides balanced trend detection for swing trading on daily/4-hour charts with moderate sensitivity. "Fast Response" delivers quick trend change detection for intraday trading on 5-minute to 1-hour charts, capturing moves early with increased whipsaw potential. "Smooth Trend" focuses on strong sustained trends for position trading on daily/weekly timeframes, filtering noise to identify only major trend shifts.
▶ Built-in Alerts: Three alert conditions enable comprehensive automated monitoring of trend changes and momentum shifts. "Bullish Trend" triggers when price crosses above the Supertrend line and the trend state changes from bearish to bullish, signaling potential long entry opportunities. "Bearish Trend" activates when price crosses below the Supertrend line and the trend state changes from bullish to bearish, signaling potential short entry or long exit points. "Any Trend Change" provides a combined alert for any trend reversal regardless of direction, allowing traders to be notified of all momentum shifts without setting up separate alerts. These notifications enable traders to capitalize on trend changes and protect positions without continuous chart monitoring.
▶ Color Customization: Five visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, ensuring optimal contrast for identifying bullish versus bearish trends across various trading environments. The adjustable cloud fill transparency control (0-100%) allows fine-tuning of the gradient area prominence between the Supertrend line and price, with higher opacity values creating subtle background context while lower values produce bold trend zone emphasis. Optional bar coloring with adjustable transparency (0-100%) extends the trend color directly to the price bars themselves, providing immediate visual reinforcement of current trend direction without requiring reference to the Supertrend line, with transparency controls allowing users to maintain visibility of candlestick patterns while still showing trend context.
Indicator

Cumulative Volume Delta (CVD) Suite [QuantAlgo]🟢 Overview
The Cumulative Volume Delta (CVD) Suite is a comprehensive toolkit that tracks the net difference between buying and selling pressure over time, helping traders identify significant accumulation/distribution patterns, spot divergences with price action, and confirm trend strength. By visualizing the running balance of volume flow, this indicator reveals underlying market sentiment that often precedes significant price movements.
🟢 How It Works
The indicator begins by determining the optimal timeframe for delta calculation. When auto-select is enabled, it automatically chooses a lower timeframe based on your chart period, e.g., using 1-second bars for minute charts, 5-second bars for 5-minute charts, and progressively larger intervals for higher timeframes. This granular approach captures volume flow dynamics that might be missed at the chart level.
Once the timeframe is established, the indicator calculates volume delta for each bar using directional classification:
getDelta() =>
close > open ? volume : close < open ? -volume : 0
When a bar closes higher than it opens (bullish candle), the entire volume is counted as positive delta representing buying pressure. Conversely, when a bar closes lower than its open (bearish candle), volume becomes negative delta representing selling pressure. This classification is applied to every bar in the selected lower timeframe, then aggregated upward to construct the delta for each chart bar:
array deltaValues = request.security_lower_tf(syminfo.tickerid, lowerTimeframe, getDelta())
float barDelta = 0.0
if array.size(deltaValues) > 0
for i = 0 to array.size(deltaValues) - 1
barDelta := barDelta + array.get(deltaValues, i)
This aggregation process sums all the individual delta values from the lower timeframe bars that comprise each chart bar, capturing the complete volume flow activity within that period. The resulting bar delta then feeds into the various display calculations:
rawCVD = ta.cum(barDelta) // Cumulative sum from chart start
smoothCVD = ta.sma(rawCVD, smoothingLength) // Smoothed for noise reduction
rollingCVD = math.sum(barDelta, rollingLength) // Rolling window calculation
Note: This directional bar approach differs from exchange-level orderflow CVD, which uses tick data to separate aggressive buy orders (executed at the ask price) from aggressive sell orders (executed at the bid price). While this method provides a volume flow approximation rather than pure tape-reading precision, it offers a practical and accessible way to analyze buying and selling dynamics across all timeframes and instruments without requiring specialized data feeds on PulseWire.
🟢 Key Features
The indicator offers five distinct visualization modes, each designed to reveal different aspects of volume flow dynamics and cater to various trading strategies and market conditions.
1. Oscillator (Raw): Displays the true cumulative volume delta from the beginning of chart history, accompanied by an EMA signal line that helps identify trend direction and momentum shifts. When CVD crosses above the signal line, it indicates strengthening buying pressure; crosses below suggest increasing selling pressure. This mode is particularly valuable for spotting long-term accumulation/distribution phases and identifying divergences where CVD makes new highs/lows while price fails to confirm, often signaling potential reversals.
2. Oscillator (Smooth): Applies a simple moving average to the raw CVD to filter out noise while preserving the underlying trend structure, creating smoother signal line crossovers. Use this when trading trending instruments where you need confirmation of genuine volume-backed moves versus temporary volatility spikes.
3. Oscillator (Rolling): Calculates cumulative delta over only the most recent N bars (configurable window length), effectively resetting the baseline and removing the influence of distant historical data. This approach focuses exclusively on current market dynamics, making it highly responsive to recent shifts in volume pressure and particularly useful in markets that have undergone regime changes or structural shifts. This mode can be beneficial for traders when they want to analyze "what's happening now" without legacy bias from months or years of prior data affecting the readings.
4. Histogram: Renders the per-bar volume delta as individual histogram bars rather than cumulative values, showing the immediate buying or selling pressure that occurred during each specific candle. Positive (green) bars indicate that bar closed higher than it opened with buying volume, while negative (red) bars show selling volume dominance. This mode excels at identifying sudden volume surges, exhaustion points where large delta bars fail to move price, and bar-by-bar absorption patterns where one side is aggressively consuming the other's volume.
5. Candles: Transforms CVD data into OHLC candlestick format, where each candle's open represents the CVD at the start of the bar and subsequent intra-bar delta changes create the high, low, and close values. This visualization reveals the internal volume flow dynamics within each time period, showing whether buying or selling pressure dominated throughout the bar's formation and exposing intra-bar reversals or sustained directional pressure. Use candle wicks and bodies to identify volume acceptance/rejection at specific CVD levels, similar to how price candles show acceptance/rejection at price levels.
▶ Built-in Alert System: Comprehensive alerts for all display modes including bullish/bearish momentum shifts (CVD crossing signal line), buying/selling pressure detection (histogram mode), and bullish/bearish CVD candle formations. Fully customizable with exchange and timeframe placeholders.
▶ Visual Customization: Choose from 5 color presets (Classic, Aqua, Cosmic, Ember, Neon) or create your own custom color schemes. Optional price bar coloring feature overlays CVD trend colors directly onto your main chart candles, providing instant visual confirmation of volume flow and making divergences immediately apparent. Optional info label with configurable position and size displays current CVD values, data source timeframe, and mode at a glance.
Indicator

Institutional Confluence Mapper [JOAT]Institutional Confluence Mapper (ICM)
Introduction
The Institutional Confluence Mapper is an open-source multi-factor analysis tool that combines five analytical modules into a unified confluence scoring system. It synthesizes institutional trading concepts including Relative Rotation analysis, Smart Money flow detection, Liquidity zone mapping, Session-based timing, and Volatility regime classification.
Rather than relying on a single indicator, ICM evaluates market conditions through multiple lenses simultaneously, presenting a clear confluence score (0-100%) that reflects the alignment of various market factors.
This script is fully open-source under the Mozilla Public License 2.0.
Originality and Purpose
This indicator is NOT a random mashup of existing indicators. It is an original implementation that creates a unified institutional analysis framework:
Why Multiple Modules? Most retail traders struggle because they rely on single indicators that provide conflicting signals. Institutional traders evaluate markets through multiple frameworks simultaneously. ICM bridges this gap by providing a unified view of complementary analysis methods.
The Confluence Scoring System: Each module contributes to a weighted confluence score (0-100%). Scores above 65% indicate bullish confluence; below 35% indicates bearish confluence.
How Components Work Together:
RRG (Relative Rotation) determines macro bias - is this asset outperforming or underperforming its benchmark?
Institutional Flow confirms smart money activity - are institutions accumulating or distributing?
Volatility Regime determines strategy selection - trend-follow or mean-revert?
Liquidity Detection identifies key levels - where are the stop hunts happening?
Session Analysis optimizes timing - when should you trade?
The Five Core Modules
1. Relative Rotation Momentum Matrix (RRG)
Compares the current symbol against a benchmark (default: SPY) using the JdK RS-Ratio methodology with double-smoothed EMA. Assets rotate through four quadrants:
LEADING: Outperforming with positive momentum (strongest bullish)
WEAKENING: Outperforming but losing momentum
LAGGING: Underperforming with negative momentum (strongest bearish)
IMPROVING: Underperforming but gaining momentum
2. Institutional Flow Analysis
Analyzes volume patterns to detect smart money activity:
Volume Z-Score measures how unusual current volume is
Buy/Sell pressure estimation based on candle structure
Unusual volume detection highlights institutional activity
3. Volatility Regime System
Uses ATR percentile ranking to classify market conditions:
COMPRESSION: Low volatility (ATR < 20th percentile) - potential breakout
EXPANSION: High volatility (ATR > 80th percentile) - trending
TRENDING_BULL/BEAR: Directional trends based on EMA alignment
RANGING: Sideways consolidation
4. Liquidity Detection
Identifies institutional liquidity targets using swing point analysis:
Swing highs/lows are tracked and displayed as dashed lines
Purple dashed lines mark resistance/sell-side liquidity
Teal dashed lines mark support/buy-side liquidity
Gold diamonds appear when liquidity sweeps are detected (potential reversals)
5. Session Momentum Profiler
Tracks trading sessions based on your selected timezone:
Asian Session: 7PM - 4AM EST
London Session: 3AM - 12PM EST
New York Session: 9:30AM - 4PM EST
London/NY Overlap: 8AM - 12PM EST (peak liquidity)
Visual Elements
Main Dashboard (Top-Right):
BIAS: Overall direction with confluence percentage
RRG: Current quadrant and momentum
FLOW: Smart money bias and volume status
REGIME: Market condition and volatility percentile
SESSION: Active trading session and current time
LIQUIDITY: Active zones and grab signals
SIGNAL: Actionable recommendation
Chart Elements:
Gold Diamond: Liquidity grab (potential reversal point)
Teal Dashed Line: Support / Buy-side liquidity zone
Purple Dashed Line: Resistance / Sell-side liquidity zone
EMA 21/55/200: Trend structure with cloud fill
Volatility Bands: ATR-based channels
How to Use
Step 1: Check the BIAS row for overall market direction
Step 2: Check REGIME to understand market conditions
Step 3: Identify key levels using liquidity zones and EMAs
Step 4: Wait for confluence above 65% (bullish) or below 35% (bearish)
Step 5: Look for gold diamond signals at key levels
Best Setups
Bullish: Confluence >65%, RRG in LEADING/IMPROVING, bullish flow, price near teal support zone.
Bearish: Confluence <35%, RRG in LAGGING/WEAKENING, bearish flow, price near purple resistance zone.
Reversal: Gold diamond appears after price sweeps a liquidity zone.
Key Input Parameters
Benchmark Symbol: Compare against (default: SPY)
RS-Ratio/Momentum Lookback: RRG calculation periods
Volume Analysis Period: Flow detection lookback
Swing Length: Liquidity zone detection
ATR Period/Rank Period: Regime classification
Timezone: Session detection timezone
Alerts
Liquidity Grab Bull: Bullish sweep detected
Liquidity Grab Bear: Bearish sweep detected
High Confluence Bull: Confluence above 70%
High Confluence Bear: Confluence below 30%
Best Practices
Use on 1H, 4H, or Daily timeframes for reliable signals
Combine with price action for confirmation
Respect the regime - don't fight strong trends
Trade during London/NY overlap for best liquidity
Wait for high confluence scores before entering
Always use proper risk management
Limitations
Works best on liquid markets with sufficient volume
Session features optimized for forex/crypto markets
RRG requires a valid benchmark symbol
No indicator predicts the future - use proper risk management
Disclaimer
This indicator is for educational and informational purposes only. It is not financial advice. Trading involves substantial risk of loss. Past performance does not guarantee future results.
-Made with passion by officialjackofalltrades
Indicator

TurboRSI Pro [JOAT]TurboRSI Pro - Multi-Length RSI Ensemble with Dynamic Momentum Analysis
Introduction
TurboRSI Pro is an open-source indicator that reimagines the classic RSI by calculating multiple RSI lengths simultaneously and combining them into a single, more reliable momentum reading. Instead of relying on a single RSI period that may lag or produce false signals, this indicator creates an ensemble of RSI values across a configurable range, providing a smoother and more robust momentum assessment.
The indicator is designed for traders who want deeper insight into momentum conditions without the noise that comes from single-period oscillators.
Originality and Purpose
This indicator is NOT a simple RSI with different settings. It is an original implementation that solves a fundamental problem with traditional RSI:
The Problem with Single-Period RSI: Traditional RSI uses a single lookback period (typically 14). The issue is that different market conditions favor different RSI lengths. A 14-period RSI might work well in one market phase but produce false signals in another. There's no "perfect" RSI length that works in all conditions.
The Multi-Length Solution: TurboRSI Pro calculates RSI across a range of lengths (default: 10 to 20) simultaneously, then averages all values to create a composite reading. This ensemble approach filters out period-specific noise while preserving genuine momentum shifts. When multiple RSI lengths agree, the signal is more reliable.
OB/OS Strength Percentage: The indicator tracks how many individual RSI lengths are in overbought or oversold territory. When 100% of lengths are overbought, it's a much stronger signal than when only 50% are. This percentage-based approach is original to this indicator and provides conviction assessment.
Candle Heatmap Innovation: An optional feature colors price bars based on deviation from a 200-bar linear regression line. This shows when price is statistically overextended (HOT/COLD) independent of RSI, providing another layer of analysis.
How the components work together:
Multi-length RSI ensemble provides a more robust momentum reading than single-period RSI
OB/OS Strength percentages quantify how many timeframes agree on the momentum condition
Dynamic channels expand/contract based on momentum strength across all calculated lengths
Candle heatmap adds statistical price deviation context independent of RSI
Core Concept: Multi-Length RSI Ensemble
Traditional RSI uses a single lookback period (typically 14). The problem is that different market conditions favor different RSI lengths. TurboRSI Pro solves this by:
Calculating RSI across a range of lengths (default: 10 to 20)
Averaging all RSI values to create a composite reading
Tracking how many individual RSI lengths are in overbought or oversold territory
Displaying this information as "OB Strength" and "OS Strength" percentages
This approach filters out noise while preserving genuine momentum shifts.
How the Multi-Length RSI Works
The calculation uses an efficient array-based approach:
int N = maxLength - minLength + 1
float diff = nz(srcInput - srcInput )
for i = 0 to N - 1
int len = minLength + i
float alpha = 1.0 / len
float numRma = alpha * diff + (1 - alpha) * array.get(numArr, i)
float denRma = alpha * math.abs(diff) + (1 - alpha) * array.get(denArr, i)
float rsiVal = denRma != 0 ? 50 * numRma / denRma + 50 : 50
avgRSI += rsiVal
Each RSI length is calculated using the RMA (Running Moving Average) formula, then all values are averaged. The result is a composite RSI that responds to momentum changes while filtering out period-specific noise.
Visual Components
1. Multi-Length RSI Line
The main oscillator line displays the averaged RSI value with a gradient color:
Green gradient when RSI is above 50 (bullish momentum)
Red gradient when RSI is below 50 (bearish momentum)
Color intensity increases as RSI approaches extreme levels
2. Dynamic Channels
Two adaptive channel lines track momentum extremes:
Upper Channel: Expands when multiple RSI lengths enter overbought territory
Lower Channel: Expands when multiple RSI lengths enter oversold territory
Channel width indicates momentum strength across all calculated lengths
3. Candle Heatmap
An optional feature that colors price bars based on deviation from a linear regression line:
Red/Orange bars: Price is significantly above the regression line (overextended to upside)
Blue bars: Price is significantly below the regression line (overextended to downside)
Yellow bars: Price is near the regression line (neutral)
The heatmap uses a 200-bar regression calculation to identify when price has deviated significantly from its statistical trend.
4. Reference Lines
Standard RSI reference levels are displayed:
80 and 20: Extreme overbought/oversold
70 and 30: Standard overbought/oversold thresholds
50: Neutral momentum line
5. Background Zones
Shaded areas indicate the percentage of RSI lengths in extreme territory:
Green shading from bottom: Percentage of lengths in overbought
Red shading from top: Percentage of lengths in oversold
Dashboard Panel
The dashboard displays real-time analysis in a 7-row table:
RSI Value: Current composite RSI reading (large text for visibility)
Momentum: Current state - OVERBOUGHT, OVERSOLD, BULLISH, BEARISH, or NEUTRAL
OB Strength: Percentage of RSI lengths currently above the overbought threshold
OS Strength: Percentage of RSI lengths currently below the oversold threshold
Heat Level: Current price deviation state - HOT, WARM, NEUTRAL, COOL, or COLD
Trend Bias: Overall trend assessment based on RSI level and channel direction
Optional Stochastic RSI
When enabled, an additional Stochastic RSI line is plotted. This applies the stochastic formula to the RSI itself, providing another layer of momentum analysis. The Stochastic RSI is more sensitive to short-term momentum shifts.
Input Parameters
RSI Settings:
Min RSI Length: Starting length for the RSI range (default: 10)
Max RSI Length: Ending length for the RSI range (default: 20)
Source: Price source for calculation (default: ohlc4)
Overbought: Upper threshold (default: 70)
Oversold: Lower threshold (default: 30)
Candle Heatmap:
Enable Heatmap: Toggle bar coloring on/off (default: enabled)
Regression Length: Lookback for linear regression calculation (default: 200)
Display:
Show Dashboard: Toggle the information panel (default: enabled)
Show Dynamic Channels: Toggle channel lines (default: enabled)
Show Stochastic RSI: Toggle additional Stoch RSI line (default: disabled)
Colors:
Bullish: Color for bullish conditions (default: teal)
Bearish: Color for bearish conditions (default: red)
Neutral: Color for neutral conditions (default: gray)
How to Use TurboRSI Pro
Identifying Momentum Shifts:
Watch for RSI crossing above 50 for bullish momentum confirmation
Watch for RSI crossing below 50 for bearish momentum confirmation
Use the gradient color to quickly assess momentum direction
Using OB/OS Strength:
When OB Strength reaches 100%, all RSI lengths are overbought - strong reversal potential
When OS Strength reaches 100%, all RSI lengths are oversold - strong bounce potential
Partial readings (e.g., 50%) indicate mixed conditions across timeframes
Heatmap Analysis:
HOT readings combined with high RSI suggest overextension - caution for longs
COLD readings combined with low RSI suggest oversold conditions - watch for reversal
Use heatmap divergence from RSI for additional confirmation
Channel Interpretation:
Expanding upper channel with rising RSI confirms strong bullish momentum
Expanding lower channel with falling RSI confirms strong bearish momentum
Channel contraction suggests momentum is weakening
Alert Conditions
Six alert conditions are available:
RSI Overbought: RSI crosses above overbought threshold
RSI Oversold: RSI crosses below oversold threshold
RSI Bullish Cross: RSI crosses above 50
RSI Bearish Cross: RSI crosses below 50
All RSI Overbought: Every RSI length is in overbought territory
All RSI Oversold: Every RSI length is in oversold territory
Best Practices
Use on higher timeframes (1H, 4H, Daily) for more reliable signals
Combine with price action analysis - RSI confirms, it does not predict
Pay attention to OB/OS Strength percentages for conviction assessment
The heatmap works best on assets with clear trending behavior
Adjust min/max RSI lengths based on your trading style - wider range for smoother signals
Limitations
Like all oscillators, can remain in overbought/oversold territory during strong trends
The heatmap regression may lag during rapid price movements
Multi-length calculation requires more processing than single RSI
Best suited for swing trading and position trading timeframes
Technical Notes
This indicator is written in Pine Script v6 and uses:
Array-based calculations for efficient multi-length RSI computation
Linear regression for heatmap deviation analysis
Gradient coloring for intuitive visual feedback
State management for dynamic channel calculations
The source code is open and available for review and modification.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Trading involves substantial risk of loss. Past performance does not guarantee future results. Always conduct your own analysis and use proper risk management.
-Made with passion by officialjackofalltrades Indicator

RSI Trend Authority [JOAT]RSI Trend Authority - VAR-RSI with OTT Trend Detection System
Introduction
RSI Trend Authority is an open-source overlay indicator that combines Variable Index Dynamic Average (VAR) smoothed RSI with the Optimized Trend Tracker (OTT) to create a complete trend detection and signal generation system. Unlike traditional RSI which oscillates in a separate pane, this indicator scales the RSI to price and overlays it directly on your chart, making trend analysis more intuitive.
The indicator generates clear BUY and SELL signals when the smoothed RSI crosses the OTT trailing stop line, providing actionable entry points with trend confirmation.
Originality and Purpose
This indicator is NOT a simple mashup of RSI and moving averages. It is an original implementation that transforms RSI into a trend-following overlay system:
Why VAR Smoothing? Traditional RSI is noisy and produces many false signals. The Variable Index Dynamic Average (VAR) is an adaptive smoothing algorithm based on the Chande Momentum Oscillator principle. It adjusts its smoothing factor based on market conditions - responding quickly during trends and smoothing out during choppy markets. This creates an RSI that filters noise while preserving genuine momentum shifts.
Why OTT Trailing Stop? The Optimized Trend Tracker (OTT) is a percentage-based trailing stop mechanism that only moves in the direction of the trend. When VAR-RSI crosses above OTT, a bullish trend is confirmed; when it crosses below, a bearish trend is confirmed. This provides clear, actionable signals rather than subjective interpretation.
Price Scaling Innovation: By scaling RSI (0-100) to price using the formula (RSI * close / 50), the indicator overlays directly on the price chart. This allows traders to see how momentum relates to actual price levels, making trend analysis more intuitive than a separate oscillator pane.
ATR Boundaries: Optional volatility-based boundaries show when price is extended relative to its normal range, helping identify potential reversal zones.
How the components work together:
VAR smoothing removes RSI noise while preserving trend information
OTT provides a dynamic trailing stop that generates clear crossover signals
Price scaling allows direct overlay on the chart for intuitive analysis
ATR boundaries add volatility context for profit target estimation
Core Components
1. VAR-RSI (Variable Index Dynamic Average RSI)
The foundation of this indicator is the VAR smoothing algorithm applied to RSI. VAR is an adaptive moving average that adjusts its smoothing factor based on the Chande Momentum Oscillator principle:
f_var_calc(float data, int length) =>
int a = 9
float b = data > nz(data ) ? data - nz(data ) : 0.0
float c = data < nz(data ) ? nz(data ) - data : 0.0
float d = math.sum(b, a)
float e = math.sum(c, a)
float f = nz((d - e) / (d + e))
float g = math.abs(f)
float h = 2.0 / (length + 1)
float x = ta.sma(data, length)
This creates an RSI that:
Responds quickly during trending conditions
Smooths out during choppy, sideways markets
Reduces false signals compared to raw RSI
2. OTT (Optimized Trend Tracker)
The OTT acts as a dynamic trailing stop that follows the VAR-RSI:
In uptrends, OTT trails below the VAR-RSI line
In downtrends, OTT trails above the VAR-RSI line
The OTT Percent parameter controls how closely it follows
When VAR-RSI crosses above OTT, a bullish trend is confirmed. When VAR-RSI crosses below OTT, a bearish trend is confirmed.
3. Price Scaling
The RSI (0-100 scale) is converted to price scale using:
float scaleFactor = close / 50.0
float varRSIScaled = varRSI * scaleFactor
This allows the indicator to overlay directly on price, showing how momentum relates to actual price levels.
Visual Components
VAR-RSI Line (Cyan/Magenta)
The main indicator line with gradient coloring:
Cyan gradient when RSI is above 50 (bullish)
Magenta gradient when RSI is below 50 (bearish)
Line thickness of 3 for clear visibility
OTT Line (Yellow Circles)
The trailing stop line displayed as circles:
Acts as dynamic support in uptrends
Acts as dynamic resistance in downtrends
Crossovers generate trading signals
Trend Fill
The area between VAR-RSI and OTT is filled:
Cyan fill during bullish trends
Magenta fill during bearish trends
Fill transparency allows price visibility
Buy position and LONG on Dashboard with a Uptrend:
ATR Boundaries (Optional)
Dotted lines showing volatility-based price boundaries:
Upper band: Close + (ATR x Multiplier)
Lower band: Close - (ATR x Multiplier)
Color matches current trend direction
Buy/Sell Signals
Clear labels appear at signal points:
BUY label below bar when VAR-RSI crosses above OTT
SELL label above bar when VAR-RSI crosses below OTT
Additional glow circles highlight signal bars
Bar Coloring
Optional feature that colors price bars:
Cyan bars during bullish trend
Magenta bars during bearish trend
Dashboard Panel
The 8-row dashboard provides comprehensive status information:
Signal: Current position - LONG or SHORT (large text)
VAR-RSI: Current smoothed RSI value (large text)
RSI State: OVERBOUGHT, OVERSOLD, BULLISH, or BEARISH
OTT Trend: UPTREND or DOWNTREND based on OTT direction
Bars Since: Number of bars since last signal
Price: Current close price (large text)
OTT Level: Current OTT trailing stop value
Input Parameters
RSI Settings:
RSI Length: Period for RSI calculation (default: 100)
Source: Price source (default: close)
VAR Settings:
VAR Length: Adaptive smoothing period (default: 50)
OTT Settings:
OTT Period: Trailing stop calculation period (default: 30)
OTT Percent: Distance percentage for trailing stop (default: 0.2)
ATR Trend Boundaries:
Show ATR Boundaries: Toggle visibility (default: enabled)
ATR Length: Period for ATR calculation (default: 14)
ATR Multiplier: Distance multiplier (default: 2.0)
Display Options:
Show Buy/Sell Signals: Toggle signal labels (default: enabled)
Show Status Table: Toggle dashboard (default: enabled)
Table Position: Choose corner placement
Color Bars by Trend: Toggle bar coloring (default: enabled)
Color Scheme:
Bullish Color: Main bullish color (default: cyan)
Bearish Color: Main bearish color (default: magenta)
OTT Line: Trailing stop color (default: yellow)
VAR-RSI Line: Main line color (default: teal)
ATR colors for boundaries
How to Use RSI Trend Authority
Signal-Based Trading:
Enter LONG when BUY signal appears (VAR-RSI crosses above OTT)
Enter SHORT when SELL signal appears (VAR-RSI crosses below OTT)
Use the OTT line as a trailing stop reference
Trend Confirmation:
Cyan fill indicates bullish trend - favor long positions
Magenta fill indicates bearish trend - favor short positions
Check RSI State in dashboard for momentum context
Using the Dashboard:
Monitor "Bars Since" to assess signal freshness
Check RSI State for overbought/oversold warnings
Use OTT Level as a reference for stop placement
ATR Boundaries:
Price near upper ATR band in uptrend suggests extension
Price near lower ATR band in downtrend suggests extension
Boundaries help identify potential reversal zones
Parameter Optimization
For Faster Signals:
Decrease RSI Length (try 50-80)
Decrease VAR Length (try 30-40)
Decrease OTT Period (try 15-25)
For Smoother Signals:
Increase RSI Length (try 120-150)
Increase VAR Length (try 60-80)
Increase OTT Period (try 40-50)
For Tighter Stops:
Decrease OTT Percent (try 0.1-0.15)
For Wider Stops:
Increase OTT Percent (try 0.3-0.5)
Alert Conditions
Three alert conditions are available:
Buy Signal: VAR-RSI crosses above OTT
Sell Signal: VAR-RSI crosses below OTT
Trend Change: OTT direction changes
Understanding the OTT Calculation
The OTT uses a percentage-based trailing mechanism:
float farkOTT = mavgOTT * ottPercent * 0.01
float longStopCalc = mavgOTT - farkOTT
float shortStopCalc = mavgOTT + farkOTT
longStop := mavgOTT > nz(longStop ) ? math.max(longStopCalc, nz(longStop )) : longStopCalc
shortStop := mavgOTT < nz(shortStop ) ? math.min(shortStopCalc, nz(shortStop )) : shortStopCalc
This ensures the trailing stop only moves in the direction of the trend, never against it.
Best Practices
Use on 1H timeframe or higher for more reliable signals
Wait for signal confirmation before entering trades
Consider RSI State when evaluating signal quality
Use ATR boundaries for profit target estimation
The longer RSI length (100) provides smoother trend detection
Combine with support/resistance analysis for better entries
Limitations
Signals may lag during rapid price movements due to smoothing
Works best in trending markets; may whipsaw in ranges
The overlay nature means RSI values are scaled, not absolute
Default parameters are optimized for crypto and forex; adjust for other markets
Technical Notes
This indicator is written in Pine Script v6 and uses:
VAR (Variable Index Dynamic Average) for adaptive smoothing
OTT (Optimized Trend Tracker) for trailing stop calculation
ATR for volatility-based boundaries
Gradient coloring for intuitive trend visualization
The source code is open and available for review and modification.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Trading involves substantial risk of loss. Past performance does not guarantee future results. Always conduct your own analysis and use proper risk management.
-Made with passion by officialjackofalltrades Indicator

Red Bull Wings [JOAT]RED BULL WINGS - Bullish-Only Institutional Overlay
Introduction and Purpose
RED BULL WINGS is an open-source overlay indicator that combines five distinct bullish detection methods into a single composite scoring system. The core problem this indicator solves is that individual bullish signals (patterns, volume, zones, trendlines) often disagree or fire in isolation. A bullish engulfing pattern means little if volume is weak and price is far from support. Traders need confluence across multiple dimensions to identify high-probability setups.
This indicator addresses that by scoring each bullish component separately, then combining them into a weighted WINGS score (0-100) that reflects overall bullish conviction. When multiple components align, the score rises; when they disagree, the score stays low.
Why These Five Modules Work Together
Each module measures a different aspect of bullish market structure:
1. Module A - Bullish Candlestick Engine - Detects classic reversal patterns (engulfing, marubozu, hammer, 3-bar cluster). These patterns identify WHERE buyers are stepping in.
2. Module B - PVSRA Volume Climax - Measures spread x volume to detect institutional participation. This tells you WHETHER smart money is involved.
3. Module C - Demand Zone Detection - Identifies and tracks order block zones where buyers previously overwhelmed sellers. This shows you WHERE institutional support exists.
4. Module D - Trendline Channel - Builds dynamic support/resistance from pivot points. This reveals the STRUCTURE of the current trend.
5. Module E - Ichimoku Assist - Optional filter using Tenkan/Kijun cross, cloud position, and Chikou confirmation. This provides TREND PERMISSION context.
The combination works because:
Patterns alone can fail without volume confirmation
Volume alone means nothing without price structure context
Zones alone are static without pattern/volume triggers
Trendlines alone miss the micro-level entry timing
When 3+ modules agree, the probability of a valid bullish setup increases significantly
How the Calculations Work
Module A - Pattern Detection:
Bullish Engulfing - Current bullish bar completely engulfs prior bearish bar:
bool engulfingCond = isBullish() and
isBearish() and
open <= close and
close >= open and
bodySize() > bodySize()
Marubozu - Strong body with minimal wicks (body >= 1.8x average, wick ratio < 20%):
float wickRatio = candleRange() > 0 ? (upperWick() + lowerWick()) / candleRange() : 0
bool marubozuCond = isBullish() and
bodySize() >= bodySizeAvg * i_maruMult and
wickRatio < i_wickRatioMax
Hammer - Long lower wick (>= 2.5x body), close in upper third, volume confirmation:
bool hammerWick = lowerWick() >= i_hammerWickMult * bodySize()
bool hammerClose = close >= low + (candleRange() * 0.66)
bool hammerVol = volume >= i_pvsraRisingMult * volAvg
3-Bar Cluster - Three consecutive bullish closes with increasing prices and volume spike:
bool threeBarBullish = isBullish() and isBullish() and isBullish()
bool increasingCloses = close > close and close > close
bool volSpike3Bar = volume >= i_pvsraRisingMult * volAvg or
volume >= i_pvsraRisingMult * volAvg
Module B - PVSRA Volume Analysis:
Uses spread x volume to detect climax conditions:
float spreadVol = candleRange() * volume
float maxSpreadVol = ta.highest(spreadVol, ADJ_PVSRA_LOOKBACK)
bool volClimax = volume >= i_pvsraClimaxMult * volAvg or spreadVol >= maxSpreadVol
bool volRising = volume >= i_pvsraRisingMult * volAvg and volume < i_pvsraClimaxMult * volAvg
Volume only scores when the candle is bullish, preventing false signals on bearish volume spikes.
Module C - Demand Zone Detection:
Identifies zones using a two-candle structure:
// Small bearish candle A followed by larger bullish candle B
bool candleA_bearish = isBearish()
bool candleB_bullish = isBullish()
bool newZoneCond = candleA_bearish and candleB_bullish and
candleB_size >= i_zoneSizeMult * candleA_size
Zones are drawn as rectangles and tracked for retests. Score increases when price is near or inside an active zone, with bonus points for rejection candles.
Module D - Trendline Channel:
Builds dynamic channel from confirmed pivot points:
float ph = ta.pivothigh(high, i_pivotLeft, i_pivotRight)
float pl = ta.pivotlow(low, i_pivotLeft, i_pivotRight)
Pivots are stored and connected to form upper/lower channel lines. The indicator detects breakouts when price closes beyond the channel with volume confirmation.
Module E - Ichimoku Assist:
Standard Ichimoku calculations with bullish scoring:
float tenkan = (ta.highest(high, i_tenkanLen) + ta.lowest(low, i_tenkanLen)) / 2
float kijun = (ta.highest(high, i_kijunLen) + ta.lowest(low, i_kijunLen)) / 2
bool tkCross = ta.crossover(tenkan, kijun)
bool priceAboveCloud = close > cloudTop
bool chikouAbovePrice = chikou > close
Module F - WINGS Composite Score:
All module scores are combined using adjustable weights:
float WINGS_score = 100 * (nW_pattern * S_pattern +
nW_volume * S_vol +
nW_zone * S_zone +
nW_trend * S_trend +
nW_ichi * S_ichi)
Default weights: Pattern 30%, Volume 25%, Zone 20%, Trend 15%, Ichimoku 10%.
Signal Thresholds
WATCH (30-49) - Interesting bullish context forming, not yet actionable
MOMENTUM (50-74) - Strong bullish conditions, multiple modules agreeing
LIFT-OFF (75+) - High-confidence bullish confluence across most modules
WINGS Badge (Dashboard)
The right-side panel displays:
WINGS Score - Current composite score (0-100)
Pattern - Active pattern name and strength, or neutral placeholder
Volume - Normal / Rising / CLIMAX status
Zone - ACTIVE if price is near a demand zone
Trend - Channel position or BREAK status
Ichimoku - OFF / Weak / Bullish / STRONG
Status - Overall signal level (Neutral / WATCH / MOMENTUM / LIFT-OFF)
Input Parameters
Module Toggles:
Enable Bullish Patterns (true) - Toggle pattern detection
Enable PVSRA Volume (true) - Toggle volume analysis
Enable Order Blocks (true) - Toggle demand zone detection
Enable Trendlines (true) - Toggle pivot channel
Enable Ichimoku Assist (false) - Toggle Ichimoku filter (off by default for performance)
Enable Visual Effects (false) - Toggle labels, trails, and visual elements
LIVE MODE (false) - Enable intrabar signals (WARNING: signals may repaint)
Pattern Engine:
Pattern Lookback (5) - Bars for body size averaging
Marubozu Body Multiplier (1.8) - Minimum body size vs average
Hammer Wick Multiplier (2.5) - Minimum lower wick vs body
Max Wick Ratio (0.2) - Maximum wick percentage for marubozu
Volume / PVSRA:
PVSRA Lookback (10) - Period for volume averaging
Climax Multiplier (2.0) - Volume threshold for climax detection
Rising Volume Multiplier (1.5) - Volume threshold for rising detection
Order Blocks:
Zone Size Multiplier (2.0) - Minimum bullish candle size vs bearish
Zone Extend Bars (200) - How far zones project forward
Max Zones (12) - Maximum active zones displayed
Remove Zone on Close Below (true) - Delete broken zones
Trendlines:
Pivot Left/Right Bars (3/3) - Pivot detection sensitivity
Min Slope % (0.25) - Minimum trendline angle
Max Trendlines (5) - Maximum pivot points stored
Trendline Projection Bars (60) - Forward projection distance
Ichimoku:
Tenkan Length (9) - Conversion line period
Kijun Length (26) - Base line period
Senkou B Length (52) - Leading span B period
Displacement (26) - Cloud displacement
WINGS Score:
Weight: Pattern (0.30) - Pattern contribution to score
Weight: Volume (0.25) - Volume contribution to score
Weight: Zone (0.20) - Zone contribution to score
Weight: Trend (0.15) - Trendline contribution to score
Weight: Ichimoku (0.10) - Ichimoku contribution to score
Lift-Off Threshold (75) - Score required for LIFT-OFF signal
Momentum Watch Threshold (50) - Score required for MOMENTUM signal
Visuals:
Signal Cooldown (8) - Minimum bars between labels
Show WINGS Score Badge (true) - Toggle dashboard
Show Wing Combos (true) - Show DOUBLE/MEGA WINGS streaks
Red Background Wash (true) - Tint chart background
Show Lift-Off Trails (false) - Toggle golden trail visuals
How to Use This Indicator
For Bullish Entry Identification:
1. Monitor the WINGS badge for score changes
2. Wait for MOMENTUM (50+) or LIFT-OFF (75+) signals
3. Check which modules are contributing (Pattern + Volume + Zone = stronger)
4. Use demand zones and trendlines as structural reference for entries
For Confluence Confirmation:
1. Use alongside your existing analysis
2. LIFT-OFF signals indicate multiple bullish factors aligning
3. Low scores (< 30) suggest weak bullish context even if one factor looks good
For Zone-Based Trading:
1. Watch for price approaching active demand zones
2. Look for pattern + volume confirmation at zone retests
3. Zone score increases with successful retests
For Trendline Analysis:
1. Monitor the pivot-based channel for trend structure
2. Breakouts with volume confirmation trigger TREND BREAK alerts
3. Price inside channel with bullish patterns = trend continuation setup
1M and lower timeframes:
Alerts Available
LIFT-OFF - High-confidence bullish confluence
MOMENTUM - Strong bullish conditions
Zone Retest - Bullish rejection from demand zone
Trendline Break - Breakout with volume confirmation
Individual patterns (Engulfing, Marubozu, Hammer, 3-Bar Cluster)
Volume Climax - Institutional volume spike
DOUBLE WINGS / MEGA WINGS - Consecutive lift-off signals
Repainting Behavior
By default, the indicator uses confirmed bars only (barstate.isconfirmed), meaning signals appear after the bar closes and do not repaint. However:
LIVE MODE - When enabled, signals can appear intrabar but may disappear if conditions change before bar close. A warning label displays when LIVE MODE is active.
Trendlines - Pivot detection requires lookback bars, so the most recent trendline segments may adjust as new pivots confirm. This is inherent to pivot-based analysis.
Demand Zones - Zones are created on confirmed bars and do not repaint, but they can be removed if price closes below the zone bottom (configurable).
Live Mode with 'Enable Visual Effect' turned off in settings:
Limitations
This is a bullish-only indicator. It does not detect bearish setups or provide short signals.
The WINGS score is a confluence measure, not a prediction. High scores indicate favorable conditions, not guaranteed outcomes.
Pattern detection uses simplified logic. Not all candlestick nuances are captured.
Volume analysis requires reliable volume data. Results may vary on instruments with inconsistent volume reporting.
Ichimoku calculations add processing overhead. Disable if not needed.
Demand zones are based on a specific two-candle structure. Other valid zones may not be detected.
Trendlines use linear regression between pivots. Curved or complex channels are not supported.
Timeframe Recommendations
15m-1H: More frequent signals, useful for intraday analysis. Higher noise.
4H-Daily: Best balance of signal quality and frequency for swing trading.
Weekly: Fewer but more significant signals for position trading.
Adjust lookback periods and thresholds based on your timeframe. Shorter timeframes may benefit from shorter lookbacks.
Open-Source and Disclaimer
This script is published as open-source under the Mozilla Public License 2.0 for educational purposes. The source code is fully visible and can be studied to understand how each module works.
This indicator does not constitute financial advice. The WINGS score and signals do not guarantee profitable trades. Past performance does not guarantee future results. Always use proper risk management, position sizing, and stop-losses. Test thoroughly on your preferred instruments and timeframes before using in live trading.
- Made with passion by officialjackofalltrades
Indicator
